# README

## Static Sites

* Built by MkDocs & CF Pages: <https://ferro-tech.pages.dev> or <https://notes.ferro.pro/>
* Built by gitbook: <https://book.ferro.pro/>

view on [github](https://github.com/fzinfz/book) or [vscode](https://github1s.com/fzinfz/book) if unexpected html rendering

## Home

Visit home for more: <https://ferro.pro/>


# DevOps

* [UI](#ui)
  * [Grafana - TS + Go](#grafana---ts--go)
* [Monitoring](#monitoring)
  * [Prometheus - Go + TS](#prometheus---go--ts)
  * [InfluxDB Telegraf](#influxdb-telegraf)
  * [Grafana Promtail](#grafana-promtail)
  * [Zabbix - C/PHP/JAVA](#zabbix---cphpjava)
    * [server - Docker](#server---docker)
    * [agent](#agent)
  * [Nagios - C](#nagios---c)
    * [Docker](#docker)
  * [Elastic](#elastic)
    * [Beats - Go](#beats---go)
  * [Cacti - PHP](#cacti---php)
    * [alert](#alert)
  * [TICK stack](#tick-stack)
  * [Pandora FMS - PHP/Perl](#pandora-fms---phpperl)
  * [open-falcon - Go + Python Flask](#open-falcon---go--python-flask)
  * [Munin - Perl/Shell](#munin---perlshell)
  * [netdata - C/Python/JS/Shell](#netdata---cpythonjsshell)
* [Management](#management)
  * [Fabric - Python library](#fabric---python-library)
  * [invoke - Python library](#invoke---python-library)
  * [Terraform](#terraform)
  * [Ansible - Python](#ansible---python)
  * [Puppet - Ruby](#puppet---ruby)
  * [Chef - Ruby](#chef---ruby)
  * [SaltStack - Python](#saltstack---python)
* [CI](#ci)
  * [Jenkins - JAVA](#jenkins---java)
  * [Travis - Ruby/JS](#travis---rubyjs)
* [SNMP](#snmp)
* [More](#more)

## UI

### Grafana - TS + Go

<https://github.com/grafana/grafana>

* Search dashboards & copy ID to /dashboard/import: <https://grafana.com/grafana/dashboards/>
* no login: <https://grafana.com/docs/grafana/latest/setup-grafana/configure-security/configure-authentication/grafana/#anonymous-authentication>

  ```
  [auth.anonymous]
  enabled = true
  org_name = Main Org.
  org_role = Viewer
  hide_version = true # default: false
  ```

## Monitoring

<https://en.wikipedia.org/wiki/Comparison\\_of\\_network\\_monitoring\\_systems>

### Prometheus - Go + TS

<https://github.com/prometheus/prometheus\\>
Grafana: <https://grafana.com/grafana/dashboards/1860-node-exporter-full/> | {url}?var-node=

### InfluxDB Telegraf

<https://www.influxdata.com/blog/getting-started-with-influxdb-2-0-scraping-metrics-running-telegraf-querying-data-and-writing-data/>

### Grafana Promtail

agent : local logs -> [loki](/db/loki) : <https://grafana.com/docs/loki/latest/clients/promtail/>

### Zabbix - C/PHP/JAVA

<https://github.com/zabbix/zabbix>

#### server - Docker

<https://www.zabbix.com/documentation/4.0/manual/installation/containers>

```
docker run --name zabbix-appliance -t \
    -p 10051:10051 \
    -p 8083:80 \
    -d zabbix/zabbix-appliance:latest
# Default login: Admin/zabbix
```

#### agent

```
Active : zabbix_agentd: active checks ->  zabbix_server: trapper  :10051  
    ServerActive=
    
Passive: zabbix_server: poller        ->  zabbix_agentd: listener :10050\
    Server=

# Windows agent, run under admininstrator cmd
zabbix_agentd.exe --config zabbix_agentd.win.conf --install

# Debian/Ubuntu
apt install zabbix-agent
service zabbix-agent start
```

### Nagios - C

<https://github.com/NagiosEnterprises/nagioscore\\>
<https://github.com/centreon/centreon\\>
<https://github.com/NagVis/nagvis>

#### Docker

<https://hub.docker.com/r/jasonrivers/nagios/>

```
docker run --name nagios4 --rm -it -p 0.0.0.0:8082:80 jasonrivers/nagios:latest

docker cp nagios4:/opt/nagios/etc ./nagios/etc
docker cp nagios4:/opt/nagios/var ./nagios/var
docker cp nagios4:/opt/nagiosgraph/etc ./nagios/graph_etc
docker cp nagios4:/opt/nagiosgraph/var ./nagios/graph_var

docker run --name nagios4  \
-d --restart unless-stopped \
-v $PWD/nagios/etc/:/opt/nagios/etc/ \
-v $PWD/nagios/var:/opt/nagios/var/ \
-v $PWD/nagios/graph_etc:/opt/nagiosgraph/etc \
-v $PWD/nagios/graph_var:/opt/nagiosgraph/var \
-v $PWD/nagios/custom-plugins:/opt/Custom-Nagios-Plugins \
-p 8082:80 jasonrivers/nagios:latest

docker exec -it nagios4 htpasswd /opt/nagios/etc/htpasswd.users nagiosadmin 
docker exec -it nagios4 cat /opt/nagios/etc/objects/contacts.cfg
docker exec -it nagios4 grep ^cfg_ /opt/nagios/etc/nagios.cfg
docker restart nagios4 && docker logs nagios4

# nrpe
NAGIOS_SERVER=1.2.3.4
docker run -d --restart unless-stopped \
    -v /:/rootfs:ro -v /var/run:/var/run:rw -v /sys:/sys:ro \
    -v /var/lib/docker/:/var/lib/docker:ro \
    --privileged --net=host --ipc=host --pid=host \
    -e NAGIOS_SERVER="$NAGIOS_SERVER" \
    --name nagios_nrpe \
    mikenowak/nrpe
```

### Elastic

#### Beats - Go

<https://www.elastic.co/products/beats\\>
<https://github.com/elastic/beats>

```
Filebeat    Log Files Beats
Metricbeat  Metrics Beats
Packetbeat  Network Data Beats
Winlogbeat  Windows Event Logs Beats
Auditbeat   Audit Data Beats
Heartbeat   Uptime Monitoring
```

### Cacti - PHP

<https://github.com/Cacti/cacti>

<https://hub.docker.com/r/smcline06/cacti>

```
docker pull smcline06/cacti:latest
```

#### alert

<https://github.com/Yelp/elastalert> <https://github.com/sirensolutions/sentinl>

<https://sematext.com/blog/x-pack-alternatives/>

### TICK stack

<https://gist.github.com/travisjeffery/43f424fbd7ac677adbba304cef6eb58f>

| Component  | Role           |
| ---------- | -------------- |
| Telegraf   | Data collector |
| InfluxDB   | Stores data    |
| Chronograf | Visualizer     |
| Kapacitor  | Alerter        |

### Pandora FMS - PHP/Perl

<https://github.com/pandorafms/pandorafms#screenshots>

```
# Auto docker
curl -sSL http://pandorafms.org/getpandora  | sh  # Auto, or manually below

# Manually
docker run \
    --name pandora-mysql \
    -e MYSQL_ROOT_PASSWORD=AVeryStrongRootPassword \
    -e MYSQL_DATABASE=pandora \
    -e MYSQL_USER=pandora \
    -e MYSQL_PASSWORD=pandora
    -d pandorafms/pandorafms-mysql:6

docker run -p 41121:41121 \
    --link pandora-mysql:mysql \
    -d pandorafms/pandorafms-server:6

docker run \
    -p 80:80 -p 8022:8022 -p 8023:8023 \
    --link pandora-mysql:mysql \
    -d pandorafms/pandorafms-console:6

apt install -y pandorafms-agent
```

### open-falcon - Go + Python Flask

<https://github.com/open-falcon/falcon-plus/tree/master/docker\\>
v0.3: May 30, 2019

<https://github.com/open-falcon/falcon-plus/blob/master/docker/README.md>

### Munin - Perl/Shell

networked resource monitoring tool\
<http://munin-monitoring.org/\\>
<http://guide.munin-monitoring.org/en/latest/tutorial/index.html>

### netdata - C/Python/JS/Shell

<https://github.com/firehol/netdata> (with screenshots)\
<https://github.com/firehol/netdata/wiki/Installation>

```
bash <(curl -Ss https://my-netdata.io/kickstart-static64.sh) 
```

## Management

### Fabric - Python library

<https://github.com/fabric/fabric\\>
Fabric is a high level Python (2.7, 3.4+) library designed to execute shell commands remotely over SSH, yielding useful Python objects in return.

Fabric (1.x and earlier) was a hybrid project implementing two feature sets: task execution (organization of task functions, execution of them via CLI, and local shell commands) and high level SSH actions (organization of servers/hosts, remote shell commands, and file transfer).

### invoke - Python library

<https://github.com/pyinvoke/invoke\\>
When planning Fabric 2.x, having the “local” feature set as a standalone library made sense, and it seemed plausible to design the SSH component as a separate layer above. Thus, Invoke was created to focus exclusively on local and abstract concerns, leaving Fabric 2.x concerned only with servers and network commands.

### Terraform

* <https://github.com/hashicorp/terraform>
* Self Managed, always free: <https://developer.hashicorp.com/terraform/downloads>

### Ansible - Python

<https://github.com/fzinfz/ansible>

### Puppet - Ruby

<https://hub.docker.com/u/puppet/\\>
<https://puppet.com/products/why-puppet/puppet-enterprise-and-open-source-puppet>

### Chef - Ruby

<https://hub.docker.com/r/chef/chef/>

### SaltStack - Python

<https://github.com/saltstack/salt\\>
<https://hub.docker.com/r/saltstack/>

Agentless: <https://docs.saltstack.com/en/latest/topics/ssh/index.html>

## CI

### Jenkins - JAVA

<https://github.com/jenkinsci/jenkins> ![](https://jenkins.io/images/blueocean/blueocean-successful-pipeline.png)

<https://github.com/jenkinsci/docker/blob/master/README.md#usage>

```
docker run -d -p 8089:8080 -p 50000:50000 jenkins/jenkins:lts
docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword

docker run jenkins/jnlp-slave -url http://jenkins-server:port <secret> <agent name>
```

<https://wiki.jenkins.io/pages/viewpage.action?pageId=75893612>

```
Open a browser on the slave machine and go to the Jenkins master server url (http://yourjenkinsmaster:8080).
Go to Manage Jenkins > Manage Nodes, Click on the newly created slave machine. You will need to login as someone that has the "Connect" Slave permission if you have configured global security.
Click on the Launch button to launch agent from browser on slave.
```

run on all nodes: elastic-axis

### Travis - Ruby/JS

<https://github.com/travis-ci/travis-ci>

## SNMP

<https://en.wikipedia.org/wiki/Simple\\_Network\\_Management\\_Protocol>

v1: Authentication of clients is performed only by a "community string", in effect a type of password, which is transmitted in cleartext.\
v2c comprises SNMPv2 without the controversial new SNMP v2 security model, using instead the simple community-based security scheme of SNMPv1. incompatible with SNMPv1 in two key areas: message formats and protocol operations.\
v2u: greater security than SNMPv1, but without incurring the high complexity of SNMPv2.\
v3 primarily added security and remote configuration enhancements to SNMP.

the agent connects to the server on port 162\
port 161 on the agent side is used for queries

![](https://upload.wikimedia.org/wikipedia/commons/thumb/2/26/SNMP_communication_principles_diagram.PNG/1000px-SNMP_communication_principles_diagram.PNG)

## More

<https://github.com/bregman-arie/devops-resources#devops-tooling>


# Grafana\_Cloud

* [Price](#price)
* [Grafana](#grafana)
* [Loki Logs](#loki-logs)
* [Tempo Traces](#tempo-traces)
* [k6 Testing](#k6-testing)
* [Pyroscope Profiles](#pyroscope-profiles)

## Price

<https://grafana.com/pricing/>

* Free: Grafana + Loki + Tempo + K6 + Pyroscope | 10k c
* Pro: Prometheus + Graphite + Alerts

## Grafana

* Free 3 Monthly Active Users

Grafana Agent Role: `grafana.grafana.grafana_agent`

* <https://github.com/grafana/grafana-ansible-collection/blob/main/examples/monitor-multiple-instances.md>

## Loki Logs

* Free 50 GB Logs

## Tempo Traces

Free 50 GB Traces

## k6 Testing

* Free 500 k6 Virtual User Hours
* <https://k6.io/docs/#what-is-k6>

## Pyroscope Profiles

* Free 50 GB Profiles

![](https://grafana.com/img/pyroscope_agent_server_diag.png)


# OS\_depoly

* [netboot.xyz](#netbootxyz)
* [iVentoy](#iventoy)

## netboot.xyz

<https://github.com/netbootxyz/netboot.xyz?tab=readme-ov-file#operating-systems>

## iVentoy

* Free vs Paid: <https://www.iventoy.com/en/doc\\_edition.html>
* OS: <https://www.iventoy.com/en/isolist.html>


# ansible

* [Install](#install)
  * [CLI](#cli)
  * [UI](#ui)

## Install

### CLI

```
uv tool install ansible
 + ansible==13.6.0
 + ansible-core==2.20.5
```

### UI

* <https://semaphoreui.com/install/>


# OpenWrt

* [Install on X86](#install-on-x86)
* [run as Container](#run-as-container)
  * [macvlan - access host](#macvlan---access-host)
  * [ipvlan](#ipvlan)
* [run as VM](#run-as-vm)
  * [QEMU NIC](#qemu-nic)
* [Docker](#docker)
* [network](#network)
  * [DSA](#dsa)
  * [/etc/config/](#etcconfig)
* [DHCP/DNS](#dhcpdns)
* [QoS](#qos)
  * [SQM](#sqm)
  * [nftables](#nftables)
* [Tailscale](#tailscale)
* [Mesh](#mesh)
  * [bat-adv](#bat-adv)
  * [Mode 802.11s](#mode-80211s)
  * [Mode AP - 802.11r](#mode-ap---80211r)
* [Switch Chip](#switch-chip)
  * [Bridged AP Setup](#bridged-ap-setup)
* [Controller - OpenWISP](#controller---openwisp)
* [Compile](#compile)
  * [Version](#version)
* [Wireshark](#wireshark)

## Install on X86

<https://openwrt.org/docs/guide-user/installation/openwrt\\_x86>

```
dd if=openwrt-21.02.0-x86-64-generic-ext4-combined.img bs=1M of=/dev/sdX

opkg update
opkg install lsblk parted losetup resize2fs
echo fix | parted -l ---pretend-input-tty
parted -s /dev/sda resizepart 2 100% 
losetup /dev/loop1 /dev/sda2
resize2fs -f /dev/loop1
```

## run as Container

* <https://supes.top/docker%E7%89%88openwrt%E6%97%81%E8%B7%AF%E7%94%B1%E5%AE%89%E8%A3%85%E8%AE%BE%E7%BD%AE%E6%95%99%E7%A8%8B/>
* <https://mlapp.cn/376.html>

```
ip link set vlan.10 promisc on
docker network create -d macvlan --subnet=10.0.0.0/8 --gateway=10.0.0.1 -o parent=vlan.10 macnet
docker network ls && docker network inspect macnet
docker run --restart unless-stopped --name openwrt -d --network macnet --privileged sulinggg/openwrt:x86_64 /sbin/init # root/password

docker exec -it openwrt /bin/sh # vim /etc/config/network // edit ip/gw & restart

config interface 'lan'
        option type 'bridge'
        option ifname 'eth0'
        option proto 'static'
        option ipaddr '10.19.0.3'
        option netmask '255.0.0.0'
        option gateway '10.0.0.1'
        option broadcast '10.255.255.255'
        option dns '10.0.0.1'

 docker network inspect macnet
```

### macvlan - access host

<https://stackoverflow.com/questions/49600665/docker-macvlan-network-inside-container-is-not-reaching-to-its-own-host>

```
docker network create -d macvlan -o parent=eno1 \
--subnet 192.168.1.0/24 \
--gateway 192.168.1.1 \
--ip-range 192.168.1.192/27 \
--aux-address 'host=192.168.1.223' \
mynet

ip link add macnet-shim link vlan.10 type macvlan  mode bridge
ip addr add 10.19.0.1/8 dev macnet-shim
ip link set macnet-shim up
ip route add 10.0.0.1/8 dev macnet-shim
ip link show macnet-shim || ip link delete macnet-shim
```

macvlan/ipvlan: <https://sreeninet.wordpress.com/2016/05/29/docker-macvlan-and-ipvlan-network-plugins/>

### ipvlan

<https://docs.docker.com/network/ipvlan/#ipvlan-l2-mode-example-usage>

```
docker network  create  -d ipvlan \
    --subnet=10.0.0.0/8 \
    --gateway=10.0.0.1 \
    --ip-range=10.19.1.0/24 \
    -o ipvlan_mode=l2 \
    -o parent=vlan.10 ipvlan10_NotTested
```

## run as VM

### QEMU NIC

```
use e1000; rtl8139 not detected by default.
eth0 -> LAN, eth1 -> WAN, usually.
```

## Docker

```
service dockerd stop
vi /etc/config/dockerd     # data_root
vi /etc/docker/daemon.json # data-root
reboot
docker pull hello-world
```

## network

### DSA

replace swconfig

Multiple networks (using VLANs): <https://forum.openwrt.org/t/mini-tutorial-for-dsa-network-config/96998>

### /etc/config/

<https://openwrt.org/docs/guide-user/network/network\\_configuration#example\\_configuration>

```
    config interface 'wan'
        option ifname 'eth0'
        option proto 'dhcp'
        option 'defaultroute' '1' # if multi WAN

    config interface 'lan'
        option type 'bridge'
        option ifname 'eth1 eth2'
        option proto 'static'
        option ipaddr '192.168.99.1'
        option netmask '255.255.255.0'
        option ip6assign '60'

/etc/init.d/network restart

# Soft network reload
service network reload

# Hard network restart
service network restart
```

H/W Router: wireless interfaces may be added to lan automatically via LUCI, create new for other bridges.

## DHCP/DNS

/etc/config/dhcp

```
config host
        list mac 'xx:xx:xx:xx:xx:xx'
        option ip '192.168.6.16'

config domain
        option name 'homeassistant.local'
        option ip '192.168.6.16'
```

## QoS

### SQM

<https://openwrt.org/docs/guide-user/network/traffic-shaping/start>

<https://openwrt.org/docs/guide-user/network/traffic-shaping/sqm>

* Interface name to your internet (WAN) link
* Link Layer Adaptation: <https://openwrt.org/docs/guide-user/network/traffic-shaping/sqm-details#sqmlink\\_layer\\_adaptation\\_tab>

### nftables

<https://github.com/openwrt/packages/blob/master/net/nft-qos/files/nft-qos.config>

## Tailscale

* <https://github.com/adyanth/openwrt-tailscale-enabler>
* <https://openwrt.org/docs/guide-user/services/vpn/tailscale/start>

## Mesh

```
iw list | grep -E "phy|mesh" # check if supported hardware
```

### bat-adv

<https://cgomesu.com/blog/Mesh-networking-openwrt-batman/#initial-configuration>

```
opkg remove wpad-basic-
opkg install batctl-full kmod-batman-adv wpad-mesh-wolfssl
```

<https://www.open-mesh.org/doc/batman-adv/Batman-adv-openwrt-config.html>

### Mode 802.11s

<https://openwrt.org/docs/guide-user/network/wifi/mesh/80211s>

### Mode AP - 802.11r

[./wireless.md#80211kvr](/openwrt/wireless#80211kvr)

## Switch Chip

<https://openwrt.org/docs/techref/swconfig>

```
swconfig list
swconfig dev switch0 show

VLAN 1:
        vid: 1
        ports: 0 1 6  # 6 = untagged CPU
VLAN 10:  # luci： `/network/vlan`
        vid: 10
        ports: 2 3 6t # tag CPU => create `eth0.X`(eth0=switch0) under `/network/iface_add`
```

<https://openwrt.org/docs/guide-user/network/vlan/switch\\_configuration#vlan\\_explained\\_with\\_default\\_scenario\\_of\\_most\\_openwrt\\_routers>

* Each port `untagged` to exactly one VLAN ID

### Bridged AP Setup

| Web URI                        | Task                                 |
| ------------------------------ | ------------------------------------ |
| /luci/admin/network/vlan       | + vlan : all ports tagged            |
| /luci/admin/network/iface\_add | test new vlan IP ; lan : remove dhcp |

## Controller - OpenWISP

* Install: <https://github.com/openwisp/openwisp-controller#deploy-it-in-production>
* Features: <https://openwisp.org/whatis.html>
* Config: <https://openwisp.io/docs/user/configure-device.html#install-openwisp-config>

## Compile

```
git clone --single-branch --branch main   --depth 1 https://github.com/openwrt/openwrt.git  /data/github/openwrt
git clone --single-branch --branch 22.03  --depth 1 https://github.com/Lienol/openwrt.git   /data/github/openwrt-Lienol-22.03
git clone --single-branch --branch master --depth 1 https://github.com/coolsnowwolf/lede    /data/github/openwrt-lede
```

<https://hub.docker.com/r/p3terx/openwrt-build-env>

```
docker run -itd \
    --name openwrt-build \
    -v /data/github/openwrt:/home/user/openwrt \
    p3terx/openwrt-build-env

n=openwrt-build-lede
docker exec $n sudo chown -hR user:user . && docker exec -it $n bash # tmux
cd ~/openwrt && ls -la
# make clean # rm /bin /build_dir
./scripts/feeds update -a ; ./scripts/feeds install -a
make menuconfig # make targetclean
make download -j8 V=s && make V=s -j$(($(nproc) - 1))


ls /data/github/openwrt*/bin/targets/mediatek/mt7622/*.bin -lh # host
```

<https://openwrt.org/docs/guide-developer/toolchain/use-buildsystem>

LuCI ---> Applications ---> luci-app-mtwifi #闭源Wi-Fi驱动 + kmod-mt76... Extra packages ---> ipv6helper

### Version

```
CONFIG_VERSIONOPT=y
CONFIG_IMAGEOPT=y
CONFIG_VERSION_DIST="##.##-SNAPSHOT"
CONFIG_VERSION_NUMBER="OpenWrt"
```

## Wireshark

* UI: click left icon of text `SSH remote capture` (no password save)
* CMD: <https://openwrt.org/docs/guide-user/firewall/misc/tcpdump\\_wireshark>


# DHCP\_DNS

* [Docs](#docs)
* [Static](#static)
  * [Luci](#luci)
  * [uci](#uci)
* [Lease Time](#lease-time)
  * [per client](#per-client)
  * [remove active](#remove-active)

## Docs

<https://openwrt.org/docs/guide-user/base-system/dhcp\\_configuration>

## Static

/etc/config/dhcp

### Luci

* all conf: <http://wrt.lan/cgi-bin/luci/admin/network/dhcp>
* dynamic -> static : <http://wrt.lan/cgi-bin/luci/admin/status/overview>

### uci

```
uci show | grep dhcp | grep host

uci add dhcp host         # will create `dhcp.@host[INDEX]=host`
uci set dhcp.@host[-1].ITEM # -1 : last | -x: xth from last

uci delete dhcp.@host[-1]

uci commit dhcp         # refresh Luci
service dnsmasq restart # reconnect client
```

## Lease Time

```
cat /tmp/dhcp.leases 

uci show | grep dhcp | grep lease
=> dhcp.lan.leasetime='12h'

uci set dhcp.lan.leasetime='10m'
uci commit dhcp; service odhcpd restart ; service dnsmasq restart
```

### per client

<https://openwrt.org/docs/guide-user/dhcp/dhcp\\_configuration#dhcp\\_pools>

luci: <http://wrt.lan/cgi-bin/luci/admin/network/dhcp>

### remove active

```
vi /tmp/dhcp.leases
/etc/init.d/dnsmasq restart
```


# OpenVPN

<https://openwrt.org/docs/guide-user/services/vpn/openvpn/server#key\\_management>

```
VPN_PKI="/etc/easy-rsa/pki"
export EASYRSA_PKI="${VPN_PKI}"
export EASYRSA_CERT_EXPIRE="36500"
cp -p pki/private/*.key /etc/openvpn/
cp -p pki/issued/*.crt   /etc/openvpn/
cp -p pki/{ca.crt,dh.pem}  /etc/openvpn/

service openvpn restart
```


# boot

* [BL2/FIP](#bl2fip)
* [MTD](#mtd)
* [uboot](#uboot)
* [cmd](#cmd)
* [Breed](#breed)

## BL2/FIP

<https://trustedfirmware-a.readthedocs.io/en/latest/design/firmware-design.html>

* Boot Loader stage 1 (BL1) AP Trusted ROM
* Boot Loader stage 2 (BL2) Trusted Boot Firmware
* Firmware Image Package

## MTD

calc HEX -> DEC ： 00400000 = 4MiB 06f00000 = 111MiB

```
cat /proc/mtd
fw_printenv | grep mtdparts

mtd write .fip FIP # kmod-mtd-rw
dd if=/tmp/uboot.fip of=/mtdX
```

## uboot

<https://openwrt.org/docs/techref/bootloader/uboot.config>

<https://github.com/hanwckf/bl-mt798x>

## cmd

```
ubinfo -a
smeminfo
```

## Breed

breed -> openwrt initramfs -> /cgi-bin/luci/admin/system/flashops/sysupgrade


# captive\_portal

* [CoovaChilli](#coovachilli)
* [uspot](#uspot)
* [NoDogSplash (NDS)](#nodogsplash-nds)

<https://openwrt.org/docs/guide-user/services/captive-portal/start>

## CoovaChilli

* <https://openwrt.org/docs/guide-user/services/captive-portal/wireless.hotspot.coova-chilli>
* Config: <https://github.com/coova/coova-chilli/blob/master/conf/defaults.in>

  ```
    # /etc/config/chilli
    # HS_MACALLOW="..."      # List of MAC addresses to authenticate (comma seperated)

    /etc/init.d/chilli status
  ```

## uspot

drop-in replacement for CoovaChilli / nftables , RFC8908 Captive Portal API

* <https://github.com/f00b4r0/uspot>
  * credentials : a simple username/password authentication
  * click-to-continue
  * radius
  * uam : remote RADIUS / MAC-based authentication bypass

## NoDogSplash (NDS)

a simple way to provide restricted access to the Internet by showing a splash page to the user before Internet access is granted.

* <https://openwrt.org/docs/guide-user/services/captive-portal/nodogsplash>
* Screenshot: <https://user-images.githubusercontent.com/56849408/67450477-ed622100-f5f3-11e9-8a49-9323d2ff94e7.png>


# hw

* [Chips](#chips)
  * [MediaTek](#mediatek)
* [CN](#cn)
* [OpenWrt One](#openwrt-one)
* [GLiNet](#glinet)
  * [Routers](#routers)
  * [VLAN](#vlan)
  * [Multi WAN](#multi-wan)

## Chips

### MediaTek

<https://wikidevi.wi-cat.ru/MediaTek#ARM>

* Ethernet switch
  * MT7531AE: 2.5Gbps / SerDes interface
  * MT7531BE: CPU port / RGMII (Reduced Gigabit Media Independent Interface)

MT7981B ds: <https://one.openwrt.org/hardware/MT7981B\\_Wi-Fi6\\_Platform\\_Datasheet\\_Open\\_V1.0.pdf>

## CN

* Xiaomi / Redmi: <https://wikidevi.wi-cat.ru/List\\_of\\_Xiaomi\\_Wireless\\_Devices>
* gl-inet: <https://wikidevi.wi-cat.ru/GL.iNet>

| openwrt.org                                                            | SoC      | CPU MHz | Flash MB | RAM MB | Wireless          | Switch   |
| ---------------------------------------------------------------------- | -------- | ------- | -------- | ------ | ----------------- | -------- |
| [CT3003](https://openwrt.org/toh/hwdata/cetron/cetron_ct3003)          | MT7981B  | 2c1.3   | 128      | 256    | MT7981            | MT7531AE |
| [RM AX6S](https://openwrt.org/toh/xiaomi/ax3200)                       | MT7622B  | 2c1.35  | 128NAND  | 256    | MT7622B/MT7915E   | MT7531BE |
| [Mi AX3000T](https://openwrt.org/inbox/toh/xiaomi/ax3000t)             | MT7981BA | 2c1.3   | 128NAND  | 256    | MT7981BA/MT7976CN | MT7531AE |
| [GL-MT3000](https://openwrt.org/toh/gl.inet/gl-mt3000)                 | MT7981BA | 2c1.3   | 256      | 512    | MT7981BA          | MT7981BA |
| [RM AX6](https://openwrt.org/inbox/toh/xiaomi/xiaomi_redmi_ax6_ax3000) | IPQ8071A | 4c1.4   | 128 MiB  | 512    | QCN5024/QCN5054   | QCA8075  |
| [GL-MT6000](https://openwrt.org/toh/gl.inet/gl-mt6000)                 | MT7986A  | 4c2.0   | 8G eMMC  | 1024   | MT7976GN/MT7976AN | MT7531AE |

## OpenWrt One

November 29, 2024: <https://openwrt.org/#openwrt\\_one\\_router\\_officially\\_launched>

MT7981B / 2C 1.3GHz / 1G + 256MB / LAN: 2.5G + 1G : <https://openwrt.org/toh/openwrt/one>

## GLiNet

```
ls -lh /etc/oui-tertf/client.db
/etc/config
```

API: <https://dev.gl-inet.com/>

Cloud Web: set firewall/lan subnet/ ; view clients

* CN : <https://cloud.gl-inet.cn>
* <https://www.goodcloud.xyz>
* remote web/terminal : need pub ip? : <https://docs.gl-inet.com/router/en/4/interface\\_guide/cloud/#remote-access-web-admin-panel>

### Routers

GL-MT6000 | eth1 + ( eth0 : lan1-5 )

GL-MT3000 | eth0 2.5G + eth1 1G

* swap: /#/netport make eth0 lan -> luci , don't edit /etc/config/network directly!

### VLAN

br-lan: rm physical, add br-VLANs.1

* if br-lan.1 : GL UI won't show clients

### Multi WAN

no custom rules on luci

* wan
* secondwan
* wwan
* tethering | USB | <https://docs.gl-inet.com/router/en/4/interface\\_guide/internet\\_tethering/>

  ```
    cat /etc/config/kmwan

        option level # TODO

    cat /etc/hotplug.d/iface/99-kmwan

    uci -q get kmwan.global.enable
  ```

sensitivity: detection time interval(unit:s)


# luci

* [Web](#web)
  * [Troubleshooting](#troubleshooting)
* [port](#port)
  * [http](#http)
* [/www/](#www)
* [/usr/lib/lua/luci/](#usrliblualuci)

## Web

| Action        | Addr                                                            |
| ------------- | --------------------------------------------------------------- |
| conf firewall | <http://wrt.lan/cgi-bin/luci/admin/network/firewall>            |
| view iptables | <http://wrt.lan/cgi-bin/luci/admin/status/iptables>             |
| view conn     | <http://wrt.lan/cgi-bin/luci/admin/status/realtime/connections> |
| SSH key       | <http://wrt.lan/cgi-bin/luci/admin/system/admin>                |

/etc/config/luci

* ping/traceroute/nslookup: <http://wrt.lan/cgi-bin/luci/admin/network/diagnostics>

### Troubleshooting

* <http://wrt.lan/cgi-bin/luci/admin/status/routes>
  * rm default gw of interface if unexpected 0.0.0.0/0
* firewall + DNS

## port

### http

```
grep listen /etc/config/uhttpd /etc/nginx/conf.d/*
```

## /www/

* cgi-bin/luci

## /usr/lib/lua/luci/

* model/view/controller
* admin


# mwan3

* [Doc](#doc)
* [Install](#install)
* [Management](#management)
* [Debug](#debug)

## Doc

<https://wiki.openwrt.org/doc/howto/mwan3>

* A new routing table is created for each interface
* A monitoring script (mwan3track) runs in the background checking each WAN interface
* <https://openwrt.org/docs/guide-user/network/wan/multiwan/mwan3>
* <https://oldwiki.archive.openwrt.org/doc/howto/mwan3>

## Install

* [mt7981](https://downloads.openwrt.org/snapshots/packages/aarch64_cortex-a53/packages/)

## Management

`/cgi-bin/luci/admin/network/mwan3`

* Globals
* Notify: /etc/mwan3.user(.sh)
* Rule -> Policy -> Member ( compare `weight` if same `metric`) -> Interface

## Debug

`/cgi-bin/luci/admin/status/mwan3`: status/Diagnostics

```
ip route show # Interface
```


# radius

## platform

<https://www.radiusdesk.com/wiki24/products>

* <https://github.com/RADIUSdesk>

## FreeRADIUS

<https://openwrt.org/docs/guide-user/network/wifi/freeradius>

* clients.conf -
  * client private-network-\* { ipaddr + secret
* sites-enabled/default

  * listen {
  * authorize { filter\_password #
    * files: mods-config/files/authorize
    * PAP (Password Authentication Protocol) | `pap: WARNING: Authentication will fail unless a "known good" password is available`

  opkg update && opkg install freeradius3-default apt install -y freeradius-utils # client tools ls -R /etc/freeradius3 /etc/init.d/radiusd stop && radiusd -X # debug radtest bob hello wrt.lan 0 testing123 # 0 = NAS-port-number = any


# route

* [PBR](#pbr)
* [OSPF](#ospf)
  * [frr-ospfd](#frr-ospfd)
  * [bird2](#bird2)

## PBR

<https://openwrt.org/docs/guide-user/network/routing/pbr>

* PBR app
  * split tunneling
* PBR with netifd
  * route traffic to a specific interface
* mwan3
  * load balancing and failover

## OSPF

### frr-ospfd

FRRouting

* active fork of Quagga

### bird2

BIRD Internet Routing Daemon

* lightweight


# theme

* [Create](#create)

## Create

<https://github.com/openwrt/luci/wiki/HowTo:-Create-Themes>


# wireless

* [Roaming](#roaming) - [Debug](#debug)
* [802.11kvr](#80211kvr) - [/etc/config/wireless](#etcconfigwireless) - [MediaTek](#mediatek)
* [Client Info](#client-info)
* [Controller](#controller) - [DAWN](#dawn) - [usteer](#usteer) - [fakemesh](#fakemesh)

## Roaming

<https://openwrt.org/docs/guide-user/network/wifi/roaming>

### Debug

* <https://openwrt.org/docs/guide-user/network/wifi/roaming#checking\\_80211k\\_is\\_enabled>
* <https://openwrt.org/docs/guide-user/network/wifi/roaming#verifying\\_client\\_80211r\\_support>

## 802.11kvr

[/nw/README.md#roaming---80211krv](/nw#roaming---80211krv)

### /etc/config/wireless

<https://openwrt.org/docs/guide-user/network/wifi/basic#neighbor\\_reports\\_options\\_80211k>

* helper: <https://github.com/walidmadkour/OpenWRT-UCI-helper-802.11r>
* uci: <https://vicfree.com/2022/11/openwrt-wpa3-802.11kvr-ap-setup/>
* [debug](https://forum.openwrt.org/t/any-way-to-monitor-if-802-11r-is-working/73504): [hostapd log](https://openwrt.org/docs/guide-developer/debugging#logging_hostapd_behaviour)

  ```
    # grep -E '11(k|v|r)|^config' /etc/config/wireless
    config wifi-device 'radio0'
    config wifi-iface 'default_radio0'
            option ieee80211r '1'
            option ieee80211k '1'
            # option ieee80211v Removed
  ```

### MediaTek

<https://github.com/coolsnowwolf/lede/issues/5002#issuecomment-683371787>

```
    grep -E 'RRM|WNM|Ft' -r /etc/wireless/ # k/v/r
```

## Client Info

<http://wrt.lan/cgi-bin/luci/admin/network/wireless>

```
    # fping -g 192.168.8.0/24 # show IPv4 if IPv6 under `Associated Stations`

    # iw dev | grep -E 'Interface|ssid'

    # iw dev phy1-ap0 station dump
    Station [K60_MAC] (on phy1-ap0)
            inactive time:  10 ms
            rx bytes:       1274880
            rx packets:     7828
            tx bytes:       56193821
            tx packets:     39844
            tx retries:     8088
            tx failed:      8088
            rx drop misc:   6
            signal:         -83 [-86, -91, -86, -95] dBm
            signal avg:     -82 [-86, -91, -86, -95] dBm
            tx bitrate:     432.3 MBit/s 160MHz HE-MCS 2 HE-NSS 2 HE-GI 0 HE-DCM 0
            tx duration:    21709248 us
            rx bitrate:     432.3 MBit/s 160MHz HE-MCS 2 HE-NSS 2 HE-GI 0 HE-DCM 0
            rx duration:    542587 us
            last ack signal:-12 dBm
            avg ack signal: -22 dBm
            airtime weight: 256
            authorized:     yes
            authenticated:  yes
            associated:     yes
            preamble:       short
            WMM/WME:        yes
            MFP:            no
            TDLS peer:      no
            DTIM period:    2
            beacon interval:100
            short preamble: yes
            short slot time:yes
            connected time: 87 seconds
            associated at [boottime]:       283658.981s
            associated at:  1700846966098 ms
            current time:   1700847053027 ms
```

## Controller

### DAWN

Decentralized WiFi Controller

* <https://github.com/berlin-open-wireless-lab/DAWN>
  * full wpad-\* version and not wpad-basic
* <https://github.com/berlin-open-wireless-lab/DAWN/blob/master/CONFIGURE.md>
* <https://openwrt.org/docs/guide-user/network/wifi/dawn>

  ```
    sed -i 's/10.0.0.255/192.168.88.255/' /etc/config/dawn && /etc/init.d/dawn restart
    grep -E '_port|_ip' /etc/config/dawn && netstat -lntup | grep dawn
  ```

### usteer

<https://openwrt.org/docs/guide-user/network/wifi/usteer>

### fakemesh

<https://github.com/x-wrt/com.x-wrt/blob/master/luci-app-fakemesh/README.md>

<https://fakemesh.com/#%E5%8F%AF%E9%80%89%E9%85%8D%E7%BD%AE>

* Sync Config


# ai

* [Model Ranking](#model-ranking)
* [Concepts](#concepts)
* [Links](#links)

## Model Ranking

<https://openrouter.ai/rankings>

## Concepts

* MCP (Model Context Protocol)
  * connecting AI applications to external systems
  * <https://modelcontextprotocol.io/docs/getting-started/intro>

## Links

* Course: <https://csdiy.wiki/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0/LHY/>
* GPT: <https://github.com/formulahendry/awesome-gpt>


# ML

* [NTU Courses](#ntu-courses)
  * [Linear Algebra](#linear-algebra)
* [Keras](#keras)
* [scikit-learn](#scikit-learn)

## NTU Courses

<http://speech.ee.ntu.edu.tw/\\~tlkagk/courses.html\\>
<https://www.youtube.com/watch?v=fegAeph9UaA\\&index=3\\&list=PLJV\\_el3uVTsPy9oCRY30oBPNLCo89yu49>

### Linear Algebra

<http://speech.ee.ntu.edu.tw/\\~tlkagk/courses\\_LA16.html>

## Keras

<https://keras.io/>

<https://www.youtube.com/watch?v=Lx3l4lOrquw\\&list=PLJV\\_el3uVTsPy9oCRY30oBPNLCo89yu49\\&index=13>

## scikit-learn

<https://www.slideshare.net/aacs0130/scikitlearn-62706630> (TW)


# agent

* [Compare](#compare)
* [OpenClaw](#openclaw)

## Hermes Agent

<https://hermes-agent.nousresearch.com/docs>

```
curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash

hermes dashboard --host 0.0.0.0 --port 9111 --no-open --insecure
```

## OpenSquilla

Token-Efficient: <https://github.com/opensquilla/opensquilla#key-features>

* routes across four tiers (T0–T3) to the cheapest capable model

## Compare

OpenSquilla OpenClaw Hermes Agent : <https://opensquilla.ai/#comparison>

|                       | [OpenClaw](https://github.com/openclaw/openclaw) | [NanoBot](https://github.com/HKUDS/nanobot) | [PicoClaw](https://github.com/sipeed/picoclaw) | [ZeroClaw](https://github.com/zeroclaw-labs/zeroclaw) | [NullClaw](https://github.com/nullclaw/nullclaw) |
| --------------------- | ------------------------------------------------ | ------------------------------------------- | ---------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------ |
| **Language**          | TypeScript                                       | Python                                      | Go                                             | Rust                                                  | **Zig**                                          |
| **RAM**               | > 1 GB                                           | > 100 MB                                    | < 10 MB                                        | < 5 MB                                                | **\~1 MB**                                       |
| **Startup (0.8 GHz)** | > 500 s                                          | > 30 s                                      | < 1 s                                          | < 10 ms                                               | **< 8 ms**                                       |
| **Binary Size**       | \~28 MB (dist)                                   | N/A (Scripts)                               | \~8 MB                                         | 3.4 MB                                                | **678 KB**                                       |

## OpenClaw

<https://github.com/openclaw/openclaw/releases>

origin not allowed (open the Control UI from the gateway host or allow it in gateway.controlUi.allowedOrigins)

```
"gateway.controlUi.allowedOrigins": [ 
  "http://127.0.0.1:37798"         // 本地
]
```


# coding

* [IDE](#ide)
  * [CN](#cn)
* [USD](#usd)
* [API](#api)
  * [openrouter](#openrouter)
* [TTS](#tts)
  * [MiMo-V2-TTS](#mimo-v2-tts)
* [Tools](#tools)
  * [Gemini CLI](#gemini-cli)

## IDE

### CN

| 工具               | 出品方   | IDE     | ext  | free         |
| ---------------- | ----- | ------- | ---- | ------------ |
| 通义灵码 (Qoder CN)​ | 阿里云   | +Quest  | full | 2week pro    |
| CodeBuddy​       | 腾讯云   | +Agents | -    | manual/daily |
| Trae（国内版）​       | 字节跳动  | +SOLO   | full |              |
| 文心快码 Comate      | 百度    | -       | full |              |
| CodeGeeX         | 智谱 AI | -       | full |              |

## USD

| Price       | Site                                            | 1M tokens                            |
| ----------- | ----------------------------------------------- | ------------------------------------ |
| 0/PAYG      | <https://ai.google.dev/gemini-api/docs/pricing> | $0.25(text/image/video) $0.50(audio) |
| 0/8/20/250  | <https://one.google.com/about/google-ai-plans/> | Antigravity                          |
| 0/10/39     | <https://github.com/features/copilot/plans>     |                                      |
| 0/8/20/200  | <https://chatgpt.com/pricing/>                  |                                      |
| 0/20/60/200 | <https://cursor.com/pricing>                    |                                      |
| 0/15/30     | <https://windsurf.com/pricing>                  |                                      |
| 0/10        | <https://www.trae.ai/pricing>                   |                                      |
| 0/20        | <https://replit.com/pricing>                    |                                      |
| 0/PAYG      | <https://docs.x.ai/docs/models>                 | API                                  |
| 0/17        | <https://www.claude.com/pricing>                | non-CN                               |
| 20+         | <https://www.augmentcode.com/pricing>           |                                      |

## API

### openrouter

* <https://openrouter.ai/openrouter/free>
* <https://openrouter.ai/openrouter/auto>

## TTS

### MiMo-V2-TTS

<https://platform.xiaomimimo.com/#/docs/news/v2-tts-release>

## Tools

| Feature / Tool          | **Cline**                   | **OpenCode**               | **Kilocode**              | **OpenClaw**                      | **Blackbox AI**                  |
| ----------------------- | --------------------------- | -------------------------- | ------------------------- | --------------------------------- | -------------------------------- |
| **Primary Interface**   | VS Code Extension           | Terminal (CLI / TUI)       | VS Code, JetBrains, CLI   | OS / Terminal Background          | Web, Mobile, IDE Extension       |
| **Philosophy**          | Human-in-the-loop IDE Agent | Terminal-first local Agent | Unified Agentic Workspace | Autonomous Background Assistant   | Multi-modal Rapid Generator      |
| **Open Source**         | ✅ Yes                       | ✅ Yes                      | ✅ Yes (Core)              | ✅ Yes                             | ❌ Proprietary (Freemium)         |
| **Standout Superpower** | Diff-based UI approvals     | Deep Terminal integration  | Cross-IDE syncing & modes | Truly autonomous background tasks | Image/Figma-to-Code & Mobile App |

### Gemini CLI

<https://github.com/google-gemini/gemini-cli?tab=readme-ov-file#-why-gemini-cli>

* free: 60 requests/min & 1,000 requests/day


# free

<https://openrouter.ai/openrouter/free>

* 200K Context Length | <https://openrouter.ai/compare/openrouter/free/openrouter/auto>

<https://opencode.ai/docs/zen/#pricing>


# tool

## mix

### tokscale

<https://github.com/junhoyeo/tokscale>

```
npx tokscale@latest
```

## opencode

<https://github.com/Shlomob/ocmonitor-share>

```
uv tool install opencode-monitor
uv tool upgrade opencode-monitor

pipx install opencode-monitor # Arch Linux, Ubuntu, macOS, etc

# Real-time monitoring dashboard
ocmonitor live

# View sessions history
ocmonitor sessions

# Daily usage breakdown (add --breakdown for per-model detail)
ocmonitor daily
ocmonitor daily --breakdown

# Deep dive into a specific model
ocmonitor model claude-sonnet-4-5
```


# apps

* [Screen sharing](#screen-sharing)
  * [Shell](#shell)
* [Terminal](#terminal)
  * [Windows](#windows)
* [KVM switch](#kvm-switch)
* [File Transfer](#file-transfer)
* [Note](#note)
  * [NextCloud](#nextcloud)
* [Sync](#sync)
  * [ResilioSync/BTSync](#resiliosyncbtsync)
* [GPU](#gpu)
  * [OpenCL](#opencl)
* [bench](#bench)
  * [net](#net)
* [DSM](#dsm)
* [Security](#security)
  * [Password Managment](#password-managment)
    * [Bitwarden](#bitwarden)
* [Instant Notifications](#instant-notifications)
* [IoT](#iot)
* [Taobao](#taobao)
* [Sandbox](#sandbox)

## Screen sharing

* host | FreeBSD Linux macOS Windows: <https://docs.lizardbyte.dev/projects/sunshine/latest/?lng=zh-CN>
* client: <https://moonlight-stream.org/>
  * qt: <https://github.com/moonlight-stream/moonlight-qt/releases>

| Type       | Site                     | Server        | Client              | Management |
| ---------- | ------------------------ | ------------- | ------------------- | ---------- |
| OSS        | <https://deskreen.com/>  | win/mac/linux | web                 | ViewOnly   |
| Commercial | <https://spacedesk.net/> | win           | win/ios/android/web | Touch      |

### Shell

<https://asciinema.org/>

## Terminal

### Windows

C | X11/XYZModem: <https://github.com/kingToolbox/WindTerm\\>
TypeScript | Terminus: <https://github.com/Eugeny/tabby\\>
Free version allowd in companay: <https://mobaxterm.mobatek.net/download.html\\>
Free for home: <https://www.netsarang.com/xshell\\_download.html>

## KVM switch

<https://github.com/debauchee/barrier/\\>
Barrier was forked from Symless's Synergy 1.9 codebase.

h/w: pikvm

## File Transfer

<https://github.com/blueimp/jQuery-File-Upload>

## Note

### NextCloud

<https://github.com/docker-library/docs/blob/master/nextcloud/README.md#using-the-apache-image>

<https://help.nextcloud.com/t/tutorial-how-to-migrate-mass-data-to-a-new-nextcloud-server/9418>

if behind rproxy:\
<https://docs.nextcloud.com/server/19/admin\\_manual/configuration\\_server/config\\_sample\\_php\\_parameters.html?highlight=overwrite%20cli%20url#proxy-configurations>

```
'overwritehost' => '...',
'overwriteprotocol' => 'https',
```

## Sync

### ResilioSync/BTSync

<https://www.resilio.com/platforms/desktop/> <https://download-cdn.resilio.com/stable/windows64/Resilio-Sync\\_x64.exe\\>
<https://download-cdn.resilio.com/stable/linux-x64/resilio-sync\\_x64.tar.gz>

## GPU

### OpenCL

```
phoronix-test-suite benchmark pts/opencl

phoronix-test-suite test system/opencl
# https://download.blender.org/demo/test/cycles_benchmark_20160228.zip
```

## bench

### net

<https://download.mikrotik.com/routeros/6.48/btest.exe>

## DSM

<https://xpenology.club/install-xpenology-dsm-6-1-x-proxmox/>

* UEFI q35 + USB boot + SATA data disk

Ports: <https://www.synology.com/en-us/knowledgebase/DSM/tutorial/Network/What\\_network\\_ports\\_are\\_used\\_by\\_Synology\\_services>

## Security

Password Crack: <https://hashcat.net/hashcat>

### Password Managment

#### Bitwarden

lightweight: <https://github.com/dani-garcia/vaultwarden> clients/extensions: <https://bitwarden.com/download/>

## Instant Notifications

<http://instapush.im/>

## IoT

<https://www.xively.com/>

## Music

<https://github.com/taurusxin/ncmdump>

* 网易云音乐 3.0 之后的某些版本，下载的 ncm 文件会出现不内置歌曲专辑的封面图片

## Sandbox

??%SystemDrive%\Sandbox%USER%%SANDBOX%


# web

* [Tools](#tools)
* [Search Engines](#search-engines)
* [Linux](#linux)

## Tools

| Desc                      | Link                                           |
| ------------------------- | ---------------------------------------------- |
| Table to Markdown         | <https://html.ferro.pro/md.html>               |
| Docker Cmd Helper         | <https://html.ferro.pro/docker.html>           |
| text split/filter/replace | <https://html.ferro.pro/txt.html>              |
| .md <-> .rst              | <https://pandoc.org/try/>                      |
| YAML / JSON / TOML        | <https://vault-tools.com/text/yaml-json-toml/> |

## Search Engines

<https://github.com/edoardottt/awesome-hacker-search-engines>

## Linux

* cron explain: <https://crontab.guru/>
* <https://explainshell.com/>


# BSD

* [Desktop](#desktop)
* [TCP congestion control](#tcp-congestion-control)
* [relayd](#relayd)
* [PF](#pf)
  * [ipfw](#ipfw)
* [ZFS](#zfs)
* [DTrace](#dtrace)
* [CAM Target Layer(ctl)](#cam-target-layerctl)
  * [HA cluster](#ha-cluster)

## Desktop

* FreeBSD since 2010, based on FreeBSD
* TrueOS (formerly PC-BSD or PCBSD) ended in 2020

## TCP congestion control

```
sysctl net.inet.tcp.cc
net.inet.tcp.cc.available: newreno
net.inet.tcp.cc.algorithm: newreno

kldload cccubic
kldload ccvegas
kldload cccdg
```

## relayd

<https://man.openbsd.org/relayd.conf.5> layer 3 and/or layer 7 load-balancer, application layer gateway, or transparent proxy

## PF

<https://man.openbsd.org/pf.conf>

```
pass in all 
pass in from any to any 
pass in proto tcp from any port < 1024 to any 
pass in proto tcp from any to any port 25 
pass in proto tcp from 10.0.0.0/8 port >= 1024 \ 
    to ! 10.1.2.3 port != ssh 
pass in proto tcp from any os "OpenBSD" 
pass in proto tcp from route "DTAG" 
```

### ipfw

```
sudo ipfw add fwd 127.0.0.1,12345 tcp from not me to any 80 in via en1
sudo ipfw add fwd 127.0.0.1,12345 tcp from not me to any 443 in via en1
```

## ZFS

<https://www.freebsd.org/cgi/man.cgi?query=zpool>

```
zpool create pool_name da0p3 da1p3
zpool create pool_name \
    mirror da0	da1 \
    mirror da2 da3 \
    log mirror da4 da5
zpool add pool cache	da2 da3

zpool list
zpool get all pool_name
zpool status pool_name
zpool iostat -v pool_name 5
zpool list -v pool_name
```

## DTrace

<https://wiki.freebsd.org/DTrace/Tutorial>

## CAM Target Layer(ctl)

The ctl subsystem provides SCSI target devices emulation

### HA cluster

<https://bsdmag.org/nearly-online-zpool-switching-two-freebsd-machines/>


# Mac

* [HighDPI](/bsd/mac#highdpi)
* [pip](/bsd/mac#pip)
* [brew & gnu tools](/bsd/mac#brew--gnu-tools)
* [Hackintosh](/bsd/mac#hackintosh)
  * [Build an OS X boot disk](/bsd/mac#build-an-os-x-boot-disk)
  * [On QEMU/KVM](/bsd/mac#on-qemukvm)

## HighDPI

```
sudo defaults write /Library/Preferences/com.apple.windowserver.plist DisplayResolutionEnabled -bool true
```

## pip

```
wget https://bootstrap.pypa.io/3.2/get-pip.py
sudo python get-pip.py
```

## brew & gnu tools

```
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
export PATH="$(brew --prefix coreutils)/libexec/gnubin:/usr/local/bin:$PATH"
brew install findutils --with-default-names
brew install gnu-indent --with-default-names
brew install gnu-sed --with-default-names
brew install gnutls
brew install grep --with-default-names
brew install gnu-tar --with-default-names
brew install gawk
```

## Hackintosh

### Build an OS X boot disk

<http://diskmakerx.com/>

### On QEMU/KVM

<https://github.com/kholia/OSX-KVM>


# Cloud

* [Domain Name lookup](#domain-name-lookup)
* [Object Storage](#object-storage)
* [HIDS uninstall](#hids-uninstall)
  * [jcloud](#jcloud)
  * [aliyun](#aliyun)
  * [qcloud](#qcloud)

## Domain Name lookup

<https://lookup.icann.org/>

## Object Storage

China：tx COS | ali/jd OSS | hw OBS

## HIDS uninstall

### jcloud

```
wget http://hids.s-sq.jcloud.com/jcloudhids_linux64_V1.0.tar.gz
tar zxvf jcloudhids_linux64_V1.0.tar.gz
./jcloudhids_linux64_V1.0.19216/uninstall.py
```

### aliyun

```
rm -f /usr/local/share/aliyun-assist/1.0.1.259/aliyun-service
```

### qcloud

```
/usr/local/sa/agent
/usr/local/qcloud/monitor/barad/admin
```


# aws

* [lambda](#lambda)

## lambda

<https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html>


# azure

* [Console](#console)
  * [Services free for 12 months](#services-free-for-12-months)
* [storage](#storage)
* [cli](#cli)
  * [vm](#vm)
  * [disk](#disk)
  * [network lb](#network-lb)
    * [inbound-nat-rule](#inbound-nat-rule)

## Console

### Services free for 12 months

<https://portal.azure.com/#blade/Microsoft\\_Azure\\_Billing/FreeServicesBlade>

<https://portal.azure.com/#blade/Microsoft\\_Azure\\_Billing/SubscriptionsBlade> -- click subscription -> "Overview"

## storage

<https://docs.microsoft.com/en-us/azure/virtual-machines/windows/disks-types>

|                | Ultra disk  | Premium SSD | Standard SSD | Standard HDD |
| -------------- | ----------- | ----------- | ------------ | ------------ |
| Max throughput | 2,000 MiB/s | 900 MiB/s   | 750 MiB/s    | 500 MiB/s    |
| Max IOPS       | 160,000     | 20,000      | 6,000        | 2,000        |

| Premium SSD sizes | P1\* | P2\* | P3\* | P4  | P6  | P10 | P15   | P20   | P30   | P40   | P50   | P60    | P70    | P80    |
| ----------------- | ---- | ---- | ---- | --- | --- | --- | ----- | ----- | ----- | ----- | ----- | ------ | ------ | ------ |
| Disk size in GiB  | 4    | 8    | 16   | 32  | 64  | 128 | 256   | 512   | 1,024 | 2,048 | 4,096 | 8,192  | 16,384 | 32,767 |
| IOPS per disk     | 120  | 120  | 120  | 120 | 240 | 500 | 1,100 | 2,300 | 5,000 | 7,500 | 7,500 | 16,000 | 18,000 | 20,000 |

## cli

<https://shell.azure.com/bash>

```
# Powershell
Invoke-WebRequest -Uri https://aka.ms/installazurecliwindows -OutFile .\AzureCLI.msi; Start-Process msiexec.exe -Wait -ArgumentList '/I AzureCLI.msi /quiet'

# Linux apt
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash

# Linux all
curl -L https://aka.ms/InstallAzureCli | bash

docker run -it -v ${HOME}/.ssh:/root/.ssh mcr.microsoft.com/azure-cli

az login
az resource list
```

### vm

<https://docs.microsoft.com/en-us/cli/azure/vm?view=azure-cli-latest>

```
az vm list --output table --show-details
az vm stop/deallocate/start --resource-group linux --name ubuntu-2     
```

`deallocate` to stop billing & `disk update`

### disk

<https://docs.microsoft.com/en-us/cli/azure/disk?view=azure-cli-latest#az-disk-update>

Locally-redundant storage (LRS)

```
az disk list --resource-group linux --output table
az disk update --resource-group linux --name ubuntu-2_OsDisk_1_74250d56f08040e1a48f38b9198148f7 --size-gb 32 # Reducing disk/snapshot size is not supported. create new snapshot/disks.
az disk update --resource-group linux --name ubuntu-2_OsDisk_1_74250d56f08040e1a48f38b9198148f7 --sku Premium_LRS

az disk create --location eastasia --sku Premium_LRS -g linux -n data-1 --size-gb 10
```

<https://docs.microsoft.com/en-us/cli/azure/vm/disk?view=azure-cli-latest#az-vm-disk-attach>

```
az vm disk attach -g linux --vm-name ubuntu-2 --name data-1 # --new
```

### network lb

#### inbound-nat-rule

<https://docs.microsoft.com/en-us/cli/azure/network/lb/inbound-nat-rule?view=azure-cli-latest#az\\_network\\_lb\\_inbound\\_nat\\_rule\\_create>


# cf

* [Network ports](#network-ports)
* [Rules](#rules)
* [SSL/TLS](#ssltls)
  * [SSL Modes](#ssl-modes)
  * [Edge Certificates](#edge-certificates)
  * [Origin CA](#origin-ca)
* [CNAME Flattening](#cname-flattening)
* [Workers](#workers)
  * [TypeScript](#typescript)
  * [Wrangler (Workers CLI)](#wrangler-workers-cli)
* [Workers as Reverse Proxy](#workers-as-reverse-proxy)
  * [Bulk origin override](#bulk-origin-override)
  * [Reflare](#reflare)
* [Storage](#storage)
  * [R2 - S3 object](#r2---s3-object)
  * [KV - key-value](#kv---key-value)
  * [D1 - RDB](#d1---rdb)
  * [Durable Objects - Workers Paid plan](#durable-objects---workers-paid-plan)
  * [Queues - Workers Paid plan](#queues---workers-paid-plan)
* [Paid](#paid)

## Network ports

HTTP: 80 8080 | No caching: 8880 2052 2082 2086 2095\
HTTPS: 443 | No caching: 2053 2083 2087 2096 8443

## Rules

Settings - URL normalization: <https://developers.cloudflare.com/rules/normalization/how-it-works/>

<https://developers.cloudflare.com/rules/>

* [order](https://developers.cloudflare.com/rules/configuration-rules/#execution-order): Origin -> Cache -> Conf -> Single -> Page

| Name                                                                                                | Free    | Desc                                                                                                        |
| --------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------- |
| [Transform Rules](https://developers.cloudflare.com/rules/transform/)                               | free 10 | no Regex support                                                                                            |
| [Origin Rules](https://developers.cloudflare.com/rules/origin-rules/)                               | 10      | Override destination port                                                                                   |
| [Cache Rules](https://developers.cloudflare.com/cache/about/cache-rules/)                           | 10      | cache properties of your HTTP requests                                                                      |
| [Configuration Rules](https://developers.cloudflare.com/rules/configuration-rules/)                 | 10      | [expressions](https://developers.cloudflare.com/firewall/cf-dashboard/edit-expressions/) / no Regex support |
| [Single Redirects](https://developers.cloudflare.com/rules/url-forwarding/bulk-redirects/concepts/) | 5\~20   |                                                                                                             |
| [Page Rules](https://support.cloudflare.com/hc/en-us/articles/218411427)                            | 3       | require a "proxied" DNS record, highest priority rule at the top                                            |

## SSL/TLS

### SSL Modes

<https://developers.cloudflare.com/ssl/origin-configuration/ssl-modes/>

```
Flexible: visitor - Edge cert - cf
Full: cf - self signed certificate - server
Full (strict): cf - trusted CA  - server
```

### Edge Certificates

[Automatic HTTPS Rewrites](https://support.cloudflare.com/hc/en-us/articles/227227647) safely eliminates **mixed content** issues by rewriting insecure URLs dynamically from known secure hosts to their secure counterpart.

[Page Rules - Always Use HTTPS](https://support.cloudflare.com/hc/en-us/articles/218411427#https)

[Page Rules - Forwarding URL](https://support.cloudflare.com/hc/en-us/articles/200170536)

### Origin CA

15-years wildcard | visitor - Edge cert - cf - Origin CA - server： <https://blog.cloudflare.com/cloudflare-ca-encryption-origin/>

```
PEM: Apache httpd and NGINX
PKCS#7: Microsoft’s IIS or Apache Tomcat
```

## CNAME Flattening

* CNAME records normally can not be on the zone apex. We use CNAME flattening to make it possible.
* DNS/Settings

<https://developers.cloudflare.com/dns/additional-options/cname-flattening/>

* speeds up CNAME resolution
* CNAME flattening occurs by default

## Workers

* Free Limits: <https://developers.cloudflare.com/workers/platform/limits>
* Examples: <https://developers.cloudflare.com/workers/examples/>
* Create site: <https://developers.cloudflare.com/workers/platform/sites/>
* Cron: <https://developers.cloudflare.com/workers/platform/triggers/cron-triggers/>
* KV: <https://developers.cloudflare.com/workers/runtime-apis/kv/>

### TypeScript

<https://github.com/cloudflare/workers-sdk/tree/main/templates/worker-typescript>

```
npm init cloudflare my-project worker-typescript
```

* Pages: <https://developers.cloudflare.com/pages/platform/functions/typescript/>

### Wrangler (Workers CLI)

<https://developers.cloudflare.com/workers/get-started/guide/>

```
npm install -g wrangler # nodejs v16.13.0+
wrangler login  # install volta/nvm if error
wrangler whoami # view permissions
wrangler init <YOUR_WORKER> && cd <YOUR_WORKER>
```

`wrangler generate [name] [template]`: <https://github.com/cloudflare/templates>

```
npm start # [l] turn on/off local mode
npm test
npm run deploy || wrangler publish # 1st time: wait 1min
```

Workers > Overview # re-login web if no menu

* Online dev: worker page > click `Quick edit`

`wrangler dev`: <https://developers.cloudflare.com/workers/learning/debugging-workers/>

`wrangler tail --format=pretty`: <https://developers.cloudflare.com/workers/learning/logging-workers/>

## Workers as Reverse Proxy

### Bulk origin override

<https://developers.cloudflare.com/workers/examples/bulk-origin-proxy>

### Reflare

<https://github.com/xiaoyang-sde/reflare>

```
npm init cloudflare reflare-app https://github.com/xiaoyang-sde/reflare-template
```

## Storage

<https://developers.cloudflare.com/workers/platform/storage-objects/>

### R2 - S3 object

<https://developers.cloudflare.com/r2/platform/pricing/>

| Product            | Free                        | Paid - Rates             |
| ------------------ | --------------------------- | ------------------------ |
| Storage            | 10 GB / month               | $0.015 / GB-month        |
| Class A Operations | 1 million requests / month  | $4.50 / million requests |
| Class B Operations | 10 million requests / month | $0.36 / million requests |

### KV - key-value

<https://developers.cloudflare.com/workers/reference/storage/namespaces/>

1 GB free: <https://developers.cloudflare.com/workers/platform/pricing/#workers-kv>

Value size 25MB / 100,000 reads per day: <https://developers.cloudflare.com/workers/platform/limits#kv-limits>

### D1 - RDB

<https://developers.cloudflare.com/d1/platform/pricing/>

* only be charged for base storage plus any database operations performed

### Durable Objects - Workers Paid plan

<https://developers.cloudflare.com/workers/learning/using-durable-objects/>

### Queues - Workers Paid plan

job queueing, batching and inter-Service (Worker to Worker) communication.

## Paid

| Product                                                                          | Fee        | Desc                                                                   |
| -------------------------------------------------------------------------------- | ---------- | ---------------------------------------------------------------------- |
| [Workers Paid plan](https://developers.cloudflare.com/workers/platform/pricing/) | $5 / month | separate from any other Cloudflare plan (Free, Professional, Business) |
| Images                                                                           | $5 / month | Store, resize, optimize and serve images at scale                      |
| Stream                                                                           | $5 / month | Live and on-demand video streaming in minutes                          |

## Community

domain: <https://community.cloudflare.com/c/website-application-performance/88>


# cf\_dev

* [Free Lmits](#free-lmits)
* [Worker](#worker)
  * [py](#py)
  * [js](#js)

## Free Lmits

<https://developers.cloudflare.com/workers/platform/limits/>

* CPU time per HTTP request 10 ms

## Worker

<https://developers.cloudflare.com/workers/languages/>

* JavaScript + TypeScript
* Python Workers
* Rust

### py

<https://developers.cloudflare.com/workers/languages/python/>

* beta @ 2026 March

### js

<https://developers.cloudflare.com/workers/tutorials/build-a-qr-code-generator/>

```
npm create cloudflare@latest -- qr-code-generator

npx wrangler deploy
```


# gcp

* [cli](#cli)
* [Tasks](#tasks)
* [GCS](#gcs)
* [fuse](#fuse)

## cli

```
curl https://sdk.cloud.google.com | bash

gcloud auth login
```

<https://cloud.google.com/static/sdk/docs/images/gcloud-cheat-sheet.pdf>

## Tasks

add project non-root ssh key: <https://console.cloud.google.com/compute/metadata?tab=sshkeys>

## GCS

```
export GCSFUSE_REPO=gcsfuse-`lsb_release -c -s`
echo "deb http://packages.cloud.google.com/apt $GCSFUSE_REPO main" | sudo tee /etc/apt/sources.list.d/gcsfuse.list
curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -
sudo apt-get update
sudo apt-get install -y gcsfuse

mkdir gcsfuse
gcsfuse ferro-asia gcsfuse
ls gcsfuse
```

## fuse

<https://cloud.google.com/storage/docs/gcs-fuse>


# github

* [Sponsorships](#sponsorships)
* [Orgs](#orgs)

## Sponsorships

```
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
```

## Orgs

* month-long celebration: <https://github.com/topics/hacktoberfest>


# ibm\_bluemix

* [cli](#cli)
* [Container](#container)
* [external services](#external-services)

## cli

```
curl -fsSL https://clis.ng.bluemix.net/install/linux | sh

docker run --name bluemix \
    -d --restart unless-stopped \
    --privileged --net host \
    reachlin/bluemix
docker exec -it bluemix bash
```

<https://console.bluemix.net/containers-kubernetes/home/clusters>

```
bx plugin list
bx plugin install container-service -r Bluemix
bx plugin update container-service -r Bluemix

bx login -a https://api.eu-de.bluemix.net -sso

bx cs region
bx cs region-set eu-de

bx cs clusters
bx cs cluster-config mycluster

bx cs workers mycluster # check public IP
bx cs worker-update mycluster <node_id>

BLUEMIX_TRACE=path/to/trace.log         # Append API request diagnostics to a log file
BLUEMIX_API_KEY=api_key_value           # API key to use during login
```

## Container

<https://dev-console.stage1.bluemix.net/docs/containers/cs\\_network\\_planning.html>

```
NodePort service (free and standard clusters)
LoadBalancer service (standard clusters only)
Ingress (standard clusters only)
```

![](https://dev-console.stage1.bluemix.net/docs/api/content/containers/images/networking.png?lang=en-US)

```
bx cs cluster-get mycluster # Master URL
```

[k8s related](/container/k8s)

## external services

<https://console.bluemix.net/docs/containers/cs\\_integrations.html#adding\\_cluster>

```
bx service list

name                    service                  plan   bound apps   last operation
Monitoring-tz           Monitoring               lite                create succeeded
Visual Recognition-8p   watson_vision_combined   free                create succeeded
```


# Pricing

* [Always Free](#always-free)
  * [Azure](#azure)
  * [AWS](#aws)
  * [GCP](#gcp)
  * [Oracle](#oracle)
* [Free CI/CD](#free-cicd)
  * [Github](#github)
  * [Jetbrains](#jetbrains)
* [Compare](#compare)
  * [Instance](#instance)
  * [Traffic](#traffic)
* [Price](#price)
  * [AWS](#aws-1)
  * [Azure](#azure-1)
  * [GCP](#gcp-1)
  * [IBM](#ibm)
  * [China](#china)
  * [VPS](#vps)
* [Limited Free](#limited-free)
  * [AWS](#aws-2)
  * [Azure](#azure-2)
  * [IBM](#ibm-1)
  * [VPS](#vps-1)
* [CDN](#cdn)
  * [China](#china-1)

## Always Free

### Azure

<https://azure.microsoft.com/en-us/free/free-account-faq/>

```
Free 2 million characters included for Translator Text API
Free 5 GB per month analysis plus 31-day retention period with Log Analytics    
Azure Maps S0 account tiers offer 250,000 monthly map tile loads and 25,000 monthly service calls

10 web, mobile, or API apps with Azure App Service with 1 GB storage
1 million requests and 400,000 GBs of resource consumption with Azure Functions
100,000 operations for event publishing and delivery with Event Grid
Free Azure Container service to cluster virtual machines
50,000 stored objects with Azure Active Directory with single sign-on (SSO) for 10 apps per user
50,000 active users per month (MAU) with Azure Active Directory B2C
Free Azure Service Fabric to build microservice apps

Unlimited nodes (server or PaaS instance) with Application Insights and 1 GB of telemetry data included per month
Unlimited use of Azure DevTest Labs

Machine Learning with 100 modules and 1 hour per experiment with 10 GB included storage

Free policy assessment and recommendations with Azure Security Center
Unlimited recommendations and best practices with Azure Advisor

Azure IoT Central includes up to 5 devices with 50,000 monthly messages per device
Free Azure IoT Hub edition includes 8,000 messages per day with 0.5 KB message meter size
Free namespace and 1 million push notifications with Azure Notification Hubs

5 free low frequency activities with Azure Data Factory
50 MB storage for 10,000 hosted documents with Azure Cognitive Search including 3 indexes per service

Unlimited Azure Batch usage for job scheduling and cluster management
First 5 users free with Azure DevOps
Free 500 minutes of job run time with Azure Automation
Unlimited users and 5,000 catalog objects with Azure Data Catalog
30,000 transactions per month processing at 20 transactions per minute with Face API

Free public load-balanced IP with Azure Load Balancer
5 GB of bandwidth for outbound data transfer with free unlimited inbound transfer
50 virtual networks free with Azure Virtual Network
Unlimited inbound Inter-VNet data transfer
```

### AWS

<https://aws.amazon.com/free>

```
Lambda: 1M free requests per month
Amazon DynamoDB 25 GB of storage
```

### GCP

<https://cloud.google.com/free/docs/free-cloud-features#free-tier>

```
GAE
    28 hours per day of "F" instances
    9 hours per day of "B" instances
    1 GB of egress per day
GCE
    1 non-preemptible e2-micro: Oregon: us-west1 / Iowa: us-central1 / South Carolina: us-east1
    30 GB-months standard persistent disk | 1 GB network egress except CN/AU
GCS: 5 GB + 1 GB network egress*
Firestore DB: 1 GB storage
```

### Oracle

<https://docs.oracle.com/en-us/iaas/Content/FreeTier/freetier\\_topic-Always\\_Free\\_Resources.htm>

```
2 AMD based Compute VMs Standard.E2.1.Micro with 1/8 OCPU** and 1 GB memory each, in one availability domain | 1 OCPU  = 2 x86 vCPU or 1 ARM vCPU
Arm-based Ampere A1 cores and 24 GB of memory usable as 1 VM or up to 4 Standard.A1.Flex VMs with 3,000 OCPU hours and 18,000 GB hours per month
2 Block Volumes Storage, 200 GB total
10 GB Object Storage – Standard
10 GB Object Storage – Infrequent Access
10 GB Archive Storage
Resource Manager: managed Terraform
5 OCI Bastions
```

## Free CI/CD

### Github

<https://github.com/pricing>

<https://docs.github.com/en/actions/learn-github-actions/usage-limits-billing-and-administration>

<https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions#runners>

<https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners>

### Jetbrains

2,000 Computation Credits per month : <https://www.jetbrains.com/space/buy/?billing=yearly#cloud\\>
1 CC/m = 2 vCPU + 7800MB memory : <https://www.jetbrains.com/help/space/billing-and-limits.html>

## Compare

### Instance

GCP: 20% vCPU + 0.60GB, Free - $4.09\
Azure: 1vCPU + 0.5 GiB, $1.45/m(West US 2, 3-year) Amazon: 5% vCPU + 0.5GB, 3 Year Reserved Instance $69

### Traffic

Amazon: 1GB to 10 TB / month $0.090 per GB, Singapore to China $0.120 per GB\
Google: $0.12 - $0.23 / GB, Singapore to China $0.23\
Microsoft: 5 GB - 10 TB 2 /Month $0.087 - $0.181 per GB, Japan to China $0.138 per GB

## Price

### AWS

<https://aws.amazon.com/ec2/pricing/\\>
<https://aws.amazon.com/ec2/pricing/reserved-instances/pricing/> <https://aws.amazon.com/blogs/aws/ec2-update-t2-nano-instances-now-available/\\>
Traffic: <https://aws.amazon.com/ec2/pricing/on-demand/> <https://calculator.s3.amazonaws.com/index.html>

### Azure

<https://azure.microsoft.com/en-us/support/plans/\\>
<https://docs.microsoft.com/en-us/azure/cost-management-billing/costs/cost-analysis-common-uses#view-cost-breakdown-by-azure-resource>

<https://azure.microsoft.com/en-us/pricing/calculator/\\>
<https://azure.microsoft.com/en-us/pricing/details/app-service/\\>
<https://azure.microsoft.com/en-us/pricing/details/bandwidth/>

```
5 GB - 10 TB /Month: $0.12 per GB
```

<https://azure.microsoft.com/en-us/pricing/details/ip-addresses/>

```
BASIC (CLASSIC) + Dynamic IP address + First Cloud Service VIP = free
```

### GCP

<https://cloud.google.com/pricing/\\>
<https://cloud.google.com/compute/pricing\\>
<https://cloud.google.com/storage/pricing>

### IBM

<https://www.ibm.com/cloud/pricing> <https://ace-docs-production-black.cdn.au-syd.s-bluemix.net/docs/pricing/>

### China

<https://www.aliyun.com/price/product?#/ecs/detail> (Compute)\
<https://help.aliyun.com/document\\_detail/25382.html> (HDD)

<https://www.qcloud.com/document/product/213/2179>

<https://www.qingcloud.com/pricing/plan>

<https://www.sinacloud.com/index/price.html>

<https://www.daocloud.io/pricing/public.html>

### VPS

<https://www.vultr.com/pricing/\\>
<https://www.linode.com/pricing\\>
<https://www.digitalocean.com/pricing/>

## Limited Free

### AWS

<https://aws.amazon.com/free/>

### Azure

$200: <https://azure.microsoft.com/en-us/offers/ms-azr-0044p/>

<https://azure.microsoft.com/en-us/free/>

```
15 GB outbound
```

<https://tryappservice.azure.com>

### IBM

<https://www.ibm.com/cloud/pricing>

### VPS

DigitalOcean $20: <https://cloud.docker.com>

## CDN

### China

JD 动态加速 赠送流量：<https://docs.jdcloud.com/cn/cdn/billing-overview\\>
qn 10G/m/http：<https://www.qiniu.com/prices/qcdn\\>
tx 新户100G/6m： <https://buy.cloud.tencent.com/price/cdn/overview\\>
ali：<https://www.aliyun.com/price/detail/cdn\\>
hw： <https://www.huaweicloud.com/pricing.html#/cdn>

dcloud free: <https://uniapp.dcloud.net.cn/uniCloud/price.html#%E5%85%8D%E8%B4%B9%E9%A2%9D%E5%BA%A6>

云函数： 资源使用量：1000GBs/月 调用次数：1.5万次 出网流量：1GB 云数据库： 集合数量 100 / 索引数量 400 容量：2GB 读操作数：0.05万次/天 写操作数：0.03万次/天 云存储： 容量：5GB 下载操作次数：0.2万次 上传操作次数：0.1万次 CDN流量：1GB 静态网站托管： 容量：5GB CDN流量：1GB


# COS

## coscli

<https://cloud.tencent.com/document/product/436/63670>

```
wget https://cosbrowser.cloud.tencent.com/software/coscli/coscli-linux-amd64
coscli config init #  ~/.cos.yaml

coscli ls # buckets

coscli sync dir1 cos://bucket1 # upload
coscli sync cos://bucket1 dir1 # download
```


# container

## cilium

<https://github.com/cilium/cilium\\>
HTTP, gRPC, and Kafka Aware Security and Networking for Containers with BPF and XDP

## LXD

<https://www.ubuntu.com/cloud/lxd> <http://insights.ubuntu.com/2016/03/14/the-lxd-2-0-story-prologue/> <https://insights.ubuntu.com/2016/04/13/stephane-graber-lxd-2-0-docker-in-lxd-712/>

<https://github.com/lxc/lxd#how-can-i-run-docker-inside-a-lxd-container>


# docker

* [Web UI](#web-ui)
* [Scripts](#scripts)
* [Dockerfile code snippets](#dockerfile-code-snippets)
  * [CMD and ENTRYPOINT](#cmd-and-entrypoint)
  * [apt](#apt)
  * [alpine](#alpine)
  * [tini](#tini)
  * [S6 - a process supervisor](#s6---a-process-supervisor)
* [badger](#badger)
* [Storage](#storage)
  * [btrfs issue](#btrfs-issue)
* [Network](#network)
  * [macvlan/ipvlan](#macvlanipvlan)
  * [plugins](#plugins)
  * [DHCP](#dhcp)
* [Commands](#commands)
  * [build](#build)
  * [container/image operations](#containerimage-operations)
  * [cp](#cp)
  * [run](#run)
    * [X11 Forwarding](#x11-forwarding)
  * [container update](#container-update)
  * [Clean up](#clean-up)
  * [Detach](#detach)
* [Config](#config)
  * [Mirrors](#mirrors)
  * [Proxy](#proxy)
* [Swarm](#swarm)
* [OS](#os)
  * [CoreOS](#coreos)
  * [boot2docker](#boot2docker)
* [Windows/Mac](#windowsmac)
* [Automated builds](#automated-builds)

## Web UI

<https://documentation.portainer.io/v2.0/deploy/ceinstalldocker/>

## Scripts

```
source /dev/stdin <<< "$(curl -sSL https://raw.githubusercontent.com/fzinfz/scripts/master/linux/docker.sh)"
```

## Dockerfile code snippets

### CMD and ENTRYPOINT

<https://docs.docker.com/engine/reference/builder/#understand-how-cmd-and-entrypoint-interact>

```
ENTRYPOINT [“exec_entry”, “p1_entry”]
CMD [“exec_cmd”, “p1_cmd”]
=> exec_entry p1_entry exec_cmd p1_cmd
```

### apt

```
RUN apt update && apt install -y 
    --no-install-recommends && rm -r /var/lib/apt/lists/*
```

### alpine

```
# install pip3
RUN wget https://bootstrap.pypa.io/get-pip.py && python3 get-pip.py && rm get-pip.py

RUN apk add --no-cache --virtual .build-deps  \
    curl ca-certificates jq \
    && apk del .build-deps
```

### tini

<https://github.com/krallin/tini>

```
docker run --init
```

### S6 - a process supervisor

<https://github.com/just-containers/s6-overlay>

## badger

<https://microbadger.com>

## Storage

<https://docs.docker.com/storage/storagedriver/select-storage-driver/#docker-engine---community>

```
When possible, overlay2 is the recommended storage driver. 
Supported backing filesystems: xfs with ftype=1, ext4 ( where /var/lib/docker/ is located )
```

<http://jpetazzo.github.io/assets/2015-06-04-deep-dive-into-docker-storage-drivers.html#80>

### btrfs issue

<https://gist.github.com/hopeseekr/cd2058e71d01deca5bae9f4e5a555440>

## Network

none/bridge/host/overlay/{belows}: <https://docs.docker.com/network/>

### macvlan/ipvlan

<https://hicu.be/macvlan-vs-ipvlan>

* Ipvlan：All sub-interfaces share parent’s MAC | vs Macvlan
* Ipvlan L3 mode：Each sub-interface has to be configured with a different subnet
* Macvlan and ipvlan cannot be used on the same parent interface at the same time.

<https://docs.docker.com/network/ipvlan/>

* IPvlan L2 mode trunking is the same as Macvlan with regard to gateways and L2 path isolation.
* `--internal`: ( off `-o parent=` )
* if no `--gateway`: gw for `--subnet=192.168.1.0/24` will be 192.168.1.1

To access host, check [/nw/openwrt](https://github.com/fzinfz/book/blob/master/nw/openwrt/README.md)

### plugins

<https://docs.docker.com/engine/extend/plugins\\_services/#network-plugins>

### DHCP

* <https://github.com/homeall/dhcphelper>
* <https://github.com/modem7/DHCP-Relay>

## Commands

### build

<https://docs.docker.com/engine/reference/commandline/build/>

```
docker build [-f Dockerfile.custom] [--target multi-stage] Dockerfile-Root-Folder

docker build - < Dockerfile      # no context, local ADD not working
curl example.com/remote/Dockerfile | docker build -f - .
Get-Content Dockerfile | docker build - # Powershell

docker build -f ctx/Dockerfile http://server/ctx.tar.gz
docker build https://github.com/user/repo.git
```

| Build Syntax Suffix          | Commit Used         | Build Context Used |
| ---------------------------- | ------------------- | ------------------ |
| myrepo.git#mytag:myfolder    | refs/tags/mytag     | /myfolder          |
| myrepo.git#mybranch:myfolder | refs/heads/mybranch | /myfolder          |

Squashing does not destroy any existing image, rather it creates a new image.

### container/image operations

```
docker image tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]

docker export container_name > container.tar
docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]

docker save image_name > image.tar
docker load < image.tar[.gz]

docker save python | ssh -C 192.168.88.72 docker load
```

### cp

<https://docs.docker.com/engine/reference/commandline/cp/>

```
docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
    
```

### run

<https://docs.docker.com/engine/reference/run/\\>
<https://docs.docker.com/engine/admin/resource\\_constraints/>

```
--user=[ user | user:group | uid | uid:gid | user:gid | uid:group ]

-m, --memory=""
-c, --cpu-shares=0	CPU shares (relative weight)
--dns=[]           : Set custom dns servers for the container
--network="bridge" : Connect a container to a network
                      'bridge': create a network stack on the default Docker bridge
                      'none': no networking
                      'container:<name|id>': reuse another container's network stack
                      'host': use the Docker host network stack
                      '<network-name>|<network-id>': connect to a user-defined network
--network-alias=[] : Add network-scoped alias for the container
--add-host=""      : Add a line to /etc/hosts (host:IP)
--mac-address=""   : Sets the container's Ethernet device's MAC address
--ip=""            : Sets the container's Ethernet device's IPv4 address
--link-local-ip=[] : Sets one or more container's Ethernet device's link local IPv4/IPv6 addresses
--read-only        ：prohibiting writes to locations other than the specified volumes

Volume labels  
`:z` => shared  
`:Z` => private

`--entrypoint` will clear out `CMD`

echo test | docker run --rm -i alpine cat
docker run --security-opt seccomp:unconfined  # may fix chromium start error
```

#### X11 Forwarding

<http://wiki.ros.org/docker/Tutorials/GUI\\>
<https://people.ece.cornell.edu/skand/post/x-forwarding-on-docker/>

```
--env="DISPLAY" --volume="$HOME/.Xauthority:/root/.Xauthority:rw"
```

### container update

<https://docs.docker.com/engine/reference/commandline/container\\_update/>

docker container update \[OPTIONS] CONTAINER \[CONTAINER...] --cpus="1.5" # one and a half of the CPUs --cpu-shares , -c --memory , -m Memory limit --memory-reservation Memory soft limit --restart

### Clean up

```
docker container prune
docker system prune  # Remove unused data
```

### Detach

```
Ctrl+p & Ctrl+q
```

## Config

<https://docs.docker.com/engine/reference/commandline/dockerd//#daemon-configuration-file>

```
/etc/docker/daemon.json     # delete `,` & `#...`
# `dockerd` for debugging: https://docs.docker.com/engine/admin/
{
    "live-restore": true,   # containers remain running if daemon unavailable
    "graph": "/data/docker-fs",
    "storage-driver": "overlay2",
}
```

### Mirrors

CN: <https://yeasy.gitbook.io/docker\\_practice/install/mirror> LAN: <https://docs.docker.com/registry/configuration/#proxy>

### Proxy

23.0+ : <https://docs.docker.com/reference/cli/dockerd/#proxy-configuration>

* daemon configuration file : /etc/docker/daemon.json
  * <https://docs.docker.com/reference/cli/dockerd/#daemon-configuration-file>
* command-line options : <https://pkg.go.dev/golang.org/x/net/http/httpproxy#Config>

<https://docs.docker.com/config/daemon/proxy/#environment-variables>

```
mkdir -p /etc/systemd/system/docker.service.d

cat > /etc/systemd/system/docker.service.d/http-proxy.conf << EOF
[Service]
Environment="HTTP_PROXY=http://127.0.0.1:1081"
Environment="HTTPS_PROXY=http://127.0.0.1:1081"
Environment="NO_PROXY=localhost,127.0.0.1,192.168.*.*,172.16.*.*,100.*.*.*"
EOF

systemctl daemon-reload && systemctl restart docker
systemctl show --property=Environment docker
```

## Swarm

TCP port 2377 for cluster management communications TCP and UDP port 7946 for communication among nodes TCP and UDP port 4789 for overlay network traffic --opt encrypted => protocol 50 (ESP) is open

<https://docs.docker.com/engine/swarm/admin\\_guide/#/add-manager-nodes-for-fault-tolerance>

```
docker swarm init --advertise-addr 10.2.0.1
docker swarm join-token manager
docker swarm join-token worker
docker swarm init --force-new-cluster # without losing data

docker node ls
docker node update --label-add server=s1 st

netstat -lntup | egrep '2377|7946|4789|50'

docker service create --name nginx -p 8080:80 --replicas 3 nginx
docker service create --name nginx -p 80:80  -p 443:443 --network web --mode global nginx

docker service ls
docker service ps nginx
docker inspect <ID> | grep Err
```

<https://docs.docker.com/engine/reference/commandline/service\\_create/>

```
docker network create \
    --driver overlay \
    --subnet 10.66.3.0/24 \
    --opt encrypted \
    web

docker network ls

# node IP
ip addr | grep -P -o '\d+\.\d+\.\d+\.\d+(?=/24)'

# service VIP
ip addr | grep -P -o '\d+\.(?!255)\d+\.\d+\.\d+(?=/32)'
```

## OS

### CoreOS

<https://coreos.com/releases/>

```
vi /etc/coreos/update.conf
update_engine_client -update
```

### boot2docker

<https://github.com/boot2docker/boot2docker\\>
Lightweight Linux for Docker

```
echo EXTRA_ARGS="--foo=bar"  >>  /var/lib/boot2docker/profile
```

## Windows/Mac

<https://docs.docker.com/engine/installation/windows/\\>
<https://docs.docker.com/machine/drivers/\\>
<https://forums.docker.com/t/how-can-i-ssh-into-the-betas-mobylinuxvm/10991/>

## Automated builds

Docker Hub | $5+/m: <https://www.docker.com/pricing/\\>
Github Actions | 2k min/m: <https://docs.docker.com/ci-cd/github-actions/\\>
Jetbrains Space |

<https://www.jetbrains.com/help/space/docker.html#publish-a-docker-image-to-docker-hub>


# Kubernetes

* [Docs](/container/k8s#docs)
* [Components](/container/k8s#components)
* [Creating HA clusters](/container/k8s#creating-ha-clusters)
* [Objects](/container/k8s#objects)
  * [namespaces](/container/k8s#namespaces)
* [controllers](/container/k8s#controllers)
  * [ReplicaSet](/container/k8s#replicaset)
  * [Replication Controller](/container/k8s#replication-controller)
  * [Deployment controller](/container/k8s#deployment-controller)
  * [StatefulSet](/container/k8s#statefulset)
  * [DaemonSet](/container/k8s#daemonset)
  * [Job & CronJob](/container/k8s#job--cronjob)
* [kubectl](/container/k8s#kubectl)
* [dashboard admin](/container/k8s#dashboard-admin)
* [expose](/container/k8s#expose)
* [token](/container/k8s#token)
* [Tutorial](/container/k8s#tutorial)
* [yaml](/container/k8s#yaml)
  * [syntax](/container/k8s#syntax)
    * [env](/container/k8s#env)
    * [Command and Arguments](/container/k8s#command-and-arguments)
  * [generator](/container/k8s#generator)
* [Verbosity](/container/k8s#verbosity)
* [minikube](/container/k8s#minikube)
  * [Bare metal](/container/k8s#bare-metal)
  * [KVM](/container/k8s#kvm)
* [kops](/container/k8s#kops)
* [Create a Cluster](/container/k8s#create-a-cluster)
* [Persistent Volumes](/container/k8s#persistent-volumes)
* [helm - package manager](/container/k8s#helm---package-manager)
  * [WebUI](/container/k8s#webui)
  * [Hub](/container/k8s#hub)

## Docs

<https://kubernetes.io/docs/setup/pick-right-solution/#table-of-solutions>

<https://kubernetes.io/docs/reference/kubectl/cheatsheet/>

<https://kubernetes.io/docs/reference/kubectl/docker-cli-to-kubectl/>

```
kubectl run --image=nginx nginx-app --port=80 --env="DOMAIN=cluster" # deployment "nginx-app" created
kubectl expose deployment nginx-app --port=80 --name=nginx-http      # service "nginx-http" exposed
kubectl exec nginx-app-5jyvm -- cat /etc/hostname

kubectl get deployment
kubectl get pods -a
kubectl logs <pod_name>
kubectl version --short
```

## Components

<https://kubernetes.io/docs/concepts/overview/components/>

## Creating HA clusters

<https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/high-availability/>

## Objects

<https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects/>

persistent entities\
All objects in REST API are identified by a Name(such as /api/v1/pods/some-name) and a UID.\
For non-unique user-provided attributes, Kubernetes provides labels and annotations.

### namespaces

multiple virtual clusters backed by the same physical cluster

```
kubectl get namespaces

NAME             STATUS    AGE
default          Active    59d
ibm-cert-store   Active    59d
ibm-system       Active    59d
kube-public      Active    59d
kube-system      Active    59d

default: for objects with no other namespace
kube-system: created by the Kubernetes system
kube-public: readable by all users. reserved for cluster usage, in case that some resources should be visible and readable publicly throughout the whole cluster. The public aspect of this namespace is only a convention, not a requirement
```

## controllers

### ReplicaSet

ReplicaSet is the next-generation Replication Controller.\
ReplicaSet supports the new set-based selector requirements

```
kubectl get pods -l 'environment,environment notin (frontend)'
```

### Replication Controller

only supports equality-based selector requirements.

```
kubectl get pods -l environment=production,tier=frontend
```

### Deployment controller

<https://kubernetes.io/docs/concepts/workloads/controllers/deployment/>\
provides declarative updates for Pods and ReplicaSets.

### StatefulSet

workload API object used to manage stateful applications.\
Unlike a Deployment, a StatefulSet maintains a sticky identity for each of their Pods.

```
Stable, unique network identifiers.
Stable, persistent storage.
Ordered, graceful deployment and scaling.
Ordered, graceful deletion and termination.
Ordered, automated rolling updates.
```

### DaemonSet

ensures that all (or some) Nodes run a copy of a Pod.

### Job & CronJob

<https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/>

## kubectl

<https://kubernetes.io/docs/tasks/tools/install-kubectl/>

```
curl -LO https://storage.googleapis.com/kubernetes-release/release/$( \
    curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt \
    )/bin/linux/amd64/kubectl
chmod +x kubectl && mv kubectl /usr/local/bin/

sudo snap install kubectl --classic

kubectl get nodes
export KUBECONFIG=/path/to/kube-config-mil01-mycluster.yml # 
kubectl proxy --address='0.0.0.0' --accept-hosts='.*' --port=8080
kubectl proxy --address=$IP_Private --accept-hosts='^.*$' # http://...:8080/ui
```

## dashboard admin

<https://github.com/kubernetes/dashboard/wiki/Access-control#admin-privileges>

## expose

<https://kubernetes.io/docs/tasks/access-application-cluster/port-forward-access-application-cluster/>

```
kubectl port-forward redis-master 6379:6379
```

`kubectl expose -h`

```
pod (po), service (svc), replicationcontroller (rc), deployment (deploy), replicaset (rs)

# Create a service for a replicated nginx, which serves on port 80 and connects to the containers on port 8000.
kubectl expose rc nginx --port=80 --target-port=8000

# Create a service for a replication controller identified by type and name specified in "nginx-controller.yaml",
which serves on port 80 and connects to the containers on port 8000.
kubectl expose -f nginx-controller.yaml --port=80 --target-port=8000

# Create a service for a pod valid-pod, which serves on port 444 with the name "frontend"
kubectl expose pod valid-pod --port=444 --name=frontend

# Create a second service based on the above service, exposing the container port 8443 as port 443 with the name
"nginx-https"
kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https

# Create a service for a replicated streaming application on port 4100 balancing UDP traffic and named 'video-stream'.
kubectl expose rc streamer --port=4100 --protocol=udp --name=video-stream

# Create a service for a replicated nginx using replica set, which serves on port 80 and connects to the containers on
port 8000.
kubectl expose rs nginx --port=80 --target-port=8000

# Create a service for an nginx deployment, which serves on port 80 and connects to the containers on port 8000.
kubectl expose deployment nginx --port=80 --target-port=8000
```

## token

```
kubectl describe secret
kubectl config view -o jsonpath='{.users[0].user.auth-provider.config.id-token}'
```

## Tutorial

```
kubectl run nginx --image=nginx
kubectl create deployment nginx --image nginx   # do the same thing as above

kubectl expose deployment/nginx --name=nginx --type=NodePort --port=80 --target-port=80
kubectl describe services nginx

kubectl run hello-world --replicas=2 \
    --labels="run=load-balancer-example" \
    --image=gcr.io/google-samples/node-hello:1.0  \
    --port=8080

kubectl get deployments hello-world
kubectl describe deployments hello-world

kubectl get replicasets
kubectl describe replicasets

kubectl expose deployment hello-world --type=LoadBalancer --name=my-service
kubectl describe services my-service

kubectl get services
```

## yaml

Release 1.8: `apps/v1beta1` -> `apps/v1beta2`; 1.9： -> `apps/v1`

```
kubectl create -f nginx.yaml
kubectl replace -f nginx.yaml   # updates from another source will be lost
kubectl delete -f nginx.yaml -f redis.yaml
```

`kubectl apply` supports multiple writers to the same object.

```
kubectl apply -f configs/
kubectl apply -R -f configs/    # Recursively 

kubectl get -f https://example.com/x.yaml -o yaml                   # print
kubectl get <kind>/<name> -o yaml --export > <kind>_<name>.yaml     # export
```

### syntax

<https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.9/> <https://kubernetes.io/docs/concepts/overview/object-management-kubectl/declarative-config/>

#### env

<https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/>

#### Command and Arguments

<https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/>

| Description                         | Docker field name | Kubernetes field name |
| ----------------------------------- | ----------------- | --------------------- |
| The command run by the container    | Entrypoint        | command               |
| The arguments passed to the command | Cmd               | args                  |

```
spec:
containers:
- name: command-demo-container
    image: debian
    command: ["printenv"]
    args: ["HOSTNAME", "KUBERNETES_PORT"]

    command:
    - sh
    - -c
    - while true; do sleep 1; done
```

Example： <https://github.com/kubernetes/kubernetes/blob/master/examples/guestbook/all-in-one/guestbook-all-in-one.yaml>

### generator

<https://github.com/grafana/tanka>

## Verbosity

| Verbosity | Description                                                                                                                                                                                       |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| --v=0     | Generally useful for this to ALWAYS be visible to an operator.                                                                                                                                    |
| --v=1     | A reasonable default log level if you don’t want verbosity.                                                                                                                                       |
| --v=2     | Useful steady state information about the service and important log messages that may correlate to significant changes in the system. This is the recommended default log level for most systems. |
| --v=3     | Extended information about changes.                                                                                                                                                               |
| --v=4     | Debug level verbosity.                                                                                                                                                                            |
| --v=6     | Display requested resources.                                                                                                                                                                      |
| --v=7     | Display HTTP request headers.                                                                                                                                                                     |
| --v=8     | Display HTTP request contents.                                                                                                                                                                    |

## minikube

<https://github.com/kubernetes/minikube>

```
curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
curl -Lo kubectl https://storage.googleapis.com/kubernetes-release/release/v1.8.0/bin/linux/amd64/kubectl
chmod +x minikube kubectl  && mv minikube kubectl /usr/local/bin/
```

### Bare metal

<https://minikube.sigs.k8s.io/docs/start/linux/>

```
minikube start --vm-driver=none && minikube config set vm-driver none
minikube logs
```

### KVM

<https://github.com/kubernetes/minikube/blob/master/docs/drivers.md#kvm-driver>

```
sudo usermod -a -G libvirt $(whoami)
newgrp libvirt
minikube config set vm-driver kvm
```

<https://github.com/dhiltgen/docker-machine-kvm> <https://github.com/docker/machine/releases>

## kops

<https://github.com/kubernetes/kops#linux>\
kubectl for clusters

## Create a Cluster

<https://kubernetes.io/docs/setup/independent/create-cluster-kubeadm/> <https://kubernetes.io/docs/getting-started-guides/scratch/#designing-and-preparing>

## Persistent Volumes

<https://kubernetes.io/docs/concepts/storage/persistent-volumes/>

```
apiVersion: v1
kind: PersistentVolume
metadata:
name: pv0003
spec:
capacity:
    storage: 5Gi
volumeMode: Filesystem
accessModes:
    - ReadWriteOnce
persistentVolumeReclaimPolicy: Recycle
storageClassName: slow
mountOptions:
    - hard
    - nfsvers=4.1
nfs:
    path: /tmp
    server: 172.17.0.2
```

| Volume Plugin        | ReadWriteOnce | ReadOnlyMany | ReadWriteMany                      |
| -------------------- | ------------- | ------------ | ---------------------------------- |
| AWSElasticBlockStore | ✓             | -            | -                                  |
| AzureFile            | ✓             | ✓            | ✓                                  |
| AzureDisk            | ✓             | -            | -                                  |
| CephFS               | ✓             | ✓            | ✓                                  |
| Cinder               | ✓             | -            | -                                  |
| FC                   | ✓             | ✓            | -                                  |
| FlexVolume           | ✓             | ✓            | -                                  |
| Flocker              | ✓             | -            | -                                  |
| GCEPersistentDisk    | ✓             | ✓            | -                                  |
| Glusterfs            | ✓             | ✓            | ✓                                  |
| HostPath             | ✓             | -            | -                                  |
| iSCSI                | ✓             | ✓            | -                                  |
| PhotonPersistentDisk | ✓             | -            | -                                  |
| Quobyte              | ✓             | ✓            | ✓                                  |
| NFS                  | ✓             | ✓            | ✓                                  |
| RBD                  | ✓             | ✓            | -                                  |
| VsphereVolume        | ✓             | -            | - (works when pods are collocated) |
| PortworxVolume       | ✓             | -            | ✓                                  |
| ScaleIO              | ✓             | ✓            | -                                  |
| StorageOS            | ✓             | -            | -                                  |

## helm - package manager

<https://docs.helm.sh/using_helm/#quickstart>

### WebUI

<https://github.com/kubernetes-helm/monocular>

```
helm repo add monocular https://kubernetes-helm.github.io/monocular
helm install monocular/monocular
kubectl get ingress
```

<https://github.com/kubeapps/hub>\
navigate and search Helm Charts.

### Hub

<https://hub.kubeapps.com/>


# lxc-pve

* [Images](#images)
* [Proxmox Container Toolkit](#proxmox-container-toolkit)
* [share host folder](#share-host-folder)
* [Unprivileged](#unprivileged)

## Images

```
pveam update # daily through the `pve-daily-update` timer
pveam available --section system
pveam list local
pveam download local {}.tar.gz # WebUI `CT Templates`: click `Templates` button
```

## Proxmox Container Toolkit

```
pct list
pct exec 201 -- bash -lc "volta list all" 
# `-l` = login shell, loads `.profile`/`.bash_profile`
```

## share host folder

<https://github.com/fzinfz/scripts/blob/master/pve\\_ct/mount.sh>

```
pct set 201 -mp1 /data,mp=/data 
```

## Unprivileged

```
apt install acl
setfacl -m u:100000:rwx /host/folder/path
```


# podman

* [Config](#config)
* [CLI](#cli)
* [network](#network)
  * [Netavark](#netavark)
  * [CNI](#cni)
    * [DHCP](#dhcp)
  * [create](#create)

## Config

V2: /etc/containers/registries.conf

```
unqualified-search-registries = ["docker.io"]
```

## CLI

```
podman search docker.io/KEYWORD
```

## network

<https://docs.podman.io/en/latest/markdown/podman-network.1.html>

* Netavark is the default network backend and was added in Podman v4.0
* CNI will be deprecated

<https://github.com/containers/common/blob/main/docs/containers.conf.5.md#network-table>

/etc/containers/containers.conf

```
[network]
network_backend="" # cni / netavark
```

```
podman network inspect podman
```

### Netavark

<https://www.redhat.com/sysadmin/podman-new-network-stack>

* Better IPv6 support
* Improved support for containers in multiple networks
* Improved performance

### CNI

cni\_config\_dir in containers.conf: /etc/cni/net.d

DHCP: <https://www.cni.dev/plugins/v0.8/ipam/dhcp/>

### create

<https://docs.podman.io/en/latest/markdown/podman-network-create.1.html>

`--driver`

* bridge
* macvlan
* ipvlan

`--ipam-driver`

* dhcp: not yet supported with netavark | For CNI the dhcp plugin needs to be activated before.
* host-local
* none


# db

* [Couchbase vs CouchDB](#couchbase-vs-couchdb)
* [API Query](#api-query)
* [key-value](#key-value)
* [Time Series DBs](#time-series-dbs)
* [TimescaleDB](#timescaledb)
* [Riak TS](#riak-ts)
* [Firebase](#firebase)
* [Supabase](#supabase)

## Couchbase vs CouchDB

<https://www.couchbase.com/couchbase-vs-couchdb>

|| Couchbase Server|Apache CouchDB| |---|---| |Topology|Distributed|Replicated| |Automatic failover|Yes|No| |Integrated cache|Yes|No| |Memcached compatible|Yes|No| |Query language|Yes, N1QL (SQL for JSON)|No|

## API Query

<http://graphql.org/>

## key-value

<https://github.com/dgraph-io/badger>

## Time Series DBs

Why relational database instead of NoSQL: <https://blog.timescale.com/time-series-data-why-and-how-to-use-a-relational-database-instead-of-nosql-d0cd6975e87c>

Elastic, InfluxDB, MongoDB, Cassandra, Couchbase, Graphite, Prometheus, ClickHouse, OpenTSDB, DalmatinerDB, KairosDB, RiakTS.

## TimescaleDB

<https://github.com/timescale/timescaledb\\>
packaged as a PostgreSQL extension

<http://docs.timescale.com/v0.8/getting-started/installation/linux/installation-docker>

```
docker run -d --name timescaledb -p 5432:5432 timescale/timescaledb
```

<https://blog.timescale.com/when-boring-is-awesome-building-a-scalable-time-series-database-on-postgresql-2900ea453ee2>

<http://docs.timescale.com/v0.8/getting-started/creating-hypertables>

```
CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;

SELECT create_hypertable('conditions', 'time');
-- backgroud:
CREATE INDEX conditions_time_idx
    ON public.conditions USING btree
    ("time" DESC)
    TABLESPACE pg_default;

-- additionally partition the data on another
--   dimension (what we call 'space partitioning').
-- E.g., to partition `location` into 4 partitions:
SELECT create_hypertable('conditions', 'time', 'location', 4);

SELECT time_bucket('5 minutes', time) AS time_range,
    location, COUNT(*),
    MAX(temperature) AS max_temp,
    MAX(humidity) AS max_hum
FROM conditions
WHERE time > NOW() - interval '3 hours'
GROUP BY time_range, location
ORDER BY time_range DESC, max_temp DESC;

    time_range       | location | count | max_temp | max_hum 
------------------------+----------+-------+----------+---------
2018-02-23 17:00:00+00 | office   |     3 |       70 |      50
2018-02-23 16:35:00+00 | garage   |     1 |       77 |    65.2
2018-02-23 16:35:00+00 | office   |     2 |     70.1 |    50.1
2018-02-23 16:35:00+00 | basement |     1 |     66.5 |      60
2018-02-23 16:25:00+00 | office   |     1 |       70 |      50
(5 rows)
```

## Riak TS

<http://docs.basho.com/riak/ts/\\>
Riak TS is a distributed NoSQL key/value store optimized for time series data.

## Firebase

Realtime NoSQL: <https://firebase.google.com/pricing>

## Supabase

Firebase alternative, PostgreSQL

* OSS: <https://github.com/supabase/supabase>
* <https://supabase.com/pricing>


# InfluxDB

* [Data Format](#data-format)
* [Client](#client)
  * [cli](#cli)
  * [Python](#python)
* [Flux Query](#flux-query)
  * [difference()](#difference)

## Data Format

```
<measurement>[,<tag-key>=<tag-value>...] \
<field-key>=<field-value>[,<field2-key>=<field2-value>...] \
[unix-nano-timestamp]
```

## Client

### cli

<https://docs.influxdata.com/influxdb/cloud/reference/cli/influx/#credential-precedence>

```
for c in version config ; do docker exec -it influxdb influx $c ; done
docker exec -it influxdb influx bucket list --org $INFLUXDB_ORG --token $INFLUXDB_TOKEN
```

### Python

<https://docs.influxdata.com/influxdb/cloud/tools/client-libraries/python/\\>
<https://github.com/influxdata/influxdb-client-python#pip-install>

## Flux Query

<https://docs.influxdata.com/influxdb/v2.0/query-data/flux/>

### difference()

<https://docs.influxdata.com/influxdb/v2.0/reference/flux/stdlib/built-in/transformations/difference/>


# loki

* [API](/db/loki#api)
  * [Query](/db/loki#query)
* [Python](/db/loki#python)

## API

### Query

<https://grafana.com/docs/loki/latest/api/#examples>

```
curl -G -s  "http://localhost:3100/loki/api/v1/query" \
    --data-urlencode 'query=sum(rate({job="varlogs"}[10m])) by (level)' \
    | jq
```

## Python

<https://pypi.org/project/python-logging-loki/>


# MySQL & MariaDB

* [Storage Engines](/db/mysql#storage-engines)
* [MySQL Cluster](/db/mysql#mysql-cluster)
* [JSON](/db/mysql#json)
  * [MySQL 5.7+](/db/mysql#mysql-57)
  * [MariaDB 10.2+](/db/mysql#mariadb-102)

## Storage Engines

<https://dev.mysql.com/doc/refman/5.7/en/storage-engines.html>\
Compare: Table 15.1 Storage Engines Feature Summary

| Feature                               | MyISAM  | Memory      | InnoDB  | Archive | NDB     |
| ------------------------------------- | ------- | ----------- | ------- | ------- | ------- |
| Storage limits                        | 256TB   | RAM         | 64TB    | None    | 384EB   |
| Transactions                          | No      | No          | Yes     | No      | Yes     |
| Locking granularity                   | Table   | Table       | Row     | Row     | Row     |
| MVCC                                  | No      | No          | Yes     | No      | No      |
| Geospatial data type support          | Yes     | No          | Yes     | Yes     | Yes     |
| Geospatial indexing support           | Yes     | No          | Yes\[a] | No      | No      |
| B-tree indexes                        | Yes     | Yes         | Yes     | No      | No      |
| T-tree indexes                        | No      | No          | No      | No      | Yes     |
| Hash indexes                          | No      | Yes         | No\[b]  | No      | Yes     |
| Full-text search indexes              | Yes     | No          | Yes\[c] | No      | No      |
| Clustered indexes                     | No      | No          | Yes     | No      | No      |
| Data caches                           | No      | N/A         | Yes     | No      | Yes     |
| Index caches                          | Yes     | N/A         | Yes     | No      | Yes     |
| Compressed data                       | Yes\[d] | No          | Yes\[e] | Yes     | No      |
| Encrypted data\[f]                    | Yes     | Yes         | Yes     | Yes     | Yes     |
| Cluster database support              | No      | No          | No      | No      | Yes     |
| Replication support\[g]               | Yes     | Limited\[h] | Yes     | Yes     | Yes     |
| Foreign key support                   | No      | No          | Yes     | No      | Yes\[i] |
| Backup / point-in-time recovery\[j]   | Yes     | Yes         | Yes     | Yes     | Yes     |
| Query cache support                   | Yes     | Yes         | Yes     | Yes     | Yes     |
| Update statistics for data dictionary | Yes     | Yes         | Yes     | Yes     | Yes     |

```
CREATE TABLE t1 (i INT) ENGINE = INNODB;

InnoDB: default in MySQL 5.7. 
    transaction-safe (ACID compliant)：commit, rollback, and crash-recovery
    row-level locking (without escalation to coarser granularity locks) 
    Oracle-style consistent nonlocking reads
    clustered indexes to reduce I/O for common queries based on primary keys
    FOREIGN KEY referential-integrity constraints
MyISAM: 
    Table-level locking. 
    often used in read-only or read-mostly workloads.
Merge: 
    logically group a series of identical MyISAM tables and reference them as one object.     
Memory or HEAP:
    Its use cases are decreasing:
        InnoDB with its buffer pool memory area
        NDBCLUSTER provides fast key-value lookups for huge distributed data sets
NDB or NDBCLUSTER: highest possible degree of uptime and availability.
Federated: link separate MySQL servers to create one logical database
CSV: Its tables are really text files with comma-separated values.
Archive: compact, unindexed tables
Blackhole: 
    not store data, Queries always return an empty set. 
    can be used in replication configurations
Example: illustrates how to begin writing new storage engines.
```

## MySQL Cluster

<http://severalnines.com/blog/mysql-docker-introduction-docker-swarm-mode-and-multi-host-networking>\
<https://dev.mysql.com/doc/refman/5.7/en/mysql-cluster-ndb-innodb-engines.html>

## JSON

### MySQL 5.7+

<https://dev.mysql.com/doc/refman/5.7/en/json.html>

```
CREATE TABLE t1 (jdoc JSON);
INSERT INTO t1 VALUES('{"key1": "value1", "key2": "value2"}');

SELECT JSON_ARRAY('a', 1, NOW());
SELECT JSON_OBJECT('key1', 1, 'key2', 'abc');
SELECT JSON_MERGE('["a", 1]', '{"key": "value"}');

SET @j = JSON_OBJECT('key', 'value');
SELECT @j;

# escape quote character
'{"mascot": "... \\"Sakila\\"."}'
JSON_OBJECT("mascot", "... \"Sakila\".")
JSON_OBJECT('mascot', '... "Sakila".')    # NO_BACKSLASH_ESCAPES

# JSON values is case sensitive
SELECT CAST('null' AS JSON); # `null`, `true`, and `false` always lowercase

SELECT col->"$.mascot" FROM qtest;          # "... \"Sakila\"."
SELECT sentence->>"$.mascot" FROM facts;    # ... "Sakila".

ORDER BY CAST(JSON_EXTRACT(jdoc, '$.id') AS UNSIGNED)
```

### MariaDB 10.2+

<https://mariadb.com/resources/blog/json-mariadb-102>

```
CREATE TABLE products(id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
price DECIMAL(9,2) NOT NULL,
stock INTEGER NOT NULL,
attr VARCHAR(1024),
CHECK (attr IS NULL OR JSON_VALID(attr)));

INSERT INTO products VALUES(NULL, 'Blouse', 17, 15, '{"colour": "white"}');
UPDATE products SET attr = JSON_REPLACE(attr, '$.colour', 'red') WHERE name = 'Blouse';

ALTER TABLE products ADD attr_colour VARCHAR(32) AS (JSON_VALUE(attr, '$.colour'));

CREATE INDEX products_attr_colour_ix ON products(attr_colour);
EXPLAIN SELECT * FROM products WHERE attr_colour = 'white';     # verify index
```


# Oracle

* [Storage](/db/oracle#storage)
* [Tools](/db/oracle#tools)
* [User](/db/oracle#user)
* [Create Table](/db/oracle#create-table)
* [Create Procedure](/db/oracle#create-procedure)

## Storage

<https://docs.oracle.com/cloud/latest/db112/CNCPT/logical.htm#CNCPT3000>

![](https://docs.oracle.com/cloud/latest/db112/CNCPT/img/cncpt227.gif) ![](https://docs.oracle.com/cloud/latest/db112/CNCPT/img/cncpt027.gif)

A `tablespace` is a logical storage container for segments. Segments are database objects, such as tables and indexes, that consume storage space.\
A `segment` is a set of extents allocated for a specific database object, such as a table. Each segment belongs to one and only one tablespace.\
An `extent` is a set of logically contiguous data blocks allocated for storing a specific type of information.\
One `logical data block` corresponds to a specific number of bytes of physical disk space, for example, 2 KB.

## Tools

<http://www.oracle.com/technetwork/developer-tools/index.html>

## User

```
ALTER USER hr ACCOUNT UNLOCK;
ALTER USER hr IDENTIFIED BY hr_password;
```

## Create Table

<https://docs.oracle.com/cd/B28359_01/server.111/b28310/tables003.htm#ADMIN11004> ![](https://docs.oracle.com/cd/B28359_01/server.111/b28286/img/create_table.gif)

```
CREATE TABLE "HR"."COUNTRIES" 
(
"COUNTRY_ID" CHAR(2 BYTE) 
    CONSTRAINT "COUNTRY_ID_NN" NOT NULL ENABLE, 
```

![](https://docs.oracle.com/cd/B19306_01/server.102/b14200/img/inline_constraint.gif)\
<https://docs.oracle.com/cd/B19306_01/server.102/b14200/clauses002.htm>

```
"COUNTRY_NAME" VARCHAR2(40 BYTE), 
"REGION_ID" NUMBER, 
    CONSTRAINT "COUNTRY_C_ID_PK" PRIMARY KEY ("COUNTRY_ID") ENABLE, 
    CONSTRAINT "COUNTR_REG_FK" FOREIGN KEY ("REGION_ID")
```

![](https://docs.oracle.com/cd/B19306_01/server.102/b14200/img/out_of_line_constraint.gif)

```
    REFERENCES "HR"."REGIONS" ("REGION_ID") ENABLE
```

![](https://docs.oracle.com/cd/B19306_01/server.102/b14200/img/references_clause.gif) ![](https://docs.oracle.com/cd/B19306_01/server.102/b14200/img/constraint_state.gif)

```
) 
ORGANIZATION INDEX -- index-organized table. 
```

ORGANIZATION: the order in which the data rows of the table are stored.

* HEAP: the data rows of table are stored in no particular order. This is the *default*.
* INDEX: table is created as an index-organized table. In an index-organized table, the data rows are held in an index defined on the primary key for the table.
* EXTERNAL: table is a read-only table located outside the database.

  NOCOMPRESS -- whether to compress data segments to reduce disk use PCTFREE 10 -- NOCOMPRESS use the PCTFREE default value of 10, to maximize compress while still allowing for some future DML changes to the data INITRANS 2 -- Specify the initial number of concurrent transaction entries allocated within each data block allocated to the database object. MAXTRANS 255 -- deprecated. LOGGING -- a database object will be logged in the redo log file

<https://docs.oracle.com/cd/B28359_01/server.111/b28286/clauses.htm#SQLRF021>

```
STORAGE(
    INITIAL 65536 -- the size of the first extent of the object. allocates space when you create the schema object.
    NEXT 1048576 -- in bytes the size of the next extent to be allocated to the object.
    MINEXTENTS 1 -- In locally managed tablespaces, determine the initial segment size in conjunction with PCTINCREASE, INITIAL and NEXT
    MAXEXTENTS 2147483645 -- valid only for objects in dictionary-managed tablespaces
    PCTINCREASE 0 -- Oracle recommends a setting of 0 as a way to minimize fragmentation and avoid the possibility of very large temporary segments during processing.
    FREELISTS 1 -- each free list group contains one free list
    FREELIST GROUPS 1 -- In tablespaces with manual segment-space management, statically partition the segment free space in an Oracle Real Application Clusters environment.
    BUFFER_POOL DEFAULT 
    FLASH_CACHE DEFAULT 
    CELL_FLASH_CACHE DEFAULT
)
```

![](https://docs.oracle.com/cd/B28359_01/server.111/b28286/img/storage_clause.gif)\
<https://docs.oracle.com/cd/B28359_01/server.111/b28286/clauses009.htm#SQLRF30013>

```
TABLESPACE "USERS" 
PCTTHRESHOLD 50;  -- when an overflow segment is being used, defines the maximum size of the portion of the row that is stored in the index block, as a percentage of block size. 1–50. The default is 50.
```

## Create Procedure

<https://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_6009.htm> ![](https://docs.oracle.com/cd/B19306_01/server.102/b14200/img/create_procedure.gif)

```
CREATE PROCEDURE find_root
( x IN REAL ) 
IS LANGUAGE C
```

Use the call\_spec to map a Java or C method name, parameter types, and return type to their SQL counterparts.\
![](https://docs.oracle.com/cd/B28359_01/appdev.111/b28370/img/call_spec.gif)\
![](https://docs.oracle.com/cd/B28359_01/appdev.111/b28370/img/java_declaration.gif)

```
    NAME c_find_root
    LIBRARY c_utils
    PARAMETERS ( x BY REFERENCE );
```

![](https://docs.oracle.com/cd/B28359_01/appdev.111/b28370/img/c_declaration.gif)

```
create or replace PROCEDURE add_job_history
(  p_emp_id          job_history.employee_id%type
, p_start_date      job_history.start_date%type
, p_end_date        job_history.end_date%type
, p_job_id          job_history.job_id%type
, p_department_id   job_history.department_id%type
)
IS
BEGIN
INSERT INTO job_history (employee_id, start_date, end_date, job_id, department_id)
    VALUES(p_emp_id, p_start_date, p_end_date, p_job_id, p_department_id);
END add_job_history;
```


# PostgreSQL

* [Info](/db/pgsql#info)
* [Config](/db/pgsql#config)
* [pgadmin](/db/pgsql#pgadmin)
* [Commands](/db/pgsql#commands)
* [user](/db/pgsql#user)
* [db](/db/pgsql#db)

## Info

```
SELECT version();
SELECT now();
```

## Config

<https://www.postgresql.org/docs/current/static/runtime-config-file-locations.html>

```
SHOW config_file;       -- /var/lib/postgresql/data/postgresql.conf
SHOW data_directory;    -- /var/lib/postgresql/data
SHOW hba_file;          -- /var/lib/postgresql/data/pg_hba.conf
    -- host-based authentication
    -- https://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html
SHOW ident_file;        -- /var/lib/postgresql/data/pg_ident.conf
    -- user name mapping: SYSTEM-USERNAME PG-USERNAME
SHOW external_pid_file;
```

## pgadmin

```
docker run -p 80:80 \
-e "PGADMIN_DEFAULT_EMAIL=user@domain.com" \
-e "PGADMIN_DEFAULT_PASSWORD=SuperSecret" \
-d dpage/pgadmin4
```

DB->'Schemas'->'public'->'Tables'->right click table->'View/Edit Data'->'All Rows'

## Commands

<https://www.postgresql.org/docs/current/static/app-psql.html>

## user

```
SELECT usename FROM pg_user;
CREATE USER fzinfz;
\password fzinfz
ALTER USER fzinfz WITH SUPERUSER;
\du
    -- list user/role
```

## db

```
CREATE database tutorial;
\c tutorial
psql -U postgres -h localhost -d tutorial
```


# dev

* [Repo](#repo)
* [GraphQL](#graphql)
* [Markdown](#markdown)
  * [Parser](#parser)
  * [Converter](#converter)
* [Markdown + LaTeX](#markdown--latex)
* [reStructuredText](#restructuredtext)
* [OCR](#ocr)
  * [Offline](#offline)
  * [Windows Universal](#windows-universal)
* [Excel](#excel)
  * [Formula](#formula)
  * [CSharp](#csharp)
* [CSharp](#csharp-1)
* [.Net Core](#net-core)
* [InPage Search](#inpage-search)
* [My Notes](#my-notes)

## Repo

| byGrok                | **Monolith**                  | **Monorepo**                           | **Polyrepo** (Multi-repo)    |
| --------------------- | ----------------------------- | -------------------------------------- | ---------------------------- |
| **Definition**        | Single deployable application | Single Git repository                  | Multiple Git repositories    |
| **Code organization** | One codebase, tightly coupled | Multiple projects/packages in one repo | One project/package per repo |

**Quick rule of thumb**

* **Monolith** → simple app, early stage
* **Monorepo** → many related projects that share a lot of code
* **Polyrepo** → independent projects/teams/services

## GraphQL

<http://graphql.org/\\>
a query language and execution engine tied to any backend service.

```
enum Episode { NEWHOPE, EMPIRE, JEDI }

interface Character {
    id: String
    name: String
    friends: [Character]
    appearsIn: [Episode]
}

type Human implements Character {
    id: String
    name: String
    friends: [Character]
    appearsIn: [Episode]
    homePlanet: String
}
```

## Markdown

### Parser

<http://demo.showdownjs.com/\\>
<https://github.com/showdownjs/showdown#browser>

```
var converter = new showdown.Converter();
var md = '- works in the server and in the **browser**';
var html = converter.makeHtml(md);
```

<https://github.com/chjj/marked#browser\\>
<https://github.com/jonschlinkert/remarkable\\>
<https://github.com/evilstreak/markdown-js\\>
<https://github.com/markdown-it/markdown-it\\>
<https://github.com/evilstreak/markdown-js#browser>

### Converter

Text/HTML table: <https://html.ferro.pro/md.html\\>
CSV/WIKI table: <http://jakebathman.github.io/Markdown-Table-Generator/\\>
HTML(non table): <https://domchristie.github.io/to-markdown/>

## Markdown + LaTeX

<https://github.com/pandao/editor.md>

## reStructuredText

* .md -> .rst: <https://pandoc.org/try/>
* table -> .rst: <https://tableconvert.com/restructuredtext-generator>

## OCR

### Offline

<https://github.com/hiroi-sora/Umi-OCR\\>
text on screen: <https://docs.microsoft.com/en-us/windows/powertoys/text-extractor>

### Windows Universal

<https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/OCR\\>
<https://docs.microsoft.com/en-us/uwp/api/Windows.Media.Ocr>

## Excel

### Formula

<https://exceljet.net/sites/default/files/styles/function\\_screen/public/images/formulas/Split%20text%20string%20at%20specific%20character.png?itok=WM1v7nsL>

```
=LEFT(B5,FIND("_",B5)-1)
=RIGHT(B5,LEN(B5)-FIND("_",B5))
```

### CSharp

<https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/interop/how-to-access-office-onterop-objects>

## CSharp

async：<https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/>

## .Net Core

<https://github.com/thangchung/awesome-dotnet-core>

## InPage Search

<https://docsearch.algolia.com/docs/DocSearch-v3>

## My Notes

* Jupyter: <http://nbviewer.jupyter.org/github/fzinfz/scripts/tree/master/jupyter/> \[[Source](https://github.com/fzinfz/scripts/tree/master/jupyter)]
* Scripts of Powershell/Python/etc: <https://github.com/fzinfz/scripts>


# AHK

* [V2](#v2)
* [Keys](#keys)
* [Functions](#functions)
  * [SendKeys](#sendkeys)
* [JoyStick](#joystick)
  * [Debug](#debug)
  * [x360](#x360)
* [Keyboard](#keyboard)
* [Mouse](#mouse)

## V2

v2.0.0 was released on 2022-12-20: <https://www.autohotkey.com/v2/>

## Keys

| Key | Name  |
| --- | ----- |
| ^   | Ctrl  |
| !   | Alt   |
| +   | Shift |
| #   | Win   |
| {+} | +     |

## Functions

* `SetTimer Function, Period(ms), Priority` | repeatedly/asynchronously | <https://www.autohotkey.com/docs/v2/lib/SetTimer.htm>
  * Period > 0: default 250
  * Period < 0: run only once
  * Period = 0: deleted after the thread finishes

### SendKeys

<https://www.autohotkey.com/docs/v2/howto/SendKeys.htm>

```
^3::{
    SendText "Double quote: `""
    SendText 'Single quote: `''
}
```

## JoyStick

<https://www.autohotkey.com/docs/v2/KeyList.htm#Controller>

* Joy1 through Joy32
* used with `GetKeyState`:

  JoyX, JoyY, and JoyZ: The X (horizontal), Y (vertical), and Z (altitude/depth) axes of the controller. JoyR: The rudder(舵) or 4th axis of the controller. JoyU and JoyV: The 5th and 6th axes of the controller. JoyPOV: The point-of-view (hat) control. JoyName: The name of the controller or its driver. JoyButtons: The number of buttons supported by the controller (not always accurate). JoyAxes: The number of axes supported by the controller. JoyInfo: Example string: ZRUVPD - Z (has Z axis), R (has R axis), U (has U axis), V (has V axis) - P (has POV control), - D (the POV control has a limited number of discrete/distinct settings) - C (the POV control is continuous/fine).

### Debug

* Windows Start keyword : 'joy'
* .ahk : <https://www.autohotkey.com/docs/v1/scripts/index.htm#ControllerTest>

### x360

| x360                      | Default | Range                      |
| ------------------------- | ------- | -------------------------- |
| Left Stick / XY           | 50      | Left/Up 0 - Right/Down 100 |
| D-Pad/hat / POV           | -1      | POV0 - POV31500            |
| Right Stick / XY Rotation | U50 R50 | 0-100                      |
| ABXY                      | 1234    |                            |
| LB/LeftBumper RB          | 5 6     |                            |
| Back ; Start              | 7 8     |                            |
| LT/LeftTrigger Z          | Z50     | - Z100                     |
| RT/RightTrigger Z         | Z50     | - Z0                       |

## Keyboard

<https://www.autohotkey.com/docs/v2/KeyList.htm>

```
Joy2::Send "{w}"
```

## Mouse

```
Joy1::
{
    Send "{LButton down}"   ; Hold down the left mouse button.
    ; SetTimer WaitForButtonUp3, 10
}
```


# BI

* [Sample data](#sample-data)
* [Diagram image generator online](#diagram-image-generator-online)
* [view & analyze Pandas](#view--analyze-pandas)
* [plotly - for Math](#plotly---for-math)
* [plot time series data](#plot-time-series-data)
* [Math graph](#math-graph)
* [bokeh- Python](#bokeh--python)
* [HoloViews](#holoviews)
* [Superset vs Redash vs Metabase](#superset-vs-redash-vs-metabase)
* [Apache Superset (Caravel/Panoramix)](#apache-superset-caravelpanoramix)
* [Redash](#redash)
* [ELK](#elk)
  * [My `docker run` scripts](#my-docker-run-scripts)
  * [Snapshot And Restore](#snapshot-and-restore)
    * [Backup](#backup)
    * [Check](#check)
* [ETL](#etl)
  * [kettle -JAVA](#kettle--java)
* [Excel](#excel)
  * [xlwings](#xlwings)
  * [django](#django)
  * [.Net](#net)
* [Word](#word)
* [highcharts](#highcharts)

## Sample data

python: <https://github.com/altair-viz/vega\\_datasets>

## Diagram image generator online

<http://blockdiag.com/en/>

## view & analyze Pandas

<https://github.com/man-group/dtale>

## plotly - for Math

<https://plot.ly/api/\\>
<https://plot.ly/python/\\>
<https://github.com/plotly/>

## plot time series data

<https://stackoverflow.com/questions/44964346/matplotlib-plot-time-series-graph\\>
<https://stackoverflow.com/questions/19079143/how-to-plot-time-series-in-python\\>
<https://stackoverflow.com/questions/38837421/simple-way-to-plot-time-series-with-real-dates-using-pandas>

## Math graph

<https://www.geogebra.org>

<https://github.com/mwaskom/seaborn> <https://github.com/mwaskom/seaborn-data>

## bokeh- Python

<https://github.com/bokeh/bokeh#interactive-gallery\\>
Interactive Web Plotting

## HoloViews

<https://github.com/ioam/holoviews\\>
annotate your data and let it visualize itself

## Superset vs Redash vs Metabase

<https://www.pervasivecomputing.net/data-analytics/superset-vs-redash-vs-metabase>

## Apache Superset (Caravel/Panoramix)

<https://github.com/apache/incubator-superset> ![](https://cloud.githubusercontent.com/assets/130878/20371438/a703a2a0-ac19-11e6-80c4-00a47c2eb644.gif)

## Redash

<https://github.com/getredash/redash> ![](https://cloud.githubusercontent.com/assets/71468/17391289/8e83878e-5a1d-11e6-8938-af9054a33b19.gif)

## ELK

### My `docker run` scripts

<https://github.com/fzinfz/docker-images/>

### Snapshot And Restore

<https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>

#### Backup

```
PUT /_snapshot/bak_1
{
   "type": "fs",
   "settings": {
       "compress" : true,
       "location": "/usr/share/elasticsearch/data/backup"
   }
}

PUT /_snapshot/bak_1/snapshot_1?wait_for_completion=true
```

#### Check

```
GET /_snapshot/bak_1
```

## ETL

### kettle -JAVA

<https://github.com/pentaho/pentaho-kettle>

## Excel

<https://docs.wso2.com/display/DSS301/Excel+Sample>

### xlwings

<http://docs.xlwings.org/en/stable/converters.html#pandas-dataframe-converter>

### django

django-excel: <http://django.pyexcel.org/en/latest/> django-import-export: <https://django-import-export.readthedocs.io/en/latest/>

### .Net

<https://github.com/tonyqus/npoi\\>
<https://github.com/JanKallman/EPPlus/wiki/Getting-Started>

## Word

<https://github.com/xceedsoftware/DocX>

## highcharts

<https://www.highcharts.com\\>
Free for non-commercial


# LBS

* [Standard](#standard)
* [DB](#db)
  * [PostGIS for PostgreSQL](#postgis-for-postgresql)
  * [GeoCouch for CouchDB](#geocouch-for-couchdb)
* [GeoIP2](#geoip2)
* [Solr](#solr)
* [AMAQ](#amaq)
* [Tencent](#tencent)

## Standard

<http://www.opengeospatial.org/>

The GeoJSON Format: <https://tools.ietf.org/html/rfc7946>

## DB

### PostGIS for PostgreSQL

<http://postgis.refractions.net/>

### GeoCouch for CouchDB

<https://github.com/couchbase/geocouch/>

## GeoIP2

<https://dev.maxmind.com/geoip/geoip2/downloadable/>

## Solr

<https://wiki.apache.org/solr/SpatialSearch>

## AMAQ

<https://lbs.amap.com/faq/top/notice/flowlevel>

## Tencent

<http://lbs.qq.com/webservice\\_v1/guide-search.html\\>
<http://lbs.qq.com/webservice\\_v1/guide-suggestion.html>


# android

* [emulator](#emulator)

## emulator

<https://developer.android.com/studio/run/emulator>

```
emulator -accel-check
```


# editor

* [Pritable](#pritable)
* [vscode](#vscode)
* [vi/vim](#vivim)
* [nano](#nano)
* [WebStorm](#webstorm)
  * [Terminal](#terminal)

## Pritable

<https://pandoc.org/getting-started.html>

```
pandoc -f html -t markdown                           # HTML to markdown
pandoc test1.md -f markdown -t html -s -o test1.html # markdown to HTML
# -s option says to create a “standalone” file, with a header and footer, not just a fragment. 
```

Chrome/Edge - print .md on Github: <https://github.com/jerry1100/github-markdown-printer>

## vscode

[/ms/vscode.md](/ms/vscode)

## vi/vim

```
go to line: Esc , line#, Shift-g
:%s/pattern/replace/g_  # i/I: case in/sensitive
cw => change word
ciw => change word from cursor
:w !sudo tee %      ===> sudo save

~/.vimrc
set nocompatible # fix array not working in insert mode
```

* Visual Insert Mode paste: Shift+Insert
* VISUAL BLOCK mode Ctrl+V；【select block】；Shift + I; 【type text】; Esc

## nano

CTRL + Shift + 6: mark CTRL + K: cut/delete

## WebStorm

### Terminal

* Support ctrl+C/V , clickable links
* env != OS env: Settings | Tools | Terminal


# flutter\_web

## Start

<https://flutter.dev/docs/get-started/install/windows#get-the-flutter-sdk>

<https://flutter.dev/docs/get-started/web>

```
flutter channel stable
flutter upgrade
flutter devices
flutter doctor

flutter create myapp
cd myapp
flutter run # -d chrome

flutter run --release # --web-renderer html or --web-renderer canvaskit
```

## Web renderers

<https://flutter.dev/docs/development/tools/web-renderers>

* HTML renderer\
  Uses a combination of HTML elements, CSS, Canvas elements, and SVG elements. This renderer has a smaller download size.
* CanvasKit renderer\
  This renderer is fully consistent with Flutter mobile and desktop, has faster performance with higher widget density, but adds about 2MB in download size.

## adaptive vs responsive

* Responsive\
  Typically, a responsive app has had its layout tuned for the available screen size. Often this means (for example), re-laying out the UI if the user resizes the window, or changes the device’s orientation. This is especially necessary when the same app can run on a variety of devices, from a watch, phone, tablet, to a laptop or desktop computer.
* Adaptive\
  Adapting an app to run on different device types, such as mobile and desktop, requires dealing with mouse and keyboard input, as well as touch input. It also means there are different expectations about the app’s visual density, how component selection works (cascading menus vs bottom sheets, for example), using platform-specific features (such as top-level windows), and more.


# git

* [Learn](#learn)
* [Workflow](#workflow)
  * [commit](#commit)
  * [log](#log)
  * [branch and merge](#branch-and-merge)
  * [Undo](#undo)
  * [stashing](#stashing)
  * [remote and push](#remote-and-push)
    * [delete remote branch](#delete-remote-branch)
* [config](#config)
  * [Proxy](#proxy)
* [filter-branch](#filter-branch)
* [Remove File](#remove-file)
  * [Unpushed commit](#unpushed-commit)
  * [Every commit](#every-commit)
  * [from Github](#from-github)
* [rebase](#rebase)
* [fork](#fork)
* [Submodules](#submodules)
* [Github API](#github-api)
  * [Download by tag](#download-by-tag)
  * [curl Github](#curl-github)
  * [Query latest release](#query-latest-release)
* [Github](#github)
* [Self-host git servers](#self-host-git-servers)
* [Tools](#tools)
* [Tools](#tools-1)

## Learn

* Practise: <https://learngitbranching.js.org/?locale=en\\_US>
* Cheatsheet
  * 4 Pages: <https://about.gitlab.com/images/press/git-cheat-sheet.pdf>
  * 2 Pages: <https://education.github.com/git-cheat-sheet-education.pdf>
  * 2 Pages: <https://www.atlassian.com/dam/jcr:8132028b-024f-4b6b-953e-e68fcce0c5fa/atlassian-git-cheatsheet.pdf>
* Books
  * <https://git-scm.com/book/en/v2>

[my functions](https://github.com/fzinfz/scripts/blob/master/lib/git.sh#L1):

```bash
source /dev/stdin <<< "$(curl -sSL https://raw.githubusercontent.com/fzinfz/scripts/master/lib/git.sh)"
```

## Workflow

<https://stackoverflow.com/questions/3689838/whats-the-difference-between-head-working-tree-and-index-in-git\\>
![](https://i.stack.imgur.com/caci5.png)

```
cat .git/HEAD       # current branch head
    ref: refs/heads/master
cat .git/ORIG_HEAD ; git show | head -1
```

`working tree` don't include `untracked files`

### commit

```
git commit -am "save arezzo files"
git commit --amend
    -c, --reedit-message <commit>   # reuse and edit message from specified commit
    -C, --reuse-message <commit>    # reuse message from specified commit
```

### log

```
git log [<options>] [<revision-range>] [[--] <path>...]
git show [<options>] <object>...
git show [path] # details of last commit log
git log --since=2.weeks
```

### branch and merge

```
git branch -a       # list all

git checkout -b dev # create and checkout a new branch

git checkout master
git merge dev       # merge dev into master
    --squash              create a single commit instead of doing a merge
    --abort               abort the current in-progress merge
```

### Undo

<https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting>

```
git checkout -- <file>    # discard changes in working directory

git reset HEAD~2    # undo 2 changes that haven’t been shared
git reset <paths>   # opposite of `git add <paths>`
    --soft                reset HEAD only
    --mixed               reset HEAD and index (default)
    --hard                reset HEAD, index and working tree
    --merge               reset HEAD, index and working tree
    --keep                reset HEAD but keep local changes

git revert HEAD~2   # undo 2 changes on a public branch
```

<https://stackoverflow.com/questions/3639342>

```
git reset master
git checkout master
```

![](https://i.stack.imgur.com/UWGiw.png)

### stashing

```
git stash
git stash list
git stash apply/pop
git stash apply stash@{2}
git stash drop
git stash drop stash@{0}
```

### remote and push

<https://git-scm.com/book/en/v2/Git-Internals-The-Refspec>

```
git remote -v
git remote add [<options>] <name> <url>
    -f, --fetch           fetch the remote branches
    --tags
    --no-tags
    -t, --track <branch>        # branch(es) to track
    -m, --master <branch>
    --mirror[=<push|fetch>]     # set up remote as a mirro

cat .git/config
    `refspec`:     +<src>:<dst>
    <src> is the pattern for references on the remote side
    <dst> is where those references will be tracked locally

    [remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        fetch = +refs/heads/master:refs/remotes/origin/master
        fetch = +refs/heads/foo/*:refs/remotes/origin/foo/*

git push -u origin master:refs/heads/foo/master

        push = refs/heads/master:refs/heads/qa/master

tree .git/refs/
    .git/refs/
    ├── heads
    │   ├── dev
    │   └── master
    ├── remotes
    │   └── origin
    │       └── HEAD
    └── tags

git push [<options>] [<repository> [<refspec>...]]
    -u, --set-upstream    set upstream for git pull/status
git pull origin master # fetch + merge
```

#### delete remote branch

```
git push origin :topic
git push origin --delete topic
```

## config

```
git config -l
    --global              ~/.gitconfig
    --local               .git/config
        core.repositoryformatversion=0
        core.filemode=true
        core.bare=false
        core.logallrefupdates=true
    --system              /etc/gitconfig

    --get                 get value: name [value-regex]
    --get-all             get all values: key [value-regex]
    --get-regexp          get values for regexp: name-regex [value-regex]
    --get-urlmatch        get value specific for the URL: section[.var] URL
    --replace-all         replace all matching variables: name value [value_regex]
    --add                 add a new variable: name value
    --unset               remove a variable: name [value-regex]
    --unset-all           remove all matches: name [value-regex]

git config --global push.default simple
git config --list --show-origin
```

### Proxy

```
git config --global http.proxy http://$IP:$Port
```

## filter-branch

<https://manishearth.github.io/blog/2017/03/05/understanding-git-filter-branch/>

```
[--setup <command>] 
[--env-filter <command>]
[--tree-filter <command>] 
[--index-filter <command>]
[--parent-filter <command>] 
[--msg-filter <command>]
[--commit-filter <command>] 
[--tag-name-filter <command>]
[--subdirectory-filter <directory>] 
[--original <namespace>]
[-d <directory>] [-f | --force] [--] [<rev-list options>...]
```

## Remove File

### Unpushed commit

```
git rm --cached giant_file # leave it on disk
git commit --amend -CHEAD
```

### Every commit

```
git filter-branch --tree-filter 'rm -f filename' HEAD
    --all       # all branches

git filter-branch --index-filter \
    'git rm --cached --ignore-unmatch filename' HEAD
```

### from Github

<https://help.github.com/articles/removing-sensitive-data-from-a-repository/>

## rebase

<https://git-scm.com/book/en/v2/Git-Branching-Rebasing>

```
git remote add upstream https://github.com/yeasy/docker_practice
git fetch upstream
git checkout master
git rebase upstream/master
git push -f origin master
```

## fork

<https://stackoverflow.com/questions/14587045/how-to-merge-branch-of-forked-repo-into-master-branch-of-original-repo>

## Submodules

<https://git-scm.com/book/en/v2/Git-Tools-Submodules\\>
treat the two projects as separate yet still be able to use one from within the other.

## Github API

<https://developer.github.com/v3/repos/>

### Download by tag

```
curl -sSL https://api.github.com/repos/django/django/tags \
    | jq '.[0].zipball_url' | xargs -t wget -O file.zip
```

### curl Github

<https://github.com/settings/tokens>

```
curl -H 'Authorization: token INSERT_ACCESS_TOKEN_HERE' \
    -H 'Accept: application/vnd.github.v3.raw' -O -L \
    https://api.github.com/repos/owner/repo/contents/path
```

### Query latest release

```
curl -sSL https://api.github.com/repos/ParsePlatform/Parse-SDK-Android/releases/latest \
    | jq '.zipball_url' | xargs -t wget -O file.zip
```

## Github

check watchers: <https://github.com/{user}/{project}/watchers>

## Self-host git servers

Go: <https://github.com/go-gitea/gitea\\>
Go: <https://github.com/gogs/gogs\\>
Ruby: <https://gitlab.com/gitlab-org/gitlab>

## Tools

curl -L <https://github.com...?raw=true\\>
.html to page, etc: <https://rawgit.com/\\>
.js CDN: <https://cdnjs.com/> <https://cdn.jsdelivr.net/gh/user/repo@version/file\\>
.ipynb fast open: <http://nbviewer.jupyter.org/>

## Tools

Code search: <https://about.sourcegraph.com/> download: <https://minhaskamal.github.io/DownGit/#/home>


# go

* [Articles](#articles)
* [Go Environment variables](#go-environment-variables)

## Articles

<https://www.zhihu.com/question/21409296> (Chinese)

## Go Environment variables

<https://golang.org/cmd/go/#hdr-Environment\\_variables>

<https://golang.org/doc/install/source#environment>

```
$GOOS	$GOARCH
android	arm
darwin	386
darwin	amd64
darwin	arm
darwin	arm64
dragonfly	amd64
freebsd	386
freebsd	amd64
freebsd	arm
linux	386
linux	amd64
linux	arm
linux	arm64
linux	ppc64
linux	ppc64le
linux	mips
linux	mipsle
linux	mips64
linux	mips64le
netbsd	386
netbsd	amd64
netbsd	arm
openbsd	386
openbsd	amd64
openbsd	arm
plan9	386
plan9	amd64
solaris	amd64
windows	386
windows	amd64
```

## Check

```
dpkg -l golang-{go,src} | grep ^ii
```


# HTML5/BS

* [Chrome](#chrome)
* [Percent-encoding reserved](#percent-encoding-reserved)
* [HTML5](#html5)
  * [lang](#lang)
  * [Subresource Integrity](#subresource-integrity)
* [media type](#media-type)
* [icons](#icons)
* [Events](#events)
* [CSS box model](#css-box-model)
  * [box-sizing](#box-sizing)
  * [content](#content)
  * [padding](#padding)
  * [border](#border)
  * [margin](#margin)
* [Spacing](#spacing)
* [Mobile](#mobile)
* [Flexbox](#flexbox)
* [UI Frameworks](#ui-frameworks)
* [Bootstrap](#bootstrap)
  * [Version 3](#version-3)
  * [Version 4](#version-4)
  * [Version 5](#version-5)
  * [Grid system](#grid-system)
  * [forms](#forms)
* [whitespace and wrap](#whitespace-and-wrap)
* [robots](#robots)
* [Frameworks](#frameworks)

## Chrome

```
hard reload: Ctrl + F5
F12 -> Ctrl+Shift+P -> "screenshot"
delete address history: Shift + Del
remove domain name: F12 -> console
    document.body.innerHTML = document.body.innerHTML.replace(/\.\w+\.\w+(?=:)/g, "")
```

## Percent-encoding reserved

<https://en.wikipedia.org/wiki/Percent-encoding>

| !   | #   | $   | %   | &   | '   | (   | )   | \*  | +   | ,   | /   | :   | ;   | =   | ?   | @   | \[  | ]   |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| %21 | %23 | %24 | %25 | %26 | %27 | %28 | %29 | %2A | %2B | %2C | %2F | %3A | %3B | %3D | %3F | %40 | %5B | %5D |

## HTML5

<https://www.w3.org/TR/html5\\>
<https://developer.mozilla.org/en-US/docs/Web/HTML/Element>

### lang

empty string indicates that the primary language is unknown

<https://www.w3.org/TR/html5/dom.html#the-lang-and-xml:lang-attributes\\>
<http://www.ietf.org/rfc/bcp/bcp47.txt>

### Subresource Integrity

<https://www.w3.org/TR/SRI/#resource-integrity>

## media type

MIME type or content type: <http://www.iana.org/assignments/media-types/media-types.xhtml#application>

```
application/pdf
audio
font
example
image
message
model
multipart
text
video
```

## icons

<https://github.com/encharm/Font-Awesome-SVG-PNG/tree/master/white/svg>

## Events

<https://developer.mozilla.org/en-US/docs/Web/Events>

```
cut/copy/paste  
input: the value of an <input>, <select>, or <textarea> element is changed  
ValueChange: mainly for an accessibility purpose, e.g.: <progress>  
change(Firefox OS specific, any change made to a file inside a given storage area)
```

## CSS box model

<https://developer.mozilla.org/en-US/docs/Web/CSS/CSS\\_Box\\_Model/Introduction\\_to\\_the\\_CSS\\_box\\_model\\>
Every box is composed of four parts (or areas), defined by their respective edges.\
![](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model/boxmodel.png)

### box-sizing

<https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing>

`content-box` is the default.\
`border-box` tells the browser to account for any border and padding in the value you specify for width and height.

### content

"real" content of the element

size can be explicitly defined with the width, min-width, max-width, height, min-height, and max-height properties.

When the content area has a background, it extends into the padding.

### padding

extends the content area to include the element's padding.

```
dimensions: padding-box width/height
thickness: padding[-top/right/bottomleft]
```

### border

extends the padding area to include the element's borders.

```
dimensions: border-box width/height
thickness: border[-width]
```

If the box-sizing property is set to border-box, the border area's size can be explicitly defined with the width, min-width, max-width, height, min-height, and max-height properties.

### margin

extends the border area to include an empty area used to separate the element from its neighbors.

```
dimensions: margin-box width/height
size: margin[-top/right/bottomleft]
```

When margin collapsing occurs, the margin area is not clearly defined since margins are shared between boxes.\
<https://developer.mozilla.org/en/CSS/margin\\_collapsing>

## Spacing

<https://getbootstrap.com/docs/4.0/utilities/spacing/>

```
Examples: class="mx-auto / pt-3"

{property}{sides}-{size} for xs
{property}{sides}-{sm, md, lg, xl}-{size}

m - margin
p - padding

t - top
b - bottom
l - left
r - right
x - *-left and *-right
y - *-top and *-bottom
blank - all 4 sides

0 - 0
1 -$spacer * .25
2 -$spacer * .5
3 -$spacer
4 -$spacer * 1.5
5 -$spacer * 3
auto - margin auto
```

## Mobile

<https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport\\_meta\\_tag>

```
viewport: a virtual "window"
viewport meta tag: let web developers control the viewport's size and scale.
```

<https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html#//apple\\_ref/doc/uid/TP40008193>

```
initial-scale: The default is calculated to fit the webpage in the visible area.
maximum-scale:  The default is 5.0. The range is from >0 to 10.0.
user-scalable: whether or not the user can zoom in and out. yes
shrink-to-fit=no: override  "width=device-width" to prevent the page from scaling
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
```

## Flexbox

* Game: <https://flexboxfroggy.com/>
* Doc: <https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS\\_layout/Flexbox> ![](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox/flex_terms.png)

Click links to live try:

* `flex-direction`: specifies which direction the **main axis** runs; `column` -> vertically
* `flex-wrap`: default `nowrap`
* `flex-flow` = `flex-direction` + `flex-wrap`
* [`justify-content`](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content#examples): default `flex-start`, items sit at the start of the main axis
* [`align-items`](https://developer.mozilla.org/en-US/docs/Web/CSS/align-items#examples)：default `stretch`，fill the parent in the direction of the cross axis
* [`align-content`](https://developer.mozilla.org/en-US/docs/Web/CSS/align-content#formal_syntax)：around content items along a flexbox's cross-axis
* [`flex`](https://developer.mozilla.org/en-US/docs/Web/CSS/flex#examples): grow or shrink to fit the space | flex-grow + flex-shrink + flex-basis

## UI Frameworks

<https://github.com/stars/fzinfz/lists/frontend>

## Bootstrap

### Version 3

<https://getbootstrap.com/docs/3.3/getting-started/#download-cdn>

### Version 4

<https://v4-alpha.getbootstrap.com/getting-started/introduction/#starter-template>

<http://blog.getbootstrap.com/2017/08/10/bootstrap-4-beta/>

* compiles faster than ever thanks to Libsass
* moved nearly everything to flexbox, added a new grid tier to better target mobile devices, and completely overhauled our source Sass with better variables, mixins, and now maps, too.
* <https://getbootstrap.com/docs/4.0/components/card/>
* move gradients, transitions, shadows, grid classes, and more into Sass variables.
* drop support for IE8/IE9, Safari 8-, iOS 8-, etc
* JS plugins in ES6. new teardown methods, option type checking, new methods, and more.
* auto-placement of tooltips, popovers, and dropdowns from <https://popper.js.org>
* npm scripts instead of Grunt

### Version 5

<https://blog.getbootstrap.com/2021/05/05/bootstrap-5/>

```
No more jQuery!
Dropped Internet Explorer 10 and 11
Dropped Microsoft Edge < 16 (Legacy Edge)
Dropped Firefox < 60
Dropped Safari < 12
Dropped iOS Safari < 12
Dropped Chrome < 60
```

### Grid system

<https://getbootstrap.com/docs/3.3/css/#grid>

Rows must be placed within a .container\[-fluid] for proper alignment and padding. Columns create gutters (gaps between column content) via `padding`. That padding is offset in rows for the first and last column via negative margin on `.rows`.

### forms

<https://getbootstrap.com/docs/4.0/components/forms/#form-groups>

.form-group provides a flexible class that encourages proper grouping of labels, controls, optional help text, and form validation messaging.

.row for .form-row, a variation of our standard grid row that overrides the default column gutters for tighter and more compact layouts.

<https://getbootstrap.com/docs/4.3/components/forms/#inline-forms>

.form-inline class to display a series of labels, form controls, and buttons on a single horizontal row.

## whitespace and wrap

<https://css-tricks.com/almanac/properties/w/whitespace/>

|          | New lines | Spaces and tabs | Text wrapping |
| -------- | --------- | --------------- | ------------- |
| normal   | Collapse  | Collapse        | Wrap          |
| pre      | Preserve  | Preserve        | No wrap       |
| nowrap   | Collapse  | Collapse        | No wrap       |
| pre-wrap | Preserve  | Preserve        | Wrap          |
| pre-line | Preserve  | Collapse        | Wrap          |

## robots

```
<META NAME="ROBOTS" CONTENT="INDEX, FOLLOW">

robots.txt
    User-agent: Google
    Disallow:

    User-agent: *
    Disallow: /tmp/
```

## Frameworks

htmx | AJAX, CSS Transitions, WebSockets and Server Sent Events: <https://htmx.org/>


# j2ee

* [Tooling Setup](#tooling-setup)

## Tooling Setup

<https://developer.ibm.com/wasdev/docs/developing-applications-wdt-liberty-profile/\\>
Help > Eclipse Marketplace… and search for "WebSphere Developer Tools"

<https://hub.docker.com/\\_/websphere-liberty> ( windows & linux share same binary)


# js

* [Toolbox](#toolbox)
* [Frameworks](#frameworks)
* [UI](#ui)
* [Basic](#basic)
  * [text](#text)
  * [export & import](#export--import)
* [the default export can be imported with any name](#the-default-export-can-be-imported-with-any-name)
  * [this](#this)
  * [IIFE (Immediately Invokable Function Expression)](#iife-immediately-invokable-function-expression)
  * [Chrome Cross origin requests](#chrome-cross-origin-requests)
  * [pdf.js](#pdfjs)
* [JQuery](#jquery)
  * [events](#events)
* [JSX](#jsx)
* [MDX](#mdx)

## Toolbox

<https://bun.sh/>

```
powershell -c "irm bun.sh/install.ps1 | iex"
curl -fsSL https://bun.sh/install | bash
```

## Frameworks

* Vue: <https://nuxtjs.org/>
* React: <https://nextjs.org/>

## UI

* byCF: <https://kumo-ui.com/>

## Basic

### text

```
if ("ab"+"c".includes("bc")) { t="_3"; console.log(`t${t}`.replace(/\d/, "").length); } else if (true) {} else { } // Out: 2
```

### export & import

* <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export>
* <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import>

  ## the default export can be imported with any name

  export default k; // file test.js import anyName from "./test";

### this

<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this>

```
const test = {
  prop: 42,
  func: function() {
    return this.prop;
  },
};
```

### IIFE (Immediately Invokable Function Expression)

```
(function() {
    statements
})();
```

### Chrome Cross origin requests

Cross origin requests are only supported for protocol schemes:\
http, data, chrome, chrome-extension, https.

### pdf.js

<https://github.com/mozilla/pdf.js/tree/master/examples/helloworld>

## JQuery

### events

<http://api.jquery.com/category/events/>

## JSX

an XML-like syntax extension to ECMAScript without any defined semantics: <https://facebook.github.io/jsx/> `const element = <h1>Hello, world!</h1>;`: <https://zh-hans.reactjs.org/docs/introducing-jsx.html>

## MDX

JSX + Markdown: <https://mdxjs.com/docs/what-is-mdx/>


# js\_grid

* [vue](#vue)
  * [vxe-table](#vxe-table)
  * [matfish2/vue-tables](#matfish2vue-tables)
* [jquery](#jquery)
  * [jexcel](#jexcel)
* [standalone](#standalone)
* [HTML Table](#html-table)
* TanStack - React, Solid, Vue, Svelte and TS/JS: <https://github.com/TanStack/table#tanstack-table-v8>
* AG Grid - Supports React / Angular / Vue / Plain JavaScript: <https://github.com/ag-grid/ag-grid>
* S2 - 多维交叉分析: <https://github.com/antvis/s2/#s2>
* Antd Table: <https://ant.design/components/table-cn>
* ProTable: <https://procomponents.ant.design/en-US/components/table?current=1\\&pageSize=5>

<https://github.com/FancyGrid/awesome-grid>

## vue

### vxe-table

<https://vxetable.cn/#/table/start/install>

* CDN: <https://vxetable.cn/#/table/start/install>
* `npm install xe-utils vxe-table@next` # better for webpack、vite

js/ts/setup()/JSX: <https://vxetable.cn/#/table/start/quick>

support tree table: <https://vxetable.cn/#/table/advanced/search>

### matfish2/vue-tables

<https://raw.githubusercontent.com/matfish2/vue-tables/master/dist/vue-tables.min.js>

Demo: <https://jsfiddle.net/matfish2/jfa5t4sm/> Feature: expand row to multi-rows

## jquery

### jexcel

<https://github.com/paulhodel/jexcel>

roadmap: Online work collaboration

## standalone

* tabulator: <https://github.com/olifolkerd/tabulator>

## HTML Table

<https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table>

```
<table>
    <thead>
        <tr>
            <th colspan="2">The table header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>The table body</td>
            <td>with two columns</td>
        </tr>
    </tbody>
</table>

<table>
    <thead>
        <tr>
            <th>Items</th>
            <th scope="col">Expenditure</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th scope="row">Donuts</th>
            <td>3,000</td>
        </tr>
        <tr>
            <th scope="row">Stationery</th>
            <td>18,000</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th scope="row">Totals</th>
            <td>21,000</td>
        </tr>
    </tfoot>
</table>
```


# js\_vue

* [Vite](#vite)
* [V3](#v3)
  * [to3](#to3)
* [createApp](#createapp)
  * [hydration mode](#hydration-mode)
* [Components](#components)
  * [defineComponent](#definecomponent)
  * [defineCustomElement](#definecustomelement)
* [Plugins](#plugins)
* [Routing](#routing)
* [VNode - h](#vnode---h)
* [Data Binding](#data-binding)
  * [v-bind/on](#v-bindon)
  * [Event](#event)
  * [Watch](#watch)
  * [computed](#computed)
  * [refs](#refs)
* [List Rendering](#list-rendering)
* [lifecycle](#lifecycle)
* [Code Snippets](#code-snippets)

## Vite

<https://vitejs.dev/guide/why.html>

<https://vitejs.dev/guide/>

```
# vanilla, vanilla-ts, vue, vue-ts, react, react-ts ...
npm create vite@latest test-vue3-ts-vite --template vue-ts    # npm 6.x
npm create vite@latest test-vue3-ts-vite -- --template vue-ts # npm 7+
npm install && npm run dev -- --host
```

[README.md](https://github.com/fzinfz/test-vue3-ts-vite/blob/0652a5ecc9440d520021e4c023fdc21da547efa2/README.md): `@builtin vscode.typescript-language-features` -> `Disable (Workspace)` | install `vue.volar` + `Vue.vscode-typescript-vue-plugin`

## V3

```
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
const { createApp } = Vue

<script type="module">
  import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
```

Live try HTML/SFC: <https://vuejs.org/tutorial/>

### 2to3

<https://vuejsdevelopers.com/2020/03/16/vue-js-tutorial/>

* `new Vue()` ====> `createApp()`
* `data: {` ====> `data: () => ({`
* `render: h => h(App)` ====> `App`
* multi `<>` under `<template>`
* `setup()`: no `.value` and `this` : <https://vuejs.org/api/composition-api-setup.html>
* Teleport: `<Teleport to="body/#id">`: <https://vuejs.org/guide/built-ins/teleport.html>
*

## createApp

```
Vue.createApp({
    data() {
        return {
            items: ...
        }
    }
}).mount('#id')
```

源码 - ensureRenderer: <https://vue3js.cn/global/createApp.html>

<https://vuejs.org/api/application.html#createapp>

```
function createApp(rootComponent: Component, rootProps?: object): App
```

### hydration mode

<https://vuejs.org/guide/scaling-up/ssr.html#client-hydration>

make the client-side app interactive: use createSSRApp() instead of createApp()

shared between the server and the client - universal code:

```
export function createApp() {
    return createSSRApp({
```

## Components

.vue - Single-File Component/SFC | no CDN: <https://vuejs.org/guide/essentials/component-basics.html>

```
<script>
import ButtonCounter from './ButtonCounter.vue'

export default {
  components: {
    ButtonCounter
  }
}
</script>

<template>
  <h1>Here is a child component!</h1>
  <ButtonCounter />
</template>
```

### defineComponent

```
import { defineComponent } from 'vue'

const MyComponent = defineComponent({
    data() {
    methods: {
```

### defineCustomElement

```
import { defineCustomElement } from 'vue'
const MyVueElement = defineCustomElement({
customElements.define('my-vue-element', MyVueElement)

<my-vue-element></my-vue-element>
```

## Plugins

<https://vuejs.org/guide/reusability/plugins.html>

```
app.use(myPlugin, { })

const myPlugin = {
    install(app, options) {

export default {
    install: (app, options) => {
```

## Routing

<https://vuejs.org/guide/scaling-up/routing.html>

## VNode - h()

<https://vuejs.org/guide/extras/render-function.html>

```
import { h } from 'vue'
h('div', { id: 'foo' }, 'hello')
```

## Data Binding

### v-bind/on

v-bind: <https://vuejs.org/guide/essentials/template-syntax.html#dynamically-binding-multiple-attributes>

```
data() {
    return {
        objectOfAttrs: {

<div v-bind="objectOfAttrs"></div>
```

v-bind : 1-way v-model: 2-way = v-bind + v-on

```
<a v-bind:href="url"> ... </a>          ==>  <a :href=""> ... </a>
<a v-on:click="doSomething"> ... </a>   ==>  <a @click=""> ... </a>
```

### Event

<https://vuejs.org/tutorial/#step-4>

SFC Demo: <https://github.com/fzinfz/test-vue3-ts-vite/commit/3b06a86c4c894436c47c33f584337fe789c5e6d0>

### Watch

<https://vuejs.org/guide/essentials/watchers.html>

HTML Demo: <https://github.com/fzinfz/scripts/commit/846a0bb2260a92ed9d76fd24f6669e8c63f15fde>

### computed

for complex logic that includes reactive data：<https://vuejs.org/guide/essentials/computed.html>

### refs

<https://vuejs.org/guide/essentials/template-refs.html>

```
<input ref="input">

this.$refs.input.focus()
```

## List Rendering

<https://v3.vuejs.org/guide/list.html>

## lifecycle

<https://v3.vuejs.org/guide/instance.html#creating-an-application-instance> ![](https://v3.vuejs.org/images/lifecycle.svg)

## Code Snippets

* str(lines) -> html(links): <https://github.com/fzinfz/fzinfz.github.io/blob/master/i/index.html>


# jupyter

* [Run](#run)
* [Docker Images](#docker-images)
  * [Community Stacks](#community-stacks)
    * [selenium](#selenium)

Test: <https://github.com/fzinfz/ipynb/blob/main/python/jupyter.ipynb>

uv: <https://docs.astral.sh/uv/guides/integration/jupyter/>

## Run

```
# win create shortcut
d:\_soft\Anaconda3\python.exe d:\_soft\Anaconda3\cwp.py d:\_soft\Anaconda3 d:\_soft\Anaconda3\python.exe d:\_soft\Anaconda3\Scripts\jupyter-notebook-script.py "d:/"

# linux
jupyter notebook --generate-config # ~/.jupyter | jupyter_notebook_config.py
    c.NotebookApp.notebook_dir = ''
    c.NotebookApp.ip = '*'
    c.NotebookApp.open_browser = False 
    c.NotebookApp.password = u'type:salt:hashed-password' # from notebook.auth import passwd; passwd()

%reload_ext autoreload
%autoreload 2
```

## Docker Images

<https://jupyter-docker-stacks.readthedocs.io/en/latest/using/selecting.html#image-relationships>

```
base + git/vi/tzdata/unzip = minimal => 
scipy | r => pyspark/tensorflow || datascience* => all-spark
```

jupyter/datascience-notebook

cell diff: <https://jovian-py.readthedocs.io/en/latest/user-guide/version.html#view-differences>

### Community Stacks

<https://jupyter-docker-stacks.readthedocs.io/en/latest/using/selecting.html#community-stacks>

#### selenium

<https://github.com/rgriffogoes/scraper-notebook>

```
docker run -p8888:8888 -d -v $PWD:/home/jovyan/work rgriffogoes/scraper-notebook
```


# node

* [Versions](#versions)
* [Install](#install)
* [Node Package Manager](#node-package-manager)
  * [fnm](#fnm)
  * [volta](#volta)
  * [nvm](#nvm)
* [Frameworks](#frameworks)

## Versions

![](https://raw.githubusercontent.com/nodejs/Release/master/schedule.svg)

| byGrok               | npm v9 (\~2022–2023) | npm v10 (\~2023–2025) | npm v11 (\~2025–2026)      |
| -------------------- | -------------------- | --------------------- | -------------------------- |
| Bundled with Node    | 18 / 19              | 20 / 22               | 22+ / 24+                  |
| Minimum Node engines | ≥14.17               | ≥18.17 \|\| ≥20.5     | ≥18 / ≥20 / ≥22 (stricter) |

## Install

```
curl -qL https://www.npmjs.com/install.sh | sh
```

## Node Package Manager

| byGrok 2026 | Language | Cross-platform             | Auto-switch (.nvmrc/.node-version) | Speed / Shell startup | Per-project tools (npm/yarn/pnpm) | Best for                       | Popularity (approx.)  |
| ----------- | -------- | -------------------------- | ---------------------------------- | --------------------- | --------------------------------- | ------------------------------ | --------------------- |
| **nvm**     | Bash     | Yes (nvm-windows separate) | Yes                                | Slow (2-3s delay)     | No                                | Beginners, traditional users   | Highest (\~75k stars) |
| **fnm**     | Rust     | Yes                        | Yes (fastest)                      | Very fast (\~instant) | No                                | Speed + simplicity             | High                  |
| **Volta**   | Rust     | Yes                        | Yes (via package.json)             | Very fast             | Yes (pins npm/yarn/pnpm too)      | Teams, consistent tooling      | High                  |
| **asdf**    | Shell    | Yes                        | Yes                                | Medium                | No (plugins for others)           | Polyglot devs (multiple langs) | Medium-High           |
| **n**       | Bash     | macOS/Linux mainly         | No                                 | Fast                  | No                                | Minimalist, no shell mods      | Medium                |
| **nvs**     | JS       | Yes                        | Yes                                | Medium                | No                                | Windows focus, cross-platform  | Lower                 |

* Speed + easy → **fnm**
* Full JS toolchain pinning → **Volta**
* Multi-language → **asdf**
* Classic → **nvm**

### fnm

```
curl -fsSL https://fnm.vercel.app/install | bash
fnm install --lts

fnm env --use-on-cd --shell powershell | Out-String | Invoke-Expression # Windows
eval "$(fnm env --use-on-cd --shell bash)"                              # Linux

fnm list
fnm use 24.14.0
```

### volta

<https://volta.sh/>

```
curl https://get.volta.sh | bash
volta list
volta install node@18
```

### nvm

<https://github.com/nvm-sh/nvm>

## Frameworks

```
cd project
npm install -g vinext  --verbose
'DEBUG="true"' | Out-File -FilePath .dev.vars -Encoding utf8
vinext dev          # Hot Module Replacement, :3000
vinext build        # Production build
vinext deploy       # Build and deploy to Cloudflare Workers
```


# ocaml

* [Init](#init)
* [opam](#opam)
* [Jupyter](#jupyter)
* [Course](#course)

## Init

```
1. To configure OPAM in the current shell session, you need to run:

    eval `opam config env`

2. To correctly configure OPAM for subsequent use, add the following
line to your profile file (for instance ~/.profile):

    . /root/.opam/opam-init/init.sh > /dev/null 2> /dev/null || true

3. To avoid issues related to non-system installations of `ocamlfind`
add the following lines to ~/.ocamlinit (create it if necessary):

    let () =
        try Topdirs.dir_directory (Sys.getenv "OCAML_TOPLEVEL_PATH")
        with Not_found -> ()
    ;;
```

## opam

```
opam list -a         # List all available packages
opam update          # Update the packages database
opam upgrade         # Bring everything to the latest version possible    

opam switch list --all
opam switch <version> && eval $(opam config env)

opam pin add camlpdf ~/src/camlpdf                            # path
opam pin list

opam install depext
opam depext <packages>
opam list --rec --required-by <package>,<package>... --external

opam switch export file.export  # from the previous switch
opam switch <new switch>
opam switch import file.export
```

## Jupyter

<https://github.com/akabe/docker-ocaml-jupyter-datascience>

## Course

<http://www.cs.cornell.edu/courses/cs3110/>


# powershell

* [aliases](#aliases)
* [Basic](#basic)
* [disk](#disk)
* [zip folders](#zip-folders)
* [list top processes sort by memory](#list-top-processes-sort-by-memory)
* [sum memory of all processes](#sum-memory-of-all-processes)
* [list and grep process members](#list-and-grep-process-members)
* [query process by WMI](#query-process-by-wmi)

## aliases

```
% = foreach = ForEach
? = where = Where-Object  # ?{ $_ -NotMatch "regex" } 
```

## Basic

```
Set-ExecutionPolicy RemoteSigned
Enable-PSRemoting -Force

Import-Module ServerManager
Add-WindowsFeature RDS-Virtualization
```

## disk

```
GWMI -namespace root\cimv2 -class win32_volume | FL -property DriveLetter, DeviceID
```

## zip folders

```
Get-ChildItem -Directory | ForEach-Object {
    Compress-Archive -Path $_.FullName -DestinationPath "$($_.Name).zip" -Force
}
```

## list top processes sort by memory

```
Get-Process | Sort WorkingSet -Descending  | select-object  Id, Name, 
@{Name='WorkingSet(Mb)';Expression={"{0:N2}" -f ($_.WorkingSet / 1Mb)}}, 
@{Name='PrivateMemorySize(Mb)';Expression={"{0:N2}" -f ($_.PrivateMemorySize / 1Mb)}}, 
@{Name='PM(Mb)';Expression={"{0:N2}" -f ($_. PM/ 1Mb)}}, 
@{Name='NPM(Mb)';Expression={"{0:N2}" -f ($_. NPM/ 1Mb)}}  `
-First 10 | Format-Table
```

## sum memory of all processes

```
Get-Process  | measure-object -sum 'PrivateMemorySize', PM,NPM,WS  |  
select-object  @{Name='Sum(Gb)';Expression={"{0:N2}" -f ($_.sum / 1Gb  ) }  } ,count, Property
```

## list and grep process members

```
Get-Process | Get-Member | findstr Mem
```

## query process by WMI

```
Get-WMIObject Win32_Process
```


# py

* [uv](#uv)
  * [scripts](#scripts)
  * [Projects](#projects)
* [pipx](#pipx)
* [Anaconda](#anaconda)
* [EOL](#eol)
* [Relative imports in Python 3](#relative-imports-in-python-3)
* [Distribution Default](#distribution-default)
* [pip](#pip)
  * [Proxy](#proxy)
  * [CN Mirror](#cn-mirror)
* [pypi](#pypi)
* [Google Fire](#google-fire)
* [pendulum](#pendulum)
* [Web automation](#web-automation)
  * [requestium](#requestium)
* [VSCode](#vscode)
  * [Remote debugging](#remote-debugging)
* [Pythonista on IOS](#pythonista-on-ios)
* [MongoDB ORM](#mongodb-orm)
* [ASGI](#asgi)
* [Web Frameworks](#web-frameworks)
  * [starlette](#starlette)
  * [aiohttp](#aiohttp)
  * [Sanic](#sanic)
  * [API Server](#api-server)
* [WSDL](#wsdl)
* [tools](#tools)

## uv

<https://pypi.org/project/uv/>

```
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" # uv/uvx/uvw , v0.9.2 < 60MB
curl -LsSf https://astral.sh/uv/install.sh | sh                                    # uv/uvx
uv self update # ~/.local/bin (win+linux)

uv python install 3.14 3.12 # around 20MB each
uv python list # supported versions & local path

cd $path
uv venv --python 3.14 --seed # cat .venv/pyvenv.cfg
uv tool run jupyter lab # v4.4.9 : 99 packages
uv tool run --from jupyter-core jupyter
```

### scripts

<https://docs.astral.sh/uv/guides/scripts/>

```
uv run example.py

echo 'print("hello world!")' | uv run -

uv run - <<EOF
print("hello world!")
EOF
```

### Projects

```
$cd example
$ uv add ruff
Creating virtual environment at: .venv
$ uv run ruff check
$ uv lock
$ uv sync
```

Jupyter: <https://docs.astral.sh/uv/guides/integration/jupyter/#using-jupyter-within-a-project>

```
uv run --with jupyter jupyter lab  # pyproject.toml or uv.lock
```

## pipx

<https://github.com/pypa/pipx?tab=readme-ov-file#overview-what-is-pipx>

* creates an isolated environment for each application
* run from the command line directly

## Anaconda

<https://docs.anaconda.com/anaconda/packages/oldpkglists/>

```
Anaconda3\condabin>conda.bat activate

~/.bashrc # conda initialize
conda config --set auto_activate_base false

conda create -n py3.14 python=3.14
```

## EOL

<https://endoflife.date/python>

| Ver  | Released | EOS      |
| ---- | -------- | -------- |
| 3.14 | Oct 2025 | Oct 2027 |

## Relative imports in Python 3

<https://stackoverflow.com/a/49375740/4769874\\>
`from module1` intead of `from .module1`

```
# __init__.py
import os, sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
```

## Distribution Default

```
Debian 7 wheezy   2.7.3   /   3.2
Debian 8 jessie   2.7.9   /   3.4
Debian 9 stretch  2.7.13  /   3.5
Debian 10 buster  2.7.14  /   3.6
Debian 11 bullseye            3.9
```

## pip

```
# online
pip install git+   https://github.com/<owner_name>/<repo_name>.git

# local
pip install --download DIR -r requirements.txt
pip wheel --wheel-dir DIR -r requirements.txt
pip install --no-index --find-links=DIR -r requirements.txt
```

### Proxy

```
export all_proxy="socks5://x:y" # cause python error: Missing dependencies for SOCKS support.
pip install --proxy=https://user@mydomain:port  somepackage
```

### CN Mirror

mkdir -p \~/.pip\
&& echo '\[global]' > \~/.pip/pip.conf\
&& echo 'index-url = <https://mirrors.aliyun.com/pypi/simple/>' >> \~/.pip/pip.conf\
&& pip install -r requirements.txt

## pypi

<https://packaging.python.org/tutorials/distributing-packages/>

```
twine upload --repository testpypi dist/*
```

## Google Fire

<https://github.com/google/python-fire/blob/master/docs/guide.md#accessing-properties>

```python
import fire

english = 'Hello World'
fire.Fire()

# .py english

fire.Fire(lambda obj: type(obj).__name__)

# .py 10 / "10"                 # output: int
# .py '"10"' / "'10'" / \"10\"  # output: str

# .py '{"name": "David Bieber"}' # notice the quote, output: dict
# .py {"name":"David Bieber"}    # Wrong. output: str

# .py --obj=True / --obj
# .py --obj=False / --noobj

def hello(name):
  return 'Hello {name}!'.format(name=name)

if __name__ == '__main__':
  fire.Fire()

# .py hello name_value

class Calculator(object):

  def add(self, x, y):
    return x + y

if __name__ == '__main__':
  fire.Fire(Calculator)

# .py add 10 20

class BrokenCalculator(object):

  def __init__(self, offset=1):
      self._offset = offset

  def add(self, x, y):
    return x + y + self._offset

if __name__ == '__main__':
  fire.Fire(BrokenCalculator)

# .py add 10 20 --offset=0

class Airport(object):

  def __init__(self, code):
    self.code = code
    self.name = fn_x(self.code)

if __name__ == '__main__':
  fire.Fire(Airport)

# .py --code=SJC name

```

## pendulum

<https://github.com/sdispater/pendulum#pendulum>

```
tomorrow = pendulum.now().add(days=1)
last_week = pendulum.now().subtract(weeks=1)

if pendulum.now().is_weekend():
past.diff_for_humans()
```

## Web automation

### requestium

<https://github.com/tryolabs/requestium\\>
merges the power of Requests, Selenium, and Parsel into a single integrated tool

## VSCode

### Remote debugging

VS: <https://youtu.be/y1Qq7BrV6Cc?t=228\\>
VSCode: <https://code.visualstudio.com/docs/python/debugging#\\_remote-debugging>

```
# bug: https://github.com/DonJayamanne/pythonVSCode/issues/981#issuecomment-308085243
pip install ptvsd==3.0.0    
```

```python
import ptvsd
ptvsd.enable_attach("my_secret", address = ('0.0.0.0', 3000))

ptvsd.wait_for_attach()
```

## Pythonista on IOS

<https://github.com/Pythonista-Tools/Pythonista-Tools/blob/master/Utilities.md>

## MongoDB ORM

<http://ming.readthedocs.io/en/latest/>

<http://turbogears.readthedocs.io/en/latest/turbogears/mongodb.html>

## ASGI

uvicorn, daphne, or hypercorn

## Web Frameworks

<https://github.com/topics/web-framework?l=python\\>
<https://wiki.python.org/moin/WebFrameworks>

### starlette

<https://github.com/encode/starlette>

### aiohttp

<https://github.com/aio-libs/aiohttp\\>
<https://aiohttp.readthedocs.io/en/stable/\\>
Supports both client and server Web-Sockets\
Web-server has middlewares and pluggable routing.

### Sanic

<https://github.com/channelcat/sanic>

### API Server

<https://github.com/tiangolo/fastapi\\>
<http://www.hug.rest/>

## WSDL

<http://www.soapclient.com/xml/soapresponder.wsdl\\>
<http://download.oracle.com/otn\\_hosted\\_doc/jdeveloper/1012/web\\_services/ws\\_wsdlstructure.html>

## tools

| pkg      | for                                     | link                                                                                    |
| -------- | --------------------------------------- | --------------------------------------------------------------------------------------- |
| pydantic | Data validation using Python type hints | <https://docs.pydantic.dev/latest/why/#type-hints>                                      |
| mypy     | static type checker                     | <https://mypy.readthedocs.io/en/stable/getting\\_started.html#dynamic-vs-static-typing> |
| ruff     | linter and formatter                    | <https://docs.astral.sh/ruff/tutorial/>                                                 |


# py\_GUI

* [Windows](#windows)
* [QT](#qt)
  * [proxy](#proxy)
* [Apps](#apps)
  * [Browser](#browser)
    * [qutebrowser](#qutebrowser)
    * [admbrowser](#admbrowser)

## Windows

<https://pypi.org/project/auto-py-to-exe/>

```
pip install --upgrade PyQt5
pip install auto-py-to-exe
auto-py-to-exe        # GUI
auto-py-to-exe --help # cli
Win+R -> shell:startup
```

## QT

```
pip install --upgrade PyQt5
# or
pip install --upgrade PySide6 # Qt 6.0+
```

### proxy

<https://www.google.com/search?q=python+QNetworkProxy+code+sample>

```
# 1. Create a QNetworkProxy instance
proxy = QNetworkProxy()

# 2. Set the proxy type (e.g., Socks5Proxy, HttpProxy)
proxy.setType(QNetworkProxy.Socks5Proxy)

# 3. Set the proxy host and port
proxy.setHostName("localhost")  # Replace with your proxy server address
proxy.setPort(9050)             # Replace with your proxy server port
```

## Apps

### Browser

#### qutebrowser

Install: <https://github.com/qutebrowser/qutebrowser/blob/master/doc/install.asciidoc#manual-install\\>
Windows + tox + conda: <https://stackoverflow.com/questions/30555943/is-it-possible-to-use-tox-with-conda-based-python-installations>

Proxy Types: <https://github.com/qutebrowser/qutebrowser/blob/86fca3e99ee4836f5f591831eb93a09ffb8231d2/qutebrowser/utils/urlutils.py#L599>

#### admbrowser

<https://github.com/alandmoore/admbrowser>

```
HTTPS, FTP, SOCKS, or authenticated proxy is not currently supported
```


# Django

* [data](/dev/py_django#data)
* [init](/dev/py_django#init)
* [Demo](/dev/py_django#demo)

## data

```
./manage.py dumpdata > db.json
./manage.py dumpdata app_name[.table_name] --indent 2 --exclude ... > ...
./manage.py loaddata foo.json
./manage.py loaddata fixture_name  # app_name/fixtures/foo.json
```

## init

```
./manage.py makemigrations connection
./manage.py makemigrations
./manage.py migrate
./manage.py compilemessages
./manage.py shell < ./foo.py
```

static files not working when DEBUG=False

## Demo

A small project for testing django features: i18n/templates/admin/shell/fixture/signal/etc.\
<https://github.com/fzinfz/tsadmin/commits/master>


# shell

* [Filename](#filename)
* [Pattern Matching](#pattern-matching)
* [Operations on variables](#operations-on-variables)
* [heredoc](#heredoc)

## Filename

| cmd                | result            |
| ------------------ | ----------------- |
| $0                 | ./t.sh            |
| $(basename $0)     | t.sh              |
| $(basename $0 .sh) | t                 |
| `${PWD##*/}`       | parent\_dir\_name |

## Pattern Matching

<https://www.gnu.org/software/bash/manual/html\\_node/Pattern-Matching.html>

## Operations on variables

<https://www.gnu.org/software/bash/manual/html\\_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion>

| type                 | example                          | result    | More                                                 |
| -------------------- | -------------------------------- | --------- | ---------------------------------------------------- |
| Length               | echo ${#SHELL}                   | 9         |                                                      |
| `${parameter:-$var}` | `${NULL:-$SHELL}`                | /bin/bash |                                                      |
| ${parameter:-word}   | echo ${SHELL:-ignored}           | /bin/bash | \[ -z "${COLUMNS:-}" ] && COLUMNS=80 ; echo $COLUMNS |
| ${parameter:=word}   | unset a ; echo ${a:=b} ; echo $a | b b       |                                                      |
| ${VAR:OFFSET:KEEP}   | echo ${SHELL:0:4}                | /bin      |                                                      |
| ${VAR/PATTERN/NEW}   | echo ${SHELL/b/}                 | /in/bash  |                                                      |
| ${VAR//PATTERN/NEW}  | echo ${SHELL//b/}                | /in/ash   |                                                      |
| `${VAR#beginning}`   | echo ${SHELL#\*/}                | bin/bash  |                                                      |
| `${VAR##beginning}`  | echo ${SHELL##\*/}               | bash      |                                                      |
| `${VAR%trailing}`    | ${SHELL%/\*h}                    | /bin      |                                                      |

## heredoc

<https://en.wikipedia.org/wiki/Here\\_document#Unix\\_shells>


# snippets

## Linux

<https://github.com/fzinfz/scripts/blob/master/linux/init.sh>

```bash

date "+%Y%m%d_%H%M%S"

```

## Python

<https://github.com/fzinfz/ipynb/tree/main/python>

```python

import time
f = "_" + str(time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))) + '.xlsx'

import subprocess
print(subprocess.check_output(['cat', path]))
print(subprocess.check_output(cmd, shell=True).strip())

```


# uni

* [tauri](#tauri)
* [NativeScript](#nativescript)

## Quasar

<https://quasar.dev/introduction-to-quasar#what-is-quasar>

## Tauri

<https://github.com/tauri-apps/tauri>

## uni-app

<https://en.uniapp.dcloud.io/>

## NativeScript

<https://docs.nativescript.org/environment-setup.html#windows-android>

```
npm config set proxy http://192.168.88.25:7890
npm install -g nativescript
ns doctor android
```


# vba

* [Books](#books)
* [Basic](#basic)
* [String & Regex](#string--regex)
* [MsgBox](#msgbox)
* [Dim & ReDim](#dim--redim)
* [Sheets](#sheets)
* [Range & Cell](#range--cell)
* [ColorIndex Property](#colorindex-property)
* [Test cell empty](#test-cell-empty)
* [Find string & delete row](#find-string--delete-row)
* [Array](#array)
* [Filter](#filter)
* [Hyperlinks](#hyperlinks)
* [Time](#time)

## Books

[Excel 2007 VBA Programmer's Reference](http://www.wrox.com/WileyCDA/WroxTitle/Excel-2007-VBA-Programmer-s-Reference.productCd-0470046430,descCd-DOWNLOAD.html)

## Basic

sheets = worksheet + chart function: can be used in cell IIF = IF THEN ELSE

```
' Force explicit variable declaration.
Option Explicit On

'turns off all error handling for subsequent statements
On Error Resume Next

Dim owner_index As Integer 'default = 0
```

## String & Regex

```
Sub Split_Cell_String()
    With ActiveSheet
        For r = 2 To 37
            s = .Range("B" & r).Value

            Set objRegExp_1 = CreateObject("vbscript.regexp")
            objRegExp_1.Global = True
            objRegExp_1.IgnoreCase = True
            objRegExp_1.Pattern = "[\d:]+"

            Set regExp_Matches = objRegExp_1.Execute(s)
            For Each m In regExp_Matches
                .Cells(r, 6).Value = m
                .Cells(r, 7).Value = objRegExp_1.Replace(s, "")
            Next
        Next
    End With
End Sub
```

## MsgBox

```
MsgBox(prompt[, buttons] [, title] [, helpfile, context])
MsgBox prompt:="xxx" , title:=... , Msgbox Buttons:=vbOKOnly/vbOKCancel/vbAbortRetryIgnore.. (Note the COMMA)
Answer = MsgBox(Prompt:=”Delete this record?”, Buttons:=vbYesNo + vbQuestion) (Note the PARENTHESES)
If Answer = vbYes/vbNo/vb...
UserName = InputBox(Prompt:=”Please enter your name”)
```

## Dim & ReDim

Dim advantage: preservation of capitalization.\
ReDim will re-initialize the array and destroy any data in it, unless you use the Preserve keyword. It is necessary to declare sht as the generic Object type if you want to allow it to refer to different sheet types.

## Sheets

There is a Sheets collection in the Excel object model, but there is no Sheet object.

```
With Workbooks.Add
    With .Worksheets.Add(After:=.Sheets(.Sheets.Count))
        .Name = “January”
        .Range(“A1”).Value = “Sales Data”
    End With
    .SaveAs Filename:=”JanSales.xlsx”
End With

icount = Worksheets.Count
Worksheets(1).Copy After:=Worksheets(icount) // icount won't ++
```

## Range & Cell

```
[A1] = 10
Range(“B3:E10”).Select
Range(“C5:Z100”).Activate ' C5 will be actived since it's within B3:E10
ActiveCell.Offset(2, 0).EntireRow.Select
Range(“A1”).End(xlDown)
Range(“B3”, Range(“B3”).End(xlToRight).End(xlDown)).Select
Range(“A1:B5,C6:D10,E11:F15”).Rows.Count ' return rows number of A1:B5
```

## ColorIndex Property

![](http://i.msdn.microsoft.com/Aa199411.colorin%28en-us,office.10%29.gif)\
Rows.Interior.ColorIndex = xlColorIndexNone

## Test cell empty

The IsEmpty function is the best way to test that a cell is empty.\
If you use If Cells(row,col) = “”, the test will be true for a formula that calculates a zero-length string.

```
MsgBox Evaluate(“=ISBLANK(A1)”)
MsgBox [ISBLANK(A1)]
```

## Find string & delete row

```
column.find

Sub DeleteRows2()
    Dim rngFoundCell As Range
    ‘Freeze screen
    Application.ScreenUpdating = False

    'Application.ScreenUpdating = False + workbook.open+close : open workbook in background
    ‘Find a cell containing Mangoes
    Set rngFoundCell = Range(“C:C”).Find(What:=”Mangoes”)

    ‘Keep looping until no more cells found
    Do Until rngFoundCell Is Nothing

    ‘Delete found cell row
    rngFoundCell.EntireRow.Delete

    ‘Find next
    Set rngFoundCell = Range(“C:C”).FindNext
    Loop
End Sub
```

## Array

```
For array_member = LBound(array) To UBound(array)
For each array_member in array
keywords_auto_route = Array("KMS, PK ", "GPS", "logo([^n]|$)")
```

## Filter

```
Sheet.FilterMode = Data has been filtered?
.Range("A1").AutoFilterMode = false
.Range("A1").AutoFilter
```

## Hyperlinks

```
With ActiveSheet
    .Hyperlinks.Add Anchor:=.Range("G17"), _
    Address:="", _
    SubAddress:="other_sheet!cell", _
    TextToDisplay:="TextToDisplay"
End With
```

## Time

```
format(date, "yyyy/mm/dd")  'TimeZone: http://www.cpearson.com/Zips/TimeZone.ZIP

Dim TInfo As CTime
Dim D As Double

If TInfo Is Nothing Then
    Set TInfo = New CTime
Else
    TInfo.Refresh
End If

today = Format(TInfo.GMT + 8 / 24, "yyyy/mm/dd") 'force to be +8:00
```


# wechat.zh

* [Token](#token)
* [IP List](#ip-list)

## Token

<https://api.weixin.qq.com/cgi-bin/token?grant\\_type=client\\_credential\\&appid=APPID\\&secret=APPSECRET>

## IP List

<https://api.weixin.qq.com/cgi-bin/getcallbackip?access\\_token=ACCESS\\_TOKEN>

```
[print("add address=" + i.replace("\\","") + " list=wechat")  for i in list ]   # ip list rule
```


# wechat\_mp.zh

* [Docs](#docs)
* [DevTool](#devtool)
* [生命周期](#生命周期)
  * [app](#app)
  * [pages](#pages)
* [逻辑](#逻辑)
  * [app.js \*](#appjs-)
  * [page.js \*](#pagejs-)
* [配置](#配置)
  * [app.json \*](#appjson-)
  * [page.json](#pagejson)
* [样式 - WeiXin Style Sheets](#样式---weixin-style-sheets)
  * [同层渲染](#同层渲染)
  * [app.wxss](#appwxss)
  * [page.wxss](#pagewxss)
* [结构](#结构)
  * [page.wxml \*](#pagewxml-)
    * [wxs - WeiXin Script](#wxs---weixin-script)
    * [简易双向绑定](#简易双向绑定)
    * [navigator](#navigator)
* [Map](#map)
  * [jssdk](#jssdk)
  * [plugin](#plugin)
* [Code](#code)
* [Books](#books)

## Docs

开始：<https://developers.weixin.qq.com/miniprogram/dev/framework/quickstart/getstart.html\\>
小程序专用邮箱登录：<https://mp.weixin.qq.com/\\>
app\&pages: <https://developers.weixin.qq.com/miniprogram/dev/framework/structure.html>

| 作用  | 格式   | App | Page |
| --- | ---- | --- | ---- |
| 逻辑  | js   | 必需  | 必需   |
| 配置  | json | 必需  | -    |
| 样式表 | wxss | -   | -    |
| 结构  | wxml | 无   | 必需   |

## DevTool

<https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html\\>
推送到微信：右上角 =》 详情-本地设置

## 生命周期

### app

<https://developers.weixin.qq.com/miniprogram/dev/framework/runtime/operating-mechanism.html>

<https://developers.weixin.qq.com/miniprogram/dev/reference/api/App.html>

```
onLaunch(Object object) 小程序初始化完成时触发，全局只触发一次。
onShow(o)/Hide()/Error(String error)/PageNotFound(o)/UnhandledRejection(o)/ThemeChange(o)/CUSTOM
```

### pages

<https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/page-life-cycle.html\\>
onLaunch/Show/... 同app： <https://developers.weixin.qq.com/miniprogram/dev/reference/api/App.html>

## 逻辑

### app.js \*

<https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/app.html>

```
App({ // App() 必须在 app.js 中调用，必须调用且只能调用一次。
    globalData: 'I am global data'
})

// page.js
const appInstance = getApp() // 获取到全局唯一的 App 实例
console.log(appInstance.globalData) // I am global data
```

### page.js \*

<https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/page.html\\>
<https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html>

```
data/options/behaviors/onXXX/CUSTOM
开发者可以添加任意的函数或数据到 Object 参数中，在页面的函数中用 this 可以访问。这部分属性会在页面实例创建时进行一次深拷贝。

Page({
data: {
    message: 'Hello MINA!'
    array: [1, 2, 3, 4, 5]
    view: 'MINA'
    staffA: {firstName: 'Hulk', lastName: 'Hu'},
}
})
```

## 配置

### app.json \*

<https://developers.weixin.qq.com/miniprogram/dev/framework/config.html\\>
Layout: <https://res.wx.qq.com/wxdoc/dist/assets/img/config.344358b1.jpg>

| app.json       | 类型           | 必填 | 描述              |
| -------------- | ------------ | -- | --------------- |
| pages          | String Array | 是  | 设置页面路径          |
| window         | Object       | 否  | 设置默认页面的窗口表现     |
| tabBar         | Object       | 否  | 设置底部 tab 的表现    |
| networkTimeout | Object       | 否  | 设置网络超时时间        |
| debug          | Boolean      | 否  | 设置是否开启 debug 模式 |

### page.json

<https://developers.weixin.qq.com/miniprogram/dev/framework/config.html#%E9%A1%B5%E9%9D%A2%E9%85%8D%E7%BD%AE>

## 样式 - WeiXin Style Sheets

### 同层渲染

<https://developers.weixin.qq.com/community/develop/article/doc/000c4e433707c072c1793e56f5c813>

### app.wxss

<https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxss.html>

```
@import "common.wxss";  /** app.wxss **/

<view class="normal_view" />
<view style="color:{{color}};" />
```

### page.wxss

<https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxss.html>

## 结构

### page.wxml \*

<https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/>

```
# get value from: page.js - Page({ data: { } })
<view> {{message}} </view>

<view wx:for="{{array}}"> {{item}} </view>

<view wx:if="{{view == 'WEBVIEW'}}"> WEBVIEW </view>
<view wx:elif="{{view == 'APP'}}"> APP </view>
<view wx:else="{{view == 'MINA'}}"> MINA </view>

<template name="staffName">
<template is="staffName" data="{{...staffA}}"></template>
```

#### wxs - WeiXin Script

```
<wxs module="m1">
var msg = "hello world";
module.exports.message = msg;
</wxs>

<view> {{m1.message}} </view>
```

#### 简易双向绑定

<https://developers.weixin.qq.com/miniprogram/dev/framework/view/two-way-bindings.html>

```
<input value="{{value}}" />        单向
<input model:value="{{value}}" />  双向
```

#### navigator

<https://mp.weixin.qq.com/debug/wxadoc/dev/component/navigator.html>

## Map

Demo: <https://github.com/TencentLBS/TencentMapMiniProgramDemo>

Doc: <https://mp.weixin.qq.com/debug/wxadoc/dev/component/map.html#map\\>
controls控件即将废弃 => view

### jssdk

<https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/jsSdkOverview\\>
<http://lbs.qq.com/qqmap\\_wx\\_jssdk/index.html>

个性化地图：<https://lbs.qq.com/dev/console/custom/guide#miniapp>

### plugin

<https://lbs.qq.com/miniProgram/plugin/pluginGuide/pluginStart>

## Code

```
  <view class="section">
    <view class="flex-wrp" style="flex-direction:row;">
      <view class="flex-item">
        <button bindtap='search'>Search</button>
      </view>
      <view class="flex-item">
        <button bindtap='clear'>Clear</button>
      </view>
    </view>
  </view>
  
  .flex-wrp{display:flex;}

button {
  margin: 0.5rem
}

<input value="{{ addr }}" bindinput='inputAddr'></input>

input {
  border-radius:4px;
  border-color: blue;
  border-style: solid;
  padding: 0.5rem;
  width: 90%
}

inputAddr: function (e) {
this.setData({
    addr: e.detail.value,
})
},

  clear: function () {
    this.setData({
      addr: ""
    });
  },

  data: {
    markers: [{
      id: 0,
    }]
  },

    <radio-group class="radio-group" bindchange="radioChange">
      <label class="radio" wx:for="{{items}}" wx:key="city" >
        <radio value="{{item.city}}站" checked="{{item.checked}}" bindtap='search' />{{item.city}}
      </label>
    </radio-group>

    items: [
      { city: '深圳' },
      { city: '广州' },
    ]

  radioChange: function (e) {
    this.setData({
      addr: e.detail.value
    });
  },

var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;

  search: function (e) {
    var that = this;
    var addr_array;
    if (typeof e === "undefined") {
      addr_array = that.data.region;
    } else {
      addr_array = e.detail.value;
    };
    qqmapsdk.geocoder({
      address: addr_array.join(''),
      success: function (res) {
        that.setData({
          region: addr_array,
          region_hint: addr_array[1],
          //raw: JSON.stringify(res, null, '\t'),
          location: JSON.stringify(res.result.location),
          lng: res.result.location.lng,
          lat: res.result.location.lat,
        });
      }
    });
  },

    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          view: {
            Height: res.windowHeight - 20
          }
        })
      }
    });
```

## Books

<http://www.weixinbook.net/download/>


# elec

* [Package](#package)
* [Symbol](#symbol)
* [Buck & Boost](#buck--boost)
  * [Buck/step-down regulators](#buckstep-down-regulators)
    * [Synchronous Rectification](#synchronous-rectification)
  * [Boost/step-up regulators](#booststep-up-regulators)
  * [forward vs flybac](#forward-vs-flybac)
* [Oscilloscope](#oscilloscope)

## Package

<https://en.wikipedia.org/wiki/List\\_of\\_integrated\\_circuit\\_packaging\\_types#Transistor,\\_diode,\\_small-pin-count\\_IC\\_packages>

## Symbol

<https://en.wikipedia.org/wiki/Electronic\\_symbol>

## Buck & Boost

by Eugene Khutoryansky: <https://www.youtube.com/watch?v=vwJYIorz\\_Aw>

More: [boost.md](/elec/boost) | [bulk.md](/elec/bulk)

### Buck/step-down regulators

<https://learnabout-electronics.org/PSU/psu31.php>

15: <https://www.bilibili.com/video/BV1nA411t7U4>

BUCK电源电感怎么选择： <https://www.bilibili.com/video/BV1ig411P7dc?t=112.2>

#### Synchronous Rectification

同/异步整流：<https://www.bilibili.com/video/BV1Jv411P7Qc?t=369.7\\>
<https://www.analog.com/en/analog-dialogue/raqs/raq-issue-147.html>

### Boost/step-up regulators

<https://learnabout-electronics.org/PSU/psu31.php>

### forward vs flybac

<https://www.eet-china.com/mp/a12732.html\\>
反激的变压器可以看作一个带变压功能的电感，是一个buck-boost电路。反激是初级工作，次级不工作，一般DCM模式。\
正激的变压器是只有变压功能，整体可以看成一个带变压器的buck电路。正激是初级工作次级也工作，次级不工作有续流电感续流，一般是CCM模式。

反激式同步整流控制技术：<https://www.bilibili.com/video/BV1bJ411W7Hi>

## Oscilloscope

示波器测量市电 - AB伪差分：[Siglent](https://youtu.be/kIir80Jnlyo?t=296) | [Tek](https://www.bilibili.com/video/BV1JU4y1K7cy?t=421.1)\
纹波：[Tek](https://www.bilibili.com/read/cv14145415) | [Rigol](https://www.bilibili.com/video/BV1my4y167ao?t=77.1)


# 3D Printing

* [Design](#design)
* [Slicer](#slicer)
* [Modeling](#modeling)
* [Printer](#printer)
* [Material](#material)
* [Printers](#printers)
  * [Ender3 S1](#ender3-s1)

## Design

FreeCAD: github.com/FreeCAD/FreeCAD\
Mesh: <https://github.com/cnr-isti-vclab/meshlab\\>
Web: <https://www.sketchup.com/plans-and-pricing/compare\\>
OpenSCAD Functional programming language: <https://en.wikibooks.org/wiki/OpenSCAD\\_User\\_Manual/General\\>
2D/.dxf/.dwg: <https://github.com/qcad/qcad> | <https://qcad.org>

## Slicer

.stl/.obj/.amf -> gcode

Ultimaker cura: <https://github.com/Ultimaker/Cura\\>
based on [Slic3r](https://github.com/slic3r/Slic3r)：<https://github.com/prusa3d/PrusaSlicer>

Web / OctoPrint: <https://github.com/OctoPrint/OctoPrint\\>
Web + Desktop / Repetier Host: <https://www.repetier.com/download-now/>

## Modeling

<https://zh.wikipedia.org/wiki/3D%E6%89%93%E5%8D%B0#%E8%BF%87%E7%A8%8B>

FDM/Fused Deposition Modeling: 熔融沉积成型 | 1.75/2.85mm

## Printer

光轴/导杆/导向轴 圆 精度< 方形线轨 or 双轴心线性导轨 | 滑轮/V轮：易磨损

## Material

<https://zhuanlan.zhihu.com/p/307980776>

* PLA: 无臭味/坚硬、储存防受潮
* ABS: 打印时味道、高抗衝擊強度、韌性
* TPU: 半柔性、建议近端送料
* PETG：吸濕性 | <https://www.3dprintinglab.com.hk/blog/3d-filament-petg-guide/>

![](https://pic3.zhimg.com/80/v2-a25fc6c7756b07eaee7f2947354039a6_720w.webp)

## Printers

导轨调平：<https://www.youtube.com/watch?v=dWpeKuIPFRE>

### Ender3 S1

* 手动+自动调平：<https://www.cxsw3d.com/Ender3S1/262-5328.html>
* 中途换料/暂停：<https://www.cxsw3d.com/Ender3S1/262-5332.html>


# AC

* [Power Meter](#power-meter)
* [Voltages](#voltages)
* [Power Connectors](#power-connectors)
  * [Industrial](#industrial)
* [Residual Current Device](#residual-current-device)
* [UPS](#ups)
* [Docs](#docs)

## Power Meter

DLT645抄表：<https://github.com/fzinfz/flask-DLT645>

## Voltages

<https://en.wikipedia.org/wiki/Mains\\_electricity\\_by\\_country#Table\\_of\\_mains\\_voltages,\\_frequencies,\\_and\\_plugs> ![](https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/World_Map_of_Mains_Voltages_and_Frequencies%2C_Detailed.svg/1200px-World_Map_of_Mains_Voltages_and_Frequencies%2C_Detailed.svg.png)

* CN 220/380V 50Hz | UK 230V 50Hz | US 120/240V 60Hz

## Power Connectors

<https://en.wikipedia.org/wiki/IEC\\_60320#Appliance\\_couplers\\>
C13/C14 and C15/C16 connectors for up to 15 A\[10] (IEC maximum is 10 A)\
C15/C16's temperature rating is 120 °C rather than the 70 °C of the similar C13/C14 combination.\
C19/C20 and C21/C22 connectors for up to 20 A\[11] (IEC maximum is 16 A)

<https://en.wikipedia.org/wiki/NEMA\\_connector> ![](https://upload.wikimedia.org/wikipedia/commons/thumb/0/0d/NEMA_simplified_pins.svg/525px-NEMA_simplified_pins.svg.png)

### Industrial

<https://en.wikipedia.org/wiki/Industrial\\_and\\_multiphase\\_power\\_plugs\\_and\\_sockets>

## Residual Current Device

<https://www.theiet.org/forums/forum/messageview.cfm?catid=205\\&threadid=9258>

```
RCD - Residual Current Device 
RCCB - Residual Current Circuit Breaker 
RCBO - Residual Current circuit Breakers integral Over current protection 
ELCB - Earth Leakage Circuit Breaker 
```

RCD is the term that covers a family of devices.

RCCBs are RCDs without any overload protection.

RCBOs are RCDs with overcurrent protection included in the device.

CBRS are circuit breakers with residual current protection which may or may not be integral.

SRCDS are socket outlets with RCD protection.

PRCDS are RCDS built in to a plug.

MRCDS are independantly mounted devices that provide a signal to trip another device.

SRCBOS are sockets incorporating an RCD and overcurrent protection.

RCDs without overcurrent protection must be protected by a separate overcurrent device.

## UPS

* Online/double-conversion: the batteries are always connected to the inverter
* Offline/standby: <https://upload.wikimedia.org/wikipedia/commons/thumb/6/66/Standby\\_UPS\\_Diagram\\_SVG.svg/525px-Standby\\_UPS\\_Diagram\\_SVG.svg.png>
* Line-interactive: adjust if over/under normal voltage | <https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Line-Interactive\\_UPS\\_Diagram\\_SVG.svg/750px-Line-Interactive\\_UPS\\_Diagram\\_SVG.svg.png>

Compare: EEVBlog <https://youtu.be/Fj7e3WGUKO8?t=521>

## Docs

常见电气元件: <http://www.sohu.com/a/216349064\\_488169\\>
导线趋肤效应和临近效应：<http://www.sohu.com/a/221088726\\_488169>

ABB低压产品目录： <https://library.e.abb.com/public/3ed9d6e55176101f48257d46000d1d62/1SXF000032X2001\\_022011\\_OEM.pdf>


# MOSFET

* [Chip](#chip)
* [Ideal Diodes](#ideal-diodes)
* [Learn](#learn)

## Chips

| Model                                                                                                                       | Vds | mΩ   | I    |
| --------------------------------------------------------------------------------------------------------------------------- | --- | ---- | ---- |
| [4N041R7](https://www.infineon.com/dgdl/Infineon-IPLU250N04S4-1R7-DS-v01_00-EN.pdf?fileId=5546d4624a0bf290014a4df712153452) | 40V | 1.7  | 250A |
| [P75NF75](https://www.st.com/resource/en/datasheet/stb75nf75.pdf)                                                           | 75V | < 11 | 80A  |

## Ideal Diodes

* 理想二极管基础知识 | <https://www.ti.com.cn/cn/lit/an/zhcab91b/zhcab91b.pdf>
* Basics of Ideal Diodes | <https://www.ti.com/lit/an/slvae57b/slvae57b.pdf>
* LTspice仿真 | <https://www.analog.com/cn/products/ltc4358.html#product-tools>
* Products
  * LT4320 / LT4321 | <https://www.analog.com/cn/parametricsearch/11518#/>

| Model                                                                                     | Vds  | Pins         |
| ----------------------------------------------------------------------------------------- | ---- | ------------ |
| [LTC4357](https://www.analog.com/media/en/technical-documentation/data-sheets/4357fd.pdf) | 9-80 | 8-Lead MSOP  |
| [LT4320](https://www.analog.com/media/en/technical-documentation/data-sheets/4320fb.pdf)  | 9-72 | 12-Lead MSOP |

## Learn

* MOS管控制电源通断以及缓启动：<https://www.bilibili.com/video/BV1fU4y1J7xi>


# PCB

* [Capacitor](#capacitor)

## Capacitor

TH Through-Hole vs SMD BD: Body Diameter Pitch 两个引脚之间的 间距 Drill hole / Pin Diameter 钻孔的直径或引脚本身的粗细


# arduino

* [IDE](#ide)
* [cli](#cli)
* [Pinout](#pinout)
* [ESP32](#esp32)
* [Uno](#uno)
  * [Q](#q)
  * [R3](#r3)
* [OLED](#oled)
  * [IDE](#ide-1)
* [3D Case](#3d-case)

## IDE

* \~/.arduinoIDE/arduino-cli.yaml (Linux/macOS)
* C:\Users\YourUsername.arduinoIDE\arduino-cli.yaml (Windows)

```
cd D:\Program Files\Arduino IDE\resources\app\lib\backend\resources

# fix: Client.Timeout
arduino-cli config set network.connection_timeout 600s

# fix: following symlink ... cannot find the path specified
arduino-cli config get directories.data
arduino-cli config set directories.data TARGET_DIR
```

## cli

```
arduino-cli board list
```

## Pinout

| Feature              | GPIO (General-Purpose I/O)                     | PWM (Pulse Width Modulation) | ADC (Analog-to-Digital Converter) |
| -------------------- | ---------------------------------------------- | ---------------------------- | --------------------------------- |
| **Input/Output**     | Both **Input** and **Output**.                 | **Output** only.             | **Input** only.                   |
| **Arduino Function** | `pinMode()`, `digitalWrite()`, `digitalRead()` | `analogWrite()`              | `analogRead()`                    |
| **Mark**             | D\_                                            | \~D\_                        | A\_                               |

AREF: <http://tronixstuff.com/2013/12/12/arduino-tutorials-chapter-22-aref-pin/>

## ESP32

* All: <https://products.espressif.com/#/product-comparison?names=ESP32-C3,ESP32-S3,ESP32-C6\\&type=SoC>
* S3: <https://docs.arduino.cc/hardware/nano-esp32/>
* C3/C6/S3: <https://wiki.seeedstudio.com/SeeedStudio\\_XIAO\\_Series\\_Introduction/#seeed-studio-xiao-series-comparison-table>

## Uno

<https://www.arduino.cc/en/hardware/#uno-family>

### Q

* Debian-capable
* Qualcomm QRB2210 microprocessor (MPU), quad-core 2.0 GHz CPU
* real-time STM32U585 microcontroller (MCU)
* RAM: 2GB LPDDR4
* Storage: 16 GB eMMC built-in (no SD card required)

### R3

Atmel AVR ATmega328P | 8-bit RISC | 16MIPS throughput at 16MHz

* <https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P\\_Datasheet.pdf>

<https://store-usa.arduino.cc/products/arduino-uno-rev3>

* INPUT VOLTAGE (LIMIT) 6-20V limit / 7-12V recommended
* DC CURRENT PER I/O PIN 20 mA

<https://content.arduino.cc/assets/A000066-pinout.png>

* 14 digital input/output pins (of which 6 can be used as PWM outputs)
* 6 analog inputs

## OLED

* I2C: 100Khz - 3.4Mhz, many devices on the same bus
* SPI: 4Mhz and up to 100Mhz

### IDE

* Sketch Menu -> Include Library -> Manage Libraries
  * Search: `BusIO` + `adafruit ssd1306`
* File -> Examples

SSD1306 Oled display: <https://create.arduino.cc/projecthub/Arnov\\_Sharma\\_makes/0-96-inch-oled-getting-started-guide-78163a>

```
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library. 
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
```

* File -> Examples ---> ssd1306\_128x32\_spi

```
    // Declaration for SSD1306 display connected using software SPI (default case)
    #define OLED_MOSI   9
    #define OLED_CLK   10
    #define OLED_DC    11
    #define OLED_CS    12
    #define OLED_RESET 13
```

## 3D Case

Pro Mini | Wall | <https://www.thingiverse.com/thing:2457807>


# battery

* [Quick Charge](#quick-charge)
* [Types](#types)
  * [Solar](#solar)
  * [Pb](#pb)
    * [充电](#充电)
    * [Repair](#repair)
      * [第一步：均衡充电 (Equalization)](#第一步均衡充电-equalization)
      * [第二步：调整电解液浓度（“调酸”）](#第二步调整电解液浓度调酸)
      * [第三步：补水（针对比重过高）](#第三步补水针对比重过高)
  * [Ni](#ni)
  * [Li](#li)
* [DC UPS](#dc-ups)

## Quick Charge

* USB Promoters Group : <https://en.wikipedia.org/wiki/USB\\_hardware#USB\\_Power\\_Delivery>
* Qualcomm ： <https://en.wikipedia.org/wiki/Quick\\_Charge>

| tech            | year                                      | max power           |
| --------------- | ----------------------------------------- | ------------------- |
| QC3             | 2016                                      | 36 W (12 V × 3 A)   |
| QC4             | 2017                                      | 100 W (20 V × 5 A)  |
| QC3+            | 2020                                      | 20mV steps from QC4 |
| PD2.0 / USB 3.1 | 2014                                      | 100W ( 20V x 5A )   |
| PD3.0           | 2015/2017                                 | 100W                |
| PD3.1           | 2021 <https://www.usb.org/usb-charger-pd> | 240W ( 48V x 5A )   |

## Types

<https://zh.wikipedia.org/wiki/%E8%93%84%E9%9B%BB%E6%B1%A0#%E8%93%84%E9%9B%BB%E6%B1%A0%E7%A8%AE%E9%A1%9E%E5%88%97%E8%A1%A8>

### Solar

open-circuit 0.5 to 0.6 volts: <https://en.wikipedia.org/wiki/Solar\\_cell>

### Pb

<https://en.wikipedia.org/wiki/Lead%E2%80%93acid\\_battery>

* 1.8V loaded at full discharge, to
* 2.1V in an open circuit at full charge

<https://www.blazartheory.com/files/notes/phy2049/Lead\\_Acid\\_Batteries.pdf>

* lead (Pb 铅) terminal
* lead(IV) oxide (PbO2) terminal
* sulfuric(硫酸) acid(酸) (H2 SO4) bath

| byGrok            | 吸收/恒压阶段 (Bulk→Absorption) | 浮充阶段 (Float) | 均衡充电 (Equalization) | 备注         |
| ----------------- | ------------------------- | ------------ | ------------------- | ---------- |
| 富液式 (Flooded)     | 14.4–14.8V                | 13.5–13.8V   | 15.0–15.6V          | 最常见，可加水    |
| EFB (增强富液)        | 14.4–14.8V                | 13.6–13.8V   | 很少用                 | 启停车用，耐循环   |
| SLD (密封富液，类似普通密封) | 14.4–14.8V                | 13.6–13.8V   | 很少用                 | 部分称呼普通密封铅酸 |
| AGM (密封阀控)        | 14.4–14.7V (部分14.7–14.8V) | 13.6–13.8V   | 14.6–15.0V (很少)     | 免维护，抗震     |
| 胶体 (Gel)          | 14.1–14.4V                | 13.5–13.8V   | 一般不建议               | 耐深放，过充敏感   |

#### 充电

| byGemini @25°C   | 吸收电压 (Absorption) | 浮充电压 (Float)  | 最大充电电流 (Max Current) | 备注                      |
| ---------------- | ----------------- | ------------- | -------------------- | ----------------------- |
| **FLOODED (富液)** | 14.4V - 14.8V     | 13.2V - 13.5V | 0.1C - 0.2C          | 需定期补水，耐过充性较好            |
| **AGM (贫液)**     | 14.4V - 14.7V     | 13.5V - 13.8V | 0.2C - 0.3C          | 充电速度快，内阻低，对高电压敏感        |
| **EFB (增强富液)**   | 14.4V - 14.6V     | 13.5V - 13.8V | 0.2C - 0.25C         | 启动停止系统常用，循环寿命优于普通富液     |
| **SLD (密封免维护)**  | 14.4V - 14.6V     | 13.5V - 13.8V | 0.1C - 0.25C         | 介于普通富液和AGM之间的密封设计       |
| **GEL (胶体)**     | 14.1V - 14.4V     | 13.5V - 13.8V | 0.1C - 0.2C          | **严禁高压**，否则易产生气泡导致电解质失水 |

1. 恒流阶段 (Bulk / Constant Current)

* **电流：** 此时充电器输出其能提供的**最大电流**（通常建议在 到 之间，例如 100Ah 电池使用 10A-20A 电流）。
* **目标：** 将电池电量快速补充到约 80%。
* **注意：** AGM 电池由于内阻极低，可以承受比 GEL 更大的初始电流而不至于过热。

2. 恒压阶段 (Absorption / Constant Voltage)

* **电压：** 保持在上述表格中的“吸收电压”。
* **电流：** 随着电池电量增加，其内阻增大，**电流会逐渐下降**。
* **结束条件：** 当电流下降到电池容量的 1% - 3%（例如 100Ah 电池电流降至 1A-3A）时，充电器应转入浮充阶段。

3. 浮充阶段 (Float)

* **电压：** 维持在较低的“浮充电压”，抵消电池的自放电。
* **电流：** **极小**，通常仅维持在数百毫安（mA）级别。
* **意义：** 此阶段可以无限期维持，以确保电池随时处于满电状态，同时防止电解液析气（水分解）。

#### Repair

| byBing                    | 是否可用于铅酸电池    | 原因                  |
| ------------------------- | ------------ | ------------------- |
| **蒸馏水（Distilled Water）**  | ✔️ 推荐        | 纯度高、无离子、无矿物质，不会损伤极板 |
| **去离子水（Deionized Water）** | ✔️ 可用（质量好的）  | 去除了大部分离子，纯度接近蒸馏水    |
| **超纯水（Ultrapure Water）**  | ✔️ 最佳        | 实验室级别，电阻率高，非常纯净     |
| **纯净水（Purified Water）**   | ⚠️ 勉强可用（不推荐） | 仍含少量矿物质，长期可能导致自放电   |

byGemini:

通过比重（Specific Gravity）来修复铅酸电池，本质上是针对**电解液分层**和**轻度硫化**的一种化学诊断与干预手段。

| 比重读数 (25°C)       | 电池状态      | 建议操作        |
| ----------------- | --------- | ----------- |
| **1.265 - 1.285** | 满电且健康     | 无需干预        |
| **1.200 - 1.240** | 电量不足或轻度硫化 | 尝试均衡充电      |
| **低于 1.100**      | 严重深度放电    | 尝试脱硫充电      |
| **单格间差异 > 0.05**  | 某个单格失效    | 可能存在内部短路或损坏 |

基于比重的修复步骤

**第一步：均衡充电 (Equalization)**

在尝试调整电解液之前，**必须先进行均衡充电**。

* **原理：** 很多时候比重低是因为硫酸根被“锁”在极板上（硫化）。通过高电压（15.5V - 16V）小电流充电，强行将硫酸根赶回电解液中。
* **现象：** 电解液会产生大量气泡（电解水），这能起到搅拌作用，消除电解液分层。
* **结果：** 充电结束后静置几小时再次测量。如果比重回升到 1.26 以上，说明修复成功。

**第二步：调整电解液浓度（“调酸”）**

如果经过多次均衡充电，比重依然偏低且不再上升，说明部分酸液已损耗或被永久锁定。

1. **吸出部分旧液：** 使用吸管从比重低的单格中吸出约 1/4 的液体。
2. **补充高比重酸液：** 加入比重为 1.300 的储备电解液。
3. **混合：** 继续充电 1-2 小时，利用气泡促进混合。
4. **循环测试：** 测量比重，重复上述步骤直到各单格比重均匀。

**第三步：补水（针对比重过高）**

如果比重**超过 1.300**，说明电解液中水分蒸发过多。

***

核心注意事项

* **温补修正：** 温度每升高 1°C，读数需加 0.0007；每降低 1°C，减 0.0007。
* **酸碱中和：** 操作时备好苏打水（碳酸氢钠溶液）。若强酸溅到皮肤，冲洗并中和。
* 如果单格比重完全不随充电改变，或者液体浑浊（极板活性物质脱落），说明电池物理寿命已尽，修复无效。
* 如果比重调整后容量提升不明显，可以配合使用**脉冲修复仪**，利用高频脉冲震碎极板上的坚硬硫酸铅结晶。

### Ni

<https://en.wikipedia.org/wiki/Nickel%E2%80%93metal\\_hydride\\_battery>

* starting voltage 1.4V
* NiMH(镍氢) batteries have replaced NiCd(镍镉)

### Li

<https://en.wikipedia.org/wiki/Comparison\\_of\\_commercial\\_battery\\_types>

| Name             | Discharge | V               |
| ---------------- | --------- | --------------- |
| ICR LiCoO2 钴酸锂   | 1-2C      | 2.5 / 3.7 / 4.2 |
| INR 三元锂          | 5-7C      | 2.5 / 3.6 / 4.2 |
| IMR LiMn2O4 锰酸锂  | 10-15C    | 2.5 / 3.9 / 4.2 |
| IFR LiFePO4 磷酸铁锂 | 25-35C    | 2 / 3.2 / 3.65  |

## DC UPS

| Type      | Vendor   | Power      | Link                                                  |
| --------- | -------- | ---------- | ----------------------------------------------------- |
| Pb/Li     | MeanWell | 120W\~600W | <https://www.meanwell.com/newsInfo.aspx?c=1\\&i=1106> |
| Li/Pb     | sw open  | 60W+       | <https://github.com/mini-box/ups>                     |
| Li 2S LED | hw open  | 60W        | <https://github.com/TobleMiner/DC-UPS>                |


# boost

* [MT3608](#mt3608)

[More](/elec#buck--boost)

| Chips  | Input  | Output | Current | Leakage Current       | mΩ |
| ------ | ------ | ------ | ------- | --------------------- | -- |
| MT3608 | 2 - 24 | 28     | 2A      | Shutdown = 0.1 - 1 µA | 80 |

## MT3608

6-pin SOT-23 | <https://www.olimex.com/Products/Breadboarding/BB-PWR-3608/resources/MT3608.pdf>

* 5/1/2 = In/Out/Gnd | 6 = NC
  * Out = Ref(0.6V) \* ( 1 + R1 / R2 )
* 4 EN | -0.3V to 26V
* 3 FB | -0.3V to 6V


# bulk

* [LM2596](#lm2596)
* [AMS1117](#ams1117)

[More](/elec#buck--boost)

| Chips   | Input                  | Output      | Current | Leakage Current | mΩ |
| ------- | ---------------------- | ----------- | ------- | --------------- | -- |
| LM2596  | 4.5 - 40               | 1.2 - 37    | 3A      | < 50 µA         |    |
| AMS1117 | 18 / max 30 / drop 1.3 | 1.25 to 12V | 1.4A    | Standby = 2mA   |    |

## LM2596

5-Pin TO-220/263 | <https://www.ti.com/lit/ds/symlink/lm2596.pdf>

* 1/2/3 = In/Out/Gnd
  * Out = Ref(1.23V) \* ( 1 + R2 / R1 )
* 4: FB | –0.3 to 25 V
* 5: ON = low < 1.3V | OFF = cmax 25V

## AMS1117

3-Pin SOT-223: <https://datasheet.lcsc.com/szlcsc/2001081204\\_Shikues-AMS1117-1-2\\_C475600.pdf>

* 3/2: In/Out
* 1: Gnd or ADJ ( Vout=1.25×(1+R2/R1)+IAdj×R2 , can ignore IAdj )


# cam

* [ESP32](#esp32)
* [Sony](#sony)
* [DJI](#dji)
  * [Drone](#drone)

## ESP32

<https://github.com/espressif/esp32-camera/blob/master/README.md#supported-sensor>

| model  | max resolution | color type | output format                                                                                | Len Size |
| ------ | -------------- | ---------- | -------------------------------------------------------------------------------------------- | -------- |
| OV2640 | 1600 x 1200    | color      | <p>YUV(422/420)/YCbCr422<br>RGB565/555<br>8-bit compressed data<br>8/10-bit Raw RGB data</p> | 1/4"     |

## Sony

| Feature                    | IMX323                        | IMX335                           | IMX415                           | IMX678                                         |
| -------------------------- | ----------------------------- | -------------------------------- | -------------------------------- | ---------------------------------------------- |
| **Technology**             | Exmor (Older BSI)             | STARVIS                          | STARVIS (Stacked)                | STARVIS 2 (Stacked)                            |
| **Max. Resolution**        | Approx. 2.1MP (1080p/Full HD) | Approx. 5.1MP (5MP/2.5K)         | Approx. 8.4MP (4K/UHD)           | Approx. 8.4MP (4K/UHD)                         |
| **Sensor Size (Diagonal)** | Type $1/2.9"$                 | Type $1/2.8"$ ($6.52 \text{mm}$) | Type $1/2.8"$ ($6.43 \text{mm}$) | Type $1/1.8"$ (Larger)                         |
| **Pixel Size**             | $\sim 2.8 \mu \text{m}$       | $2.0 \mu \text{m}$               | $1.45 \mu \text{m}$              | $2.0 \mu \text{m}$ (Often larger than IMX415)  |
| **Dynamic Range (HDR)**    | Basic/Limited                 | DOL-HDR                          | DOL-HDR                          | Enhanced/Superior (DOL HDR, Clear HDR support) |

* **IMX678** uses **STARVIS 2**, the successor to STARVIS, which offers superior low-light performance, much higher dynamic range, and better motion clarity
* The **IMX415** is competent but is often overshadowed by the IMX335 in pure low-light sensitivity due to its smaller pixel pitch

## DJI

### Drone

| inch   | type | 视角  | 等效焦距  | 光圈       | 对焦点   | 变焦     | Model         |
| ------ | ---- | --- | ----- | -------- | ----- | ------ | ------------- |
| 1/0.75 | 哈苏   | 72° | 28mm  | f/2.0-11 | 2m+   | 1-2.5倍 | Mavic4P       |
| 1/1    | 广角   | 84° | 24mm  | f/1.8    | 0.5m+ | 1-2.9倍 | Mini5P/Air3S  |
| 1/1.3  | 中长焦  | 35° | 70mm  | f/2.8    | 3m+   | 3-9倍   | Air3S/Mavic4P |
| 1/1.5  | 长焦   | 15° | 168mm | f/2.8    | 3m+   | 6-24倍  | Mavic4P       |


# LCEDA

* license export | <https://lceda.cn/page/desktop-client-activation>
* win/linux/mac | <https://lceda.cn/page/download> | app + guide
* doc | <https://prodocs.lceda.cn/cn/device/file-new-device/>
* video | <https://space.bilibili.com/430536057/lists/253096>
* OSS | <https://oshwhub.com/>


# esptool

```
uv pip install esptool

esptool --chip esp32c3 --port COM4 chip_id

    esptool.py v4.8.1
    Serial port COM4
    Connecting....
    Chip is ESP32-C3 (QFN32) (revision v0.4)
    Features: WiFi, BLE, Embedded Flash 4MB (XMC)
    Crystal is 40MHz
    MAC: dc:06:75:aa:6e:e8

    Uploading stub...
    Running stub...
    Stub running...

    Warning: ESP32-C3 has no Chip ID. Reading MAC instead.
    MAC: dc:06:75:aa:6e:e8
    Hard resetting via RTS pin...

esptool --chip esp32c3 --port COM4 flash_id

    Manufacturer: 20
    Device: 4016
    Detected flash size: 4MB

esptool --chip esp32c3 --port COM4 erase_flash

    Erasing flash (this may take a while)...
    Chip erase completed successfully in 17.0s

D:\天问Block>pyboard\esptool.exe --chip esp32c3 --baud 1500000 --port COM4 write_flash -z --erase-all 0x00 esp32c3.bin

    Compressed 4194304 bytes to 1491998...
    Wrote 4194304 bytes (1491998 compressed) at 0x00000000 in 52.4 seconds (effective 640.7 kbit/s)...
    Hash of data verified.

```


# home-assistant

* [Install](#install)
* [Home Assistant Community Store (HACS)](#home-assistant-community-store-hacs)
* [ha\_xiaomi\_home](#ha_xiaomi_home)

## Install

qcow2: <https://www.home-assistant.io/installation/alternative>

## Home Assistant Community Store (HACS)

* 2024.4.1 or newer
* web: /hassio/store : `Get HACS`
* cli: `ls /root/homeassistant/custom_components` <https://www.hacs.xyz/docs/use/repositories/dashboard/>

## ha\_xiaomi\_home

<https://github.com/XiaoMi/ha\\_xiaomi\\_home?tab=readme-ov-file#method-2-hacs>


# metal

* [AWG](#awg)
  * [多股硅胶线](#多股硅胶线)
* [密度](#密度)
* [电阻率](#电阻率)
* [镀层](#镀层)

## AWG

| byGemini | Diameter (inches) | Diameter (mm) | Area | Resistance (Ohms/km) | Typical Max Ampacity\* |
| -------- | ----------------- | ------------- | ---- | -------------------- | ---------------------- |
| **1**    | 0.289             | 7.35          | 42.4 | 0.407                | 110A - 130A            |
| **2**    | 0.258             | 6.54          | 33.6 | 0.513                | 95A - 115A             |
| **4**    | 0.204             | 5.19          | 21.2 | 0.815                | 70A - 85A              |
| **6**    | 0.162             | 4.11          | 13.3 | 1.30                 | 55A - 65A              |
| **8**    | 0.128             | 3.26          | 8.37 | 2.06                 | 40A - 50A              |
| **10**   | 0.102             | 2.59          | 5.26 | 3.28                 | 30A                    |
| **12**   | 0.081             | 2.05          | 3.31 | 5.21                 | 20A                    |
| **14**   | 0.064             | 1.63          | 2.08 | 8.29                 | 15A                    |
| **16**   | 0.051             | 1.29          | 1.31 | 13.2                 | 10A - 13A              |
| **18**   | 0.040             | 1.02          | 0.82 | 21.0                 | 7A - 10A               |
| **20**   | 0.032             | 0.81          | 0.52 | 33.3                 | 5A                     |
| **22**   | 0.025             | 0.64          | 0.33 | 53.0                 | 3A - 5A                |
| **24**   | 0.020             | 0.51          | 0.21 | 84.2                 | 2A - 3.5A              |
| **26**   | 0.016             | 0.40          | 0.13 | 134.0                | 1A - 2.2A              |
| **28**   | 0.013             | 0.32          | 0.08 | 213.0                | 0.5A - 1.4A            |
| **30**   | 0.010             | 0.25          | 0.05 | 339.0                | 0.5A - 0.8A            |

* "3-Gauge" Rule: doubles the cross-sectional area
* "6-Gauge" Rule: doubles the wire diameter

### 多股硅胶线

| byGrok | mm²        | 股数×单股直径 (约)         | 外径 (mm) 约 | 最大A | 40℃额定A  |
| ------ | ---------- | ------------------- | --------- | --- | ------- |
| 26     | 0.14       | 7×0.16 或 30×0.08    | 1.8–2.2   | 3.5 | 2.5–3.0 |
| 24     | 0.22       | 7×0.20 或 40×0.08    | 2.0–2.5   | 5.5 | 4.0–4.5 |
| 22     | 0.35       | 7×0.25 或 65×0.08    | 2.3–2.8   | 8.0 | 6.0–7.0 |
| 20     | 0.5        | 7×0.30 或 100×0.08   | 2.6–3.2   | 11  | 8–9     |
| 18     | 0.75       | 19×0.23 或 150×0.08  | 3.0–3.8   | 16  | 12–14   |
| 16     | 1.0 / 1.3  | 19×0.30 或 196×0.08  | 3.4–4.2   | 22  | 17–20   |
| 14     | 2.0 / 2.08 | 41×0.25 或 324×0.08  | 4.2–5.0   | 32  | 25–28   |
| 12     | 3.3 / 3.31 | 65×0.25 或 513×0.08  | 5.0–6.0   | 41  | 33–38   |
| 10     | 5.26       | 105×0.25 或 826×0.08 | 6.0–7.2   | 55  | 45–50   |
| 8      | 8.37       | 168×0.25            | 7.5–8.5   | 80  | 65–70   |
| 6      | 13.3       | 266×0.25            | 9.0–10.5  | 105 | 85–95   |

## 密度

<https://en.wikipedia.org/wiki/Densities\\_of\\_the\\_elements\\_(data\\_page)#Density,\\_solid\\_phase>

```
13 Al aluminium 2.70 g/cm3
26 Fe iron      6.98 g/cm3
29 Cu copper    8.02 g/cm3
47 Ag silver    9.32 g/cm3
82 Pb lead     11.34 g/cm3
79 Au gold     19.3  g/cm3
```

## 电阻率

<https://zh.wikipedia.org/wiki/%E7%94%B5%E9%98%BB%E7%8E%87>

| 物质  | 电阻率 (Ωm)  |
| --- | --------- |
| 石墨烯 | 1.00×10−8 |
| 银   | 1.59×10−8 |
| 铜   | 1.7×10−8  |
| 金   | 2.44×10−8 |
| 铝   | 2.82×10−8 |
| 黄铜  | 8×10−8    |
| 铁   | 10×10−8   |

<http://www.elektrisola.com/cn/conductor-materials/comparison-of-metals.html\\>
![](https://pic3.zhimg.com/v2-c62dd9e9abb89511164888df8e558b3a_r.jpg)

## 镀层

<https://www.zhihu.com/question/57329327>

```
接线应采用相同的表面处理，铜镀锡与铜镀银接触，锡面会被氧化腐蚀。
活泼: 锡>铜>银
镀镍：不生铜锈
银：价贵；易氧化，在电场的作用下容易迁移
要求严格的地方，触点用铂或者铼合金
```


# sensor\_env

* [TI/LM\*](#tilm)
* [ADI](#adi)
  * [DS18B20](#ds18b20)
* [aosong/ASAIR](#aosongasair)
  * [AHT25 vs DHT20 Sensor Comparison](#aht25-vs-dht20-sensor-comparison)
  * [AHT](#aht)

## TI/LM\*

* chart compare: <https://www.ti.com/product-category/sensors/temperature/analog/overview.html>
* table filter: <https://www.ti.com/product-category/sensors/temperature/analog/products.html>

## ADI

* Analog | <https://www.analog.com/en/parametricsearch/2772#/>
* Digital | <https://www.analog.com/en/parametricsearch/2750#/>

### DS18B20

<https://www.analog.com/media/en/technical-documentation/data-sheets/ds18b20.pdf>

\| by Grok | DS18B20 (Temperature Only) | DHT20 (Temperature + Humidity) | |----------------- -------|--------------------------------------------|---------------------------------------------| | **Interface** | 1-Wire (multi-sensor support) | I²C (single address) | | **Temperature Range** | -55°C to +125°C | -40°C to +85°C | | **Temperature Accuracy**| ±0.5°C (from -10°C to +85°C) | ±0.3°C (at 25°C) |

**Notes**: DS18B20 excels in precision temp monitoring (e.g., liquids)

## aosong/ASAIR

<https://www.aosong.com/Products/list.aspx?lcid=1>

### AHT25 vs DHT20 Sensor Comparison

DHT22 = AM2302 | 3.3-6V

### AHT

| by bing                  | AHT10          | AHT20(Gen 2)       | AHT21              |
| ------------------------ | -------------- | ------------------ | ------------------ |
| **Temperature Range**    | -40°C to +85°C | -40°C to +85°C     | -40°C to +120°C    |
| **Temperature Accuracy** | ±0.3°C typical | ±0.3°C typical     | ±0.3°C typical     |
| **Humidity Accuracy**    | ±2% RH typical | ±2% RH typical     | ±2% RH typical     |
| **Voltage Range**        | 1.8V – 3.6V    | 2.0V – 5.5V        | 2.0V – 5.5V        |
| **Current Consumption**  | \~400 µA       | \~980 µA (typical) | \~980 µA (typical) |


# simulator

* [Simulation Program](#simulation-program)
* [Falstad - HTML5/JAVA](#falstad---html5java)
* [Qucs-S - Qt](#qucs-s---qt)
* [Micro-Cap - Windows](#micro-cap---windows)

## Simulation Program

Free: <https://en.wikipedia.org/wiki/List\\_of\\_free\\_electronics\\_circuit\\_simulators>

Non-free: Multisim/Matlab

## Falstad - HTML5/JAVA

<http://lushprojects.com/circuitjs/>

* Full Screen: <https://www.falstad.com/circuit/circuitjs.html>
  * Options -> Other Options... -> `Change Language`
* win/linux/Mac: <https://www.falstad.com/circuit/offline/>

## Qucs-S - Qt

SPICE circuit simulation kernels with Qt GUI: <https://ra3xdh.github.io/>

## Micro-Cap - Windows

25/1080p: <https://www.youtube.com/watch?v=WExvpASP-1c\\&list=PLZ0\\_iMoMBSslK1NFAXIEBsTnFzP8u9BGH>

Switches: <https://www.youtube.com/watch?v=oCrtZO9c-hw>

25/720p: <https://www.youtube.com/watch?v=gvTqw3peBsY\\&list=PLWR39YMcPJodL5TXQ4c0GlS4oskR7gacV\\>
9/720p: <https://www.youtube.com/channel/UCAFaRNJVEvMz5hIVKwbeCeA/videos?view=0\\&sort=da\\&flow=grid>


# hw

* [CPU](#cpu)
* [Endianness](#endianness)
* [Protection ring](#protection-ring)
* [UEFI Shell](#uefi-shell)
* [Buses](#buses)
* [Infini Band](#infini-band)
* [Raspberry PI](#raspberry-pi)
  * [Console](#console)
* [Resolution](#resolution)
* [Screen](#screen)

## CPU

CPUID to arch: <https://github.com/mer-tools/oprofile/blob/master/libop/op\\_hw\\_specific.h#L119\\>
CPU flags meaning: <http://unix.stackexchange.com/questions/43539/what-do-the-flags-in-proc-cpuinfo-mean>

## Endianness

<https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html\\>
In big endian, you store the most significant byte(MSB) in the smallest address.\
In little endian, you store the least significant byte(LSB) in the smallest address

## Protection ring

![](https://en.wikipedia.org/wiki/File:Priv_rings.svg)

## UEFI Shell

<https://software.intel.com/en-us/articles/uefi-shell>

```
map # list disks
help bcfg
```

## Buses

VESA (Video Electronics Standards Association)

<https://en.wikipedia.org/wiki/List\\_of\\_device\\_bit\\_rates>

|Technology|Rate||Year| |---|---|---| |ISA 16-Bit/8.33 MHz|66.7 Mbit/s|8.33 MB/s|1984 (created)| |I²C|3.4 Mbit/s|425 kB/s|1992 (standardized)| |Low Pin Count|125 Mbit/s|15.63 MB/s \[x]|2002| |HyperTransport 3.1 (3.2 GHz, 32-pair)|409.6 Gbit/s|51.2 GB/s|2008| |Unified Media Interface 2.0 (UMI 2.0; ×4 link)|20 Gbit/s|2 GB/s \[z]|2012| |Direct Media Interface 3.0 (DMI 3.0; ×4 link)|40 Gbit/s|4 GB/s \[z]|2015| |AGP 8×|17.066 Gbit/s|2.133 GB/s|2002| |AGP 8× 64-bit|34.133 Gbit/s|4.266 GB/s|| |PCI 32-bit/66 MHz|2.133 Gbit/s|266.7 MB/s|1995| |PCI 64-bit/100 MHz|6.4 Gbit/s|800 MB/s|| |PCI-X QDR|34.133 Gbit/s|4.266 GB/s|| |PCI Express 2.0 (×32 link)\[43]|160 Gbit/s|16 GB/s \[z]|2007| |PCI Express 3.0 (×32 link)\[44]|256 Gbit/s|31.51 GB/s \[y]|2011| |QPI (9.6GT/s, 4.8 GHz)|307.2 Gbit/s|38.4 GB/s|2014|

<https://en.wikipedia.org/wiki/NVLink>

## Infini Band

<https://en.wikipedia.org/wiki/InfiniBand>

|                                                   | SDR       | DDR  | QDR  | FDR10   | FDR         | EDR      | HDR      | NDR        | XDR    |
| ------------------------------------------------- | --------- | ---- | ---- | ------- | ----------- | -------- | -------- | ---------- | ------ |
| Signaling rate (Gbit/s)                           | 2.5       | 5    | 10   | 10.3125 | 14.0625\[6] | 25.78125 | 50       | 100        | 250    |
| Theoretical effective throughput, Gbs, per 1x\[7] | 2         | 4    | 8    | 10      | 13.64       | 25       | 50       |            |        |
| Speeds for 12x links (Gbit/s)                     | 24        | 48   | 96   | 120     | 163.64      | 300      | 600      |            |        |
| Encoding (bits)                                   | 8/10      | 8/10 | 8/10 | 64/66   | 64/66       | 64/66    | 64/66    |            |        |
| Adapter latency (microseconds)\[8]                | 5         | 2.5  | 1.3  | 0.7     | 0.7         | 0.5      |          |            |        |
| Year\[9]                                          | 2001,2003 | 2005 | 2007 | 2011    | 2011        | 2014\[7] | 2017\[7] | after 2020 | future |

## Raspberry PI

```
/opt/vc/bin/vcgencmd measure_temp
```

### Console

/dev/ttyAMA0

```
Speed (baud rate): 115200
Bits: 8
Parity: None
Stop Bits: 1
Flow Control: None
```

## Resolution

```
SQCIF = 128x96
QCIF = 176x144
QVGA = 320x240
CIF = 352x240/288
HVGA = 640x240
VGA = 640x480
2 CIF = 704x240/288
4 CIF = 704x480/576
D1 CROPPED = 704x480/576
D1 = 720x480/576

D1 (525) 720 x 480 is in NTSC
D1 (625) 720 x 576 is in PAL

720p is 1280 x 720. (921,600 total pixels)
1080p is 1920x1080. (2,073,600 total pixels)
3MP is 2048 x 1536. (3,145,728 total pixels)
5MP is 2560 x 1920. (4,915,200 total pixels)
```

## Screen

| Name                              | Wiki                                                         |
| --------------------------------- | ------------------------------------------------------------ |
| OLED                              | <https://en.wikipedia.org/wiki/OLED>                         |
| microLED, micro-LED, mLED or μLED | <https://en.wikipedia.org/wiki/MicroLED>                     |
| Mini LED                          | <https://en.wikipedia.org/wiki/LED-backlit\\_LCD#Mini\\_LED> |


# GPU

* [nVidia](#nvidia)
* [AMD](#amd)

## nVidia

<https://en.wikipedia.org/wiki/List\\_of\\_Nvidia\\_graphics\\_processing\\_units>

```
28nm
    Kepler  April 2012 : GeForce 700 series
    Maxwell February 2014 : GeForce 900 series
16nm
    Pascal April 5, 2016 : GeForce 10 series
12nm	
    Turing (consumer) September 20, 2018 : GeForce 16/20 series
    Volta (workstation/datacenter)
TSMC 7 nm (Professional)
Samsung 8 nm (Consumer)
    Ampere : GeForce 30 series
```

## AMD

<https://en.wikipedia.org/wiki/List\\_of\\_AMD\\_graphics\\_processing\\_units#API\\_Overview>

OpenGL -> Vulkan

Vulkan is a low-overhead, cross-platform 3D graphics and compute API; supported since Graphics Core Next (Southern Islands) 1

```
GCN 1 - 2012/01 : Radeon HD 7000 series
GCN 2 - 2013/09 : Radeon HD 7790+
    28nm FM2+ "Kaveri" (2014) : A6-7400K A10-7890K
GCN 3 - 2014 : Radeon R9 285+
    28nm FM2+ AM4 "Carrizo" (2016) : A6-7480 A8-7680
    28nm AM4 "Bristol Ridge" (2016) : A6-9400 A10-9700
GCN 4 - 2016 : Radeon 400 series
GCN 5 - 2017 : Vega 10/12/20
    14nm AM4 "Raven Ridge" (2018) : Ryzen 3 2200GE
RDNA (Radeon DNA) - 2019
RDNA 2 - 2020

28nm    
    Radeon RX 400/500 series
```


# PCI

* [PCIe](#pcie)
  * [Check](#check)
* [Thunderbolt](#thunderbolt)
  * [Chip](#chip)
* [DisplayPort](#displayport)

## PCIe

<https://en.wikipedia.org/wiki/PCI\\_Express#History\\_and\\_revisions>

Per lane:

* Version 1.0a: 2.5 GT/s is 2.5 Gbps on the encoded serial link. This corresponds to 2.0 Gbps of pre-coded data or 250 MB/s
* Version 2.x : 5 GT/s = 500 MB/s
* Version 3.x : 8 GT/s \~= 1 GB/s | upgraded the encoding scheme to 128b/130b from the previous 8b/10b encoding
* Version 4.0 : 16 GT/s \~= 2 GB/s

split: BIOS - PCIe Bifurcation

### Check

* Powershell: <https://superuser.com/questions/1732084/is-there-a-way-to-identify-the-pcie-speed-for-a-device-using-powershell-win10>
* devmgmt.msc : Properties - Details

## Thunderbolt

<https://en.wikipedia.org/wiki/Thunderbolt\\_(interface)>

* Superseded: IEEE 1394 (FireWire) / ExpressCard
* Connector: v1/v2 - Mini-DP ; v3/v4 - USB-C
* v3/v4: 40 Gbit/s (5 GB/s) bidirectional
  * Thunderbolt 3: 4× PCI Express 3.0, DisplayPort 1.2, USB 3.1 Gen 2
  * Thunderbolt 4: 4× PCI Express 3.0, DisplayPort 2.0, USB4
* USB4 compatible with Thunderbolt 3, and backwards compatible with USB 3.2 and USB 2.0

### Chip

* Intel 6000 Series: <https://www.thunderbolttechnology.net/sites/default/files/18-241\\_ThunderboltController\\_Brief\\_HI.pdf>
  * JHL6340: 4 lanes
    * Peripherial Confiuration: 1
* Intel 7000 Series: <https://www.thunderbolttechnology.net/sites/default/files/18-241\\_Thunder7000Controller\\_Brief\\_FIN\\_HI.pdf>
  * JHL7440: 2 Ports, Downstream x4 lanes
    * Peripherial Confiuration: 2 Tunneled, 1 dedicated DP output

## DisplayPort

* 4 lanes: <https://en.wikipedia.org/wiki/DisplayPort#Specifications>
  * Thunderbolt 3 interface which implements up to 8 lanes of DisplayPort


# Bluetooth

* [Bluetooth](#bluetooth)
* [Audio Codecs](#audio-codecs)
* [Hardware](#hardware)

## Bluetooth

|Technology|Rate||Year| |---|---|---| |Bluetooth 2.0+EDR|3 Mbit/s|375 kB/s|2004| |Bluetooth 3.0|25 Mbit/s|3.125 MB/s|2009| |Bluetooth 4.0|25 Mbit/s|3.125 MB/s|2010| |Bluetooth 5.0|50 Mbit/s|6.25 MB/s|2016|

## Audio Codecs

<https://majorhifi.com/what-can-bluetooth-codecs-do-for-you-a-brief-decoding/\\>
![](https://majorhifi.com/wp-content/uploads/audio46-bluetooth-spec-chart-1.jpg)

## Hardware

Jabra Clipper - Reset: - + - + - +. Power off/on.


# ent

* [IPMI](#ipmi)
  * [Dell idrac](#dell-idrac)
* [OS](#os)
  * [IBM Advanced Interactive eXecutive(AIX)](#ibm-advanced-interactive-executiveaix)
  * [IBM i](#ibm-i)
  * [HP-UX](#hp-ux)
* [Software](#software)
  * [IBM PowerVM](#ibm-powervm)
  * [IBM PowerKVM](#ibm-powerkvm)
  * [IBM PowerHA](#ibm-powerha)
  * [IBM PowerSC](#ibm-powersc)
* [IBM Power Systems](#ibm-power-systems)
* [IBM Power S8 series servers](#ibm-power-s8-series-servers)
* [IBM PurePower System](#ibm-purepower-system)

## IPMI

### Dell idrac

virtual console: open port 443 + 5900 & java8\javaws.exe viewer.jnlp -verbose\
HKEY\_CLASSES\_ROOT\jnlp\_auto\_file\shell\open\command

```
action=powerstatus # powerdown powerup graceshutdown hardreset powercycle
ssh root@${host} "racadm serveraction ${action}"    
```

## OS

### IBM Advanced Interactive eXecutive(AIX)

<https://en.wikipedia.org/wiki/IBM\\_AIX\\>
AIX 7.2(October 5, 2015) exploits POWER8 hardware features including accelerators and eight-way hardware multithreading.\
Live update for Interim Fixes, Service Packs and Technology Levels – replaces the entire AIX kernel without impacting applications

### IBM i

runs on IBM Power Systems and on IBM PureSystems\
Version 7.3 was released in April 2016\
requiring little or no on-site attention from IT staff during normal operation

AIX programs are binary compatible with IBM i when using its PASE (Portable Applications System Environment)

### HP-UX

Latest release 11i v3 Update 16 / March 2017

## Software

### IBM PowerVM

Available on IBM Power Systems™ servers and supported by the IBM AIX®, Linux® and IBM i operating systems

<https://www.ibm.com/developerworks/community/blogs/fe313521-2e95-46f2-817d-44a4f27eba32/entry/Virtualization\\_Options\\_for\\_Power\\_Linux?lang=en\\>
PowerVM, which comes in standard and enterprise versions;\
PowerVM for PowerLinux only supports Linux and VIO Servers as guests and can run on any “L” model and is also the version provided in the Enterprise Systems IFLs. PowerVM for PowerLinux is logically equivalent to PowerVM Enterprise Edition, and includes Live Partition Mobility.

PowerVP: Secure and scalable server virtualization environment for AIX, IBM i and Linux applications\
PowerVC: Advanced virtualization management and cloud management for Power Systems

### IBM PowerKVM

<https://www.ibm.com/developerworks/community/blogs/fe313521-2e95-46f2-817d-44a4f27eba32/entry/Virtualization\\_Options\\_for\\_Power\\_Linux> only supported on the “L” models. NOT on the S824L GPU model, nor any POWER7 systems.\
PowerKVM does not support the pHyp interface, so OPAL (OpenPower Abstraction Layer), which is an alternative hardware interface, was created.\
order the system with PowerVM：get both the vet codes and machine code for PowerVM

<https://www.ibm.com/developerworks/community/wikis/form/anonymous/api/wiki/61ad9cf2-c6a3-4d2c-b779-61ff0266d32a/page/1cb956e8-4160-4bea-a956-e51490c2b920/attachment/7a905bdf-5274-43ae-b5fd-3ef5bfc81f8a/media/AIX%20VUG%20-%20PowerKVM%20Overview.pdf>

### IBM PowerHA

<https://www-03.ibm.com/systems/power/software/availability/> Resiliency for AIX, Linux and IBM i

### IBM PowerSC

Simplify security management and compliance measurement

## IBM Power Systems

previous generation: IBM System i

S821LC / S822LC Runs Ubuntu, SUSE and Red Hat Linux PowerVM and PowerKVM virtualization options

IBM Power S822, ESS, S812L, S822L and S824L Configurable into highly scalable Linux clusters

E850C, E870C and E880C cloud models • Runs AIX, IBM i and Linux

## IBM Power S8 series servers

for mid-size business. Supports Linux, UNIX, and IBM i workloads

## IBM PurePower System

Based on open standards


# pinout

* [RS232](#rs232)
* [RS485](#rs485)
* [USB3](#usb3)
  * [Type-C](#type-c)
* [PCI-E](#pci-e)
* [HMDI](#hmdi)
  * [19 Pins](#19-pins)
* [Channel](#channel)
* [DVI/HMDI](#dvihmdi)

## I2C

<https://en.wikipedia.org/wiki/I%C2%B2C>

* differential driver: 20-100m

  VCC - 3V–5V GND - GND SDA - Data SCL - Clock

## RS232

[RS232簡單接法(3線)](http://flykof.pixnet.net/blog/post/24074586-rs232%E7%B0%A1%E5%96%AE%E6%8E%A5%E6%B3%95\(3%E7%B7%9A\))\
![](https://pic.pimg.tw/flykof/4a729ba808337.jpg)

## RS485

Line Termination Resistor Calculator: <http://www.alciro.org/tools/RS-485/RS485-resistor-termination-calculator.jsp>

## USB3

VBUS/GND: shared by USB2/3; D-/D+: USB2 only.

![](https://imgur.com/Z8covNr.png)\
<https://en.wikipedia.org/wiki/USB\\_3.0>

![](https://upload.wikimedia.org/wikipedia/commons/8/82/USB_2.0_and_3.0_connectors.svg)

### Type-C

* Receptacles: 12+12 Pins
* Plugs: 12+10 Pins: B6/7 n/a & CC2 -> VCONN

| Pin    | Name            | Description                                         |
| ------ | --------------- | --------------------------------------------------- |
| A1/B12 | GND             | Ground return                                       |
| A2     | SSTXp1 ("TX1+") | SuperSpeed differential pair #1, transmit, positive |
| A3     | SSTXn1 ("TX1−") | SuperSpeed differential pair #1, transmit, negative |
| A4     | VBUS            | Bus power                                           |
| A5     | CC1             | Configuration channel                               |
| A6     | D+              | USB 2.0 differential pair, position 1, positive     |
| A7     | D−              | USB 2.0 differential pair, position 1, negative     |
| A8     | SBU1            | Sideband use (SBU)                                  |
| A9     | VBUS            | Bus power                                           |
| A10    | SSRXn2 ("RX2−") | SuperSpeed differential pair #4, receive, negative  |
| A11    | SSRXp2 ("RX2+") | SuperSpeed differential pair #4, receive, positive  |
| A12    | GND             | Ground return                                       |

## PCI-E

<https://en.wikipedia.org/wiki/PCI\\_Express#Pinout>

```
side A: PRSNT1# shorter than the rest | side B: component side
×1/4/8/16 cards end at pin 18/32/49/82  
+12 V power: 75 W (6-pin) or 150 W (8-pin) | 300 W total (2 × 75 W + 1 × 150 W)
```

![](https://imgur.com/u3rUvyL)

## HDMI

<https://en.wikipedia.org/wiki/HDMI>

| Type | Name       | -       |
| ---- | ---------- | ------- |
| A    | Std        |         |
| C    | Mini       |         |
| D    | Micro      |         |
| E    | Automotive | locking |

### 19 Pins

```
Pin 17	Ground for ARC, CEC, DDC and HEC
Pin 18	+5 V (up to 50 mA)

Pin 1	TMDS data 2 (+)
Pin 2	TMDS data 2 ground
Pin 3	TMDS data 2 (−)

Pin 4	TMDS data 1 (+)
Pin 5	TMDS data 1 ground
Pin 6	TMDS data 1 (−)

Pin 7	TMDS data 0 (+)
Pin 8	TMDS data 0 ground
Pin 9	TMDS data 0 (−)

Pin 10	TMDS clock (+)
Pin 11	TMDS clock ground
Pin 12	TMDS clock (−)

Pin 15	SCL (I2C clock for DDC)
Pin 16	SDA (I2C data for DDC)

Pin 13	CEC / Consumer Electronic Control

Pin 14
        HDMI 1.0–1.3a: Unused
        HDMI 1.4+: ARC (+) or HEC (+)
Pin 19
        All versions: Hot plug detect
        HDMI 1.4+: ARC (−) or HEC (−)
```

## Channel

* Audio Return Channel (ARC): supports stereo PCM
* HDMI Ethernet Channel (HEC): IP-based @ 100 Mbit/s

## DVI/HMDI

DVI: <http://www.alciro.org/alciro/conectores\\_26/conector-DVI-interfaz-visual-digital\\_269\\_en.htm>

```
C1	Red analog	
C2	Green analog	
C3	Blue analog	
C4	Analog horizontal sync	
C5	Ground (analog)	Return for analog signals
```

HDMI to DVI-D: <http://www.alciro.org/alciro/conectores\\_26/patillas-cable-HDMI-a-DVI-D\\_274\\_en.htm>


# x86\_AMD

* [Chipset](#chipset)
* [APU](#apu)
* [CPU](#cpu)

## Chipset

<https://www.amd.com/en/products/chipsets-am4>

* B550: PCIe® 4.0 Ready for AMD Ryzen™ processors

<https://en.wikipedia.org/wiki/Socket\\_AM4>

## APU

Accelerated Processing Unit (APU): AMD processors with 3D graphics

* <https://en.wikipedia.org/wiki/RDNA\\_2#Integrated\\_graphics\\_processors\\_(iGPs)>

## CPU

| Generation | Sockets | Desktop   | APUs   | Mobile | Release date |
| ---------- | ------- | --------- | ------ | ------ | ------------ |
| Zen 2      | 7nm/AM4 | 3100/4500 | 4300G  | 4300U  | 2019/2020    |
| Zen 3      | 7nm/AM4 | 5500      | 5300GE | 5400U  | 2020         |
| Zen 3+     | 6nm     | -         | -      | 6600U  | 2022         |
| Zen 4      | 5nm/AM5 | 7600      | any?   | 7440U  | 2023         |


# x86\_intel

* [CPU](#cpu)
* [CPU and Chipset](#cpu-and-chipset)
* [Chipset](#chipset)
  * [Gen 12](#gen-12)
  * [Gen 11](#gen-11)
* [NUC](#nuc)
  * [NUC11](#nuc11)
* [Notebook](#notebook)
  * [Thinkpad X](#thinkpad-x)

## CPU

| nm | CPU       | Cores | Base    | Turbo   | TDP    | Single Thread | Average Mark |
| -- | --------- | ----- | ------- | ------- | ------ | ------------- | ------------ |
| 14 | J4125     | 4C4T  | 2.0 GHz | 2.7 GHz | 10 W   | 1167          | 2982         |
| 10 | 7505      | 2C4T  | 2.0 GHz | 3.5 GHz | 15 W   | 2308          | 5281         |
| 10 | i3-1115G4 | 2C4T  | 3.0 GHz | 4.1 GHz | 12-28W | 2673          | 6193         |
| 10 | i5-1135G7 | 4C8T  | 2.4 GHz | 4.2 GHz | 12-28W | 2716          | 9989         |
| 10 | i7-1165G7 | 4C8T  | 2.8 GHz | 4.7 GHz | 12-28W | 2851          | 10429        |
| 10 | i3-N305   | 8C8T  | 3.8 GHz | 9-15W   | 2296   | 10512         |              |

## CPU and Chipset

> Below tables generated by Goolge Bard

| Year | CPU Gen  | CPU Codename        | Chipset                                |
| ---- | -------- | ------------------- | -------------------------------------- |
| 2022 | 13th Gen | Raptor Lake         | Z790, H770, B760, H710                 |
| 2021 | 12th Gen | Alder Lake          | Z690, H670, B660, H610                 |
| 2020 | 11th Gen | Tiger Lake          | Z590, H570, B560, H510                 |
| 2019 | 10th Gen | Comet Lake          | Z490, H470, B460, H410                 |
| 2018 | 9th Gen  | Coffee Lake Refresh | Z390, H370, B365, H310                 |
| 2017 | 8th Gen  | Coffee Lake         | Z370, H370, B360, H310                 |
| 2016 | 7th Gen  | Kaby Lake           | Z270, H270, Q270, B250, H210           |
| 2015 | 6th Gen  | Skylake             | Z170, H170, Q170, B150, H110           |
| 2014 | 5th Gen  | Broadwell           | Z97, H97, Q97, B85, H81                |
| 2013 | 4th Gen  | Haswell             | Z87, H87, Q87, B85, H81                |
| 2012 | 3rd Gen  | Ivy Bridge          | Z77, H77, P75, P77, Z75, Z77, Q75, Q77 |
| 2011 | 2nd Gen  | Sandy Bridge        | P67, H67, P67, H67, Z68, Z68           |
| 2010 | 1st Gen  | Nehalem             | X58, P55, H55, H57                     |

## Chipset

### Gen 12

| Feature               | Z690                                      | H670                   | B660                                | H610                     |
| --------------------- | ----------------------------------------- | ---------------------- | ----------------------------------- | ------------------------ |
| Socket                | LGA 1700                                  | LGA 1700               | LGA 1700                            | LGA 1700                 |
| CPU support           | 12th Gen Core i9/i7/i5/i3/Pentium/Celeron | 12th Gen Core i9/i7/i5 | 12th Gen Core i5/i3/Pentium/Celeron | 12th Gen Pentium/Celeron |
| PCIe 5.0 lanes        | 20                                        | 16                     | 8                                   | 4                        |
| DDR5 memory support   | Up to 64GB @ 6400 MT/s                    | Up to 64GB @ 6000 MT/s | Up to 64GB @ 5000 MT/s              | Up to 32GB @ 4800 MT/s   |
| M.2 slots             | 4                                         | 3                      | 2                                   | 1                        |
| USB 3.2 Gen 2x2 ports | 2                                         | 2                      | 2                                   | 1                        |
| Thunderbolt 4 ports   | 2                                         | 2                      | 1                                   | 0                        |
| Wi-Fi 6E support      | Yes                                       | Yes                    | Yes                                 | No                       |
| LAN port              | 2.5 Gbps                                  | 2.5 Gbps               | 1 Gbps                              | 1 Gbps                   |

### Gen 11

| Feature               | Z590                                      | H570                    | B560                                | H510                     |
| --------------------- | ----------------------------------------- | ----------------------- | ----------------------------------- | ------------------------ |
| Socket                | LGA 1200                                  | LGA 1200                | LGA 1200                            | LGA 1200                 |
| CPU support           | 11th Gen Core i9/i7/i5/i3/Pentium/Celeron | 11th Gen Core i9/i7/i5  | 11th Gen Core i5/i3/Pentium/Celeron | 11th Gen Pentium/Celeron |
| PCIe 4.0 lanes        | 20                                        | 20                      | 12                                  | 8                        |
| DDR4 memory support   | Up to 128GB @ 3200 MT/s                   | Up to 128GB @ 2933 MT/s | Up to 128GB @ 2666 MT/s             | Up to 128GB @ 2666 MT/s  |
| M.2 slots             | 4                                         | 4                       | 2                                   | 2                        |
| USB 3.2 Gen 2x2 ports | 2                                         | 2                       | 2                                   | 2                        |
| Thunderbolt 4 ports   | 2                                         | 2                       | 1                                   | 0                        |
| Wi-Fi 6E support      | Yes                                       | Yes                     | Yes                                 | No                       |
| LAN port              | 2.5 Gbps                                  | 2.5 Gbps                | 1 Gbps                              | 1 Gbps                   |

## NUC

### NUC11

Multi Display: <https://www.intel.com/content/www/us/en/support/articles/000058069/intel-nuc.html>

## Notebook

### Thinkpad X

<https://en.wikipedia.org/wiki/ThinkPad\\_X\\_series>

| Year | Model  | Intel |
| ---- | ------ | ----- |
| 2018 | X280   | 7/8   |
| 2019 | X390   | 8/10  |
| 2020 | X13 G1 | 10    |
| 2023 | X13 G4 | 13    |


# linux

* [Linux Releases](#linux-releases)
* [Install](#install)
* [Download](#download)
  * [Debian](#debian)
  * [Ubuntu](#ubuntu)
* [Mirrors](#mirrors)
* [Bash](#bash)
  * [tmux](#tmux)
* [Init](#init)
  * [login & non-login shells](#login--non-login-shells)
  * [supervisord](#supervisord)
* [Exit code](#exit-code)
* [Syslog Message Severities](#syslog-message-severities)
* [Signals](#signals)
* [kill](#kill)
* [top](#top)
  * [Glances - A top/htop alternative - Python](#glances---a-tophtop-alternative---python)
* [User & Permission](#user--permission)
  * [add user to group](#add-user-to-group)
  * [rename](#rename)
  * [password](#password)
  * [sudoers](#sudoers)
  * [chown](#chown)
* [Package Management](#package-management)
  * [Redhat](#redhat)
  * [Ubuntu](#ubuntu-1)
  * [Debian](#debian-1)
    * [experimental](#experimental)
  * [dpkg](#dpkg)
  * [apt](#apt)
  * [ssh server](#ssh-server)
* [Grub](#grub)
  * [grub-customizer](#grub-customizer)
  * [boot .iso](#boot-iso)
* [boot repair](#boot-repair)
  * [ubuntu](#ubuntu-2)
* [Serial](#serial)
  * [client](#client)
* [Benchmark](#benchmark)
* [mosh](#mosh)
* [sshd](#sshd)
* [ssh redirect](#ssh-redirect)
* [web](#web)
  * [wget](#wget)
  * [curl](#curl)
* [files](#files)
  * [find](#find)
  * [grep](#grep)
  * [compress/uncompress](#compressuncompress)
  * [rsync](#rsync)
* [history without line numbers](#history-without-line-numbers)
* [hostname](#hostname)
* [font](#font)
* [SELinux](#selinux)
* [Dropbox](#dropbox)
  * [link account](#link-account)
* [Ubuntu snap](#ubuntu-snap)
  * [Proxy](#proxy)
* [JAVA\_HOME](#java_home)
* [I18N & I10N](#i18n--i10n)
* [Chrome](#chrome)
* [AD](#ad)
* [cache diagnostics](#cache-diagnostics)
* [WOL](#wol)
* [Tools - Online](#tools---online)
* [CPU](#cpu)
  * [check\_cpu\_core\_mapping](#check_cpu_core_mapping)
* [USB Persistence](#usb-persistence)
* [kali](#kali)
* [ssh](#ssh)
  * [tools](#tools)
* [Video](#video)
* [OpenCL](#opencl)
* [zFCP](#zfcp)
* [Diagram](#diagram)
* [diskless](#diskless)

## Linux Releases

[RHEL](https://access.redhat.com/articles/3078) | [Ubuntu](https://en.wikipedia.org/wiki/Ubuntu_version_history#Table_of_versions) | [Debian](https://en.wikipedia.org/wiki/Debian_version_history#Release_table)

```
6.0	Squeeze	 2.6.32  -> Security until February 2016
7	Wheezy   3.2     -> Security until May 2018
8	Jessie   3.16    -> Security until April/May 2020
9	Stretch	 4.9	 -> Security until June 2022
10	Buster   4.19    -> Security until June 2024
11	Bullseye 5.10    -> Security until June 2026
12  Bookworm 6.1     -> Security until June 2028
```

## Install

from existing: <https://www.debian.org/releases/stretch/amd64/apds03.html.en>

## Download

### Debian

<https://www.debian.org/CD/live/>

### Ubuntu

<http://ftp.sjtu.edu.cn/ubuntu-cd/>

<http://archive.ubuntu.com/ubuntu/dists/bionic-updates/main/installer-amd64/current/images/netboot/mini.iso\\>
( Mirror only <http://us.archive.ubuntu.com/> , need proxy, local DNS not working )

Debug: Console 4 or /var/log/syslog

## Mirrors

* <https://debgen.github.io/>
* <https://mirrors.tuna.tsinghua.edu.cn/help/debian/>

  apt install netselect-apt && netselect-apt -c china --nonfree mv /etc/apt/sources.list /etc/apt/sources.list.ori && mv sources.list /etc/apt/

## Bash

<https://www.gnu.org/software/bash/manual/bash.html>

```
url=https://raw.githubusercontent.com/fzinfz/scripts/master/init.sh # alias & functions
source /dev/stdin <<< "$(curl -sS $url)"

set
    -x                      debug
    -T                      If  set, any traps on DEBUG and RETURN are inherited
    -o functrace/errtrace

shopt [-pqsu] [-o] [optname …]
    -s: Enable (set) each optname.
    -u: Disable (unset) each optname.

shopt -s expand_aliases     # when the shell is not interactive
alias foo='...'

0: stdin; 1: stdout; 2: stderr              # File descriptor
2>&1 >/dev/null
&>/dev/null
ssh-add 2>/dev/null
```

<https://git.savannah.gnu.org/cgit/bash.git/>

### tmux

```
ctrl+b x -> kill pane   # /usr/share/doc/tmux/examples/screen-keys.conf
cat /usr/share/doc/tmux/examples/screen-keys.conf | grep '\bbind \w'
```

## Init

| Level | Desc                                                                   |
| ----- | ---------------------------------------------------------------------- |
| 0     | Halt the system.                                                       |
| 1     | Single-user mode (for special administration).                         |
| 2     | Local Multiuser with Networking but without network service (like NFS) |
| 3     | Full Multiuser with Networking                                         |
| 4     | Not Used                                                               |
| 5     | Full Multiuser with Networking and X Windows(GUI)                      |
| 6     | Reboot.                                                                |

```
ls -R -l /etc/rc*

ls -l /usr/lib/systemd      # check `systemd` page for more
ls -l /usr/share/upstart    # last release 2014; 3 years ago
ls -l /etc/init.d           # SysV init

cat /etc/modules-load.d/*

apt install systemd-sysv    # make link: /sbin/init -> /lib/systemd/systemd
```

### login & non-login shells

<https://www.gnu.org/software/bash/manual/html\\_node/Bash-Startup-Files.html>

```
login shells：  
    /etc/profile
    ~/.bash_profile(?-> ~/.bashrc), ~/.bash_login, and ~/.profile 
    exit:  ~/.bash_logout

non-login shells： 
    ~/.bashrc

# echo $0 : `shopt login_shell` \| $-
-bash : login_shell on | himBHs
# bash
# echo $0 : `shopt login_shell` \| $-
bash : login_shell off | himBHs
# bash -c 'echo $0 : `shopt login_shell` \| $-'
bash : login_shell off | hBc
```

### supervisord

<http://supervisord.org/running.html>

## Exit code

<http://tldp.org/LDP/abs/html/exitcodes.html>

```
1	Catchall for general errors
2	Misuse of shell builtins
126	Command invoked cannot execute
127	"command not found"	illegal_command	Possible problem with $PATH or a typo
128+n	Fatal error signal "n"	
    kill -9 $PPID of script	$? returns 137 (128 + 9)
130	Script terminated by Control-C
```

## Syslog Message Severities

<https://tools.ietf.org/html/rfc5424#section-6.2.1>

```
0       Emergency: system is unusable
1       Alert: action must be taken immediately
2       Critical: critical conditions
3       Error: error conditions
4       Warning: warning conditions
5       Notice: normal but significant condition
6       Informational: informational messages
7       Debug: debug-level messages
```

## Signals

```
kill -l
1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
6) SIGABRT      7) SIGBUS       8) SIGFPE       9) SIGKILL ... 64) SIGRTMAX
```

## kill

```
pkill -KILL -u {username}
```

## top

```
* 1 - Single Cpu       Off (thus multiple cpus)
* c - Command line     Off (name, not cmdline)
* i - Idle tasks       On  (show all tasks)
j - Str align right  Off (not right justify)
V - Forest view      On  (show as branches)
f - sort/hide columns
(`*')  could be overridden through the command-line.
```

### Glances - A top/htop alternative - Python

<https://github.com/nicolargo/glances>

```
pip install glances[action,browser,cloud,cpuinfo,chart,docker,export,folders,gpu,ip,raid,snmp,web,wifi]
```

## User & Permission

### add user to group

```
sudo adduser foobar www-data
sudo usermod -a -G ftp tony
```

### rename

```
pkill -9 -u ubuntu
usermod --login fzinfz --move-home --home /home/fzinfz ubuntu
sed -i 's/ubuntu/fzinfz/' /etc/sudoers
```

### password

```
echo user:pwd | chpasswd
```

### sudoers

```
sudo visudo
    root    ALL=(ALL) ALL # {terminals}=({users}) {commands}
    %supergroup  ALL=(ALL) NOPASSWD:ALL
```

### chown

```
chown -h myuser:mygroup mysymbolic
```

## Package Management

### Redhat

Free RHEL： <https://developers.redhat.com/articles/no-cost-rhel-faq/>

```
subscription-manager register
subscription-manager attach --auto
subscription-manager repos --enable rhel-7-server-optional-rpms
subscription-manager repos --enable rhel-7-server-extras-rpms
yum install epel-release
rm -f /var/run/yum.pid <PID> && yum remove PackageKit

yum-config-manager --disable c7-media
yum --nogpgcheck localinstall xx.rpm

### EPEL
http://elrepo.org/tiki/tiki-index.php

rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org
rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-3.el7.elrepo.noarch.rpm
yum install yum-plugin-fastestmirror
yum --enablerepo=elrepo-kernel install kernel-ml
```

### Ubuntu

Main - Canonical-supported free and open-source software.\
Universe - Community-maintained free and open-source software.\
Restricted - Proprietary drivers for devices.\
Multiverse - Software restricted by copyright or legal issues.

```
# https://mirror.tuna.tsinghua.edu.cn/help/ubuntu/
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial main restricted universe multiverse
```

### Debian

→ experimental\
→ unstable(Sid) → testing → stable\
Unstable - repository where new & untested packages are introduced.\
Testing - repository with packages from unstable, if no bug are found within 10 days.

`main` consists of DFSG-compliant packages, which do not rely on software outside this area to operate. These are the only packages considered part of the Debian distribution.\
`contrib` packages contain DFSG-compliant software, but have dependencies not in main (possibly packaged for Debian in non-free).\
`non-free` contains software that does not comply with the DFSG.

```
deb http://mirror.sjtu.edu.cn/debian/ bullseye main contrib non-free
```

#### experimental

```
deb http://mirror.sjtu.edu.cn/debian/ experimental main contrib non-free

apt install -t experimental linux-image-amd64 # latest kernel
```

### dpkg

```
dpkg --get-selections   # list installed
```

To install .deb manually, visit `linux/kernel` page.

### apt

```
apt-get install linux-base -t jessie-backports
apt-cache search linux-image | grep linux-image-4
apt install linux-image-4.10.0-9-generic linux-image-extra-4.10.0-9-generic

apt show linux-image-extra-4.10*

apt-get install --only-upgrade docker-engine

apt policy docker-ce | head -n 20

apt-get autoclean
apt list --installed

rm -r /var/lib/apt/lists/*
```

```
echo 'Acquire::http::Proxy "http://192.168.88.25:7890"; ' > /etc/apt/apt.conf.d/proxy
```

### ssh server

```
deb http://.../debian/ buster main contrib non-free

apt install openssh-server # not "openssl"

journalctl -u ssh # fix： ssh-rsa not in PubkeyAcceptedAlgorithms
PubkeyAcceptedAlgorithms  +ssh-rsa
```

## Grub

```
grub2-mkconfig -o /boot/grub2/grub.cfg
awk -F\' '/menuentry / {print $2}' /boot/grub/grub.cfg
grub2-set-default 'CentOS Linux (4.9.0-rc8-amd64) 7 (Core)'
grub2-editenv list
```

fix: <https://www.supergrubdisk.org/category/download/>

### grub-customizer

```
sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer
```

### boot .iso

<https://netboot.xyz/docs/booting/grub>

```
apt install grub-imageboot
mkdir /boot/images && cd /boot/images
wget https://boot.netboot.xyz/ipxe/netboot.xyz.iso
update-grub2
```

## boot repair

<https://sourceforge.net/p/boot-repair-cd/home/Home/> apt install linux-image-\* # if vmlinuz & initrd.img missing

### ubuntu

```
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install -y boot-repair && boot-repair
```

## Serial

<https://help.ubuntu.com/community/SerialConsoleHowto>

```
GRUB_CMDLINE_LINUX="console=tty0 console=ttyS0,115200n8"
```

### client

```
screen /dev/ttyUSB0 115200
picocom -b 115200 /dev/ttyUSB0
```

## Benchmark

<http://www.brendangregg.com/Perf/linux\\_benchmarking\\_tools.png>

```
    sysbench --test=cpu --cpu-max-prime=20000 --num-threads=32 run

    wget http://www.numberworld.org/y-cruncher/y-cruncher%20v0.7.9.9510-static.tar.xz
    tar -xf y-cruncher*.tar.xz

```

## mosh

```
apt install mosh -y
ss -lntup | grep mosh # 60000:61000/udp | **after** client connected
```

## sshd

mobaxterm login failed: No supported authentication methods

```
PubkeyAcceptedAlgorithms +ssh-rsa # sshd_config # journalctl -u ssh
```

## ssh redirect

```
ssh -L 9000:public.com:80   # visit local:9000 -> public.com:80
ssh -L 0.0.0.0:54321:127.0.0.1:54321 remote -p 22
ssh -R 9000:localhost:3000  # visit remote:9000 -> local:3000, "GatewayPorts yes" in sshd_config
    -nNT -L ...   # port forwarding only, no shell
```

## web

### wget

```
wget -O diff_name.zip http://...
```

### curl

```
curl -O http://...
curl -o diff_name.zip http://

curl -sSL $1

  -f, --fail          Fail silently (no output at all) on HTTP errors (H)
  -s, --silent        Silent mode (don't output anything)
  -S, --show-error    Show error. With -s, make curl show errors when they occur
  -L, --location      Follow redirects (H)
  -o, --output FILE   Write to FILE instead of stdout
  -O, --remote-name   Write output to a file named as the remote file
  
```

## files

String replace: <http://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files>

```
apt-get install mlocate
updatedb
locate -S
lsof -p <PID>

ls --help | grep -E '[-][tr]\b'
-r, --reverse              reverse order while sorting
                            extension -X, size -S, time -t, version -v
-t                         sort by modification time, newest first

mkdir -p /not/existing/folder

cat > file <<'EOL'
EOL

ncdu --exclude='/root/data/*' /

du -hcd 2  / | more
du -a / | sort -n -r | head -n 20

ls -1 $PWD | wc -l  # count files

file /bin/ps
ldd /bin/ps
```

### find

```
find /home -iname tecmint.txt
find $1 -iname $2
# find . ! -readable / -writable / -executabl
# find . ! -perm -g=w

find -regextype posix-extended -regex ".*[.](py|sh)" -exec chmod +x {} \;
```

### grep

```
grep --color=auto -rn -P "${regex}" ${path}
# -r, --recursive           like --directories=recurse
# -n, --line-number         print line number with output lines
# -P, --perl-regexp         PATTERN is a Perl regular expression
```

### compress/uncompress

```
gunzip file.gz

tar -czvf name-of-archive.tar.gz /path/to/directory-or-file # Compress

tar -tvf my-data.tar.gz '*.py'

tar -zxvf toExtract.tar.gz
tar -xvf {tarball.tar} {special_file} -C /target/directory

tar -cf archive.tar foo bar  # Create archive.tar from files foo and bar.
tar -tvf archive.tar         # List all files in archive.tar verbosely.
tar -xf archive.tar          # Extract all files from archive.tar.
    -t, --list                 list the contents of an archive
    -j, --bzip2                filter the archive through bzip2
    -c, --create               create a new archive    
    -x, --extract, --get       extract files from an archive    
    -z, --gzip, --gunzip, --ungzip   filter the archive through gzip
    -v, --verbose              verbosely list files processed
    -f, --file=ARCHIVE         use archive file or device ARCHIVE

zip [options] zipfile files_list
    -r   recurse into directories
    -x   exclude the following names
    -v   verbose operation/print version info

    -m   move into zipfile (delete OS files) !!
    -d   delete entries in zipfile !!!
    -u   update: only changed or new files

xz --decompress file.xz # -dgrub # unxz
```

### rsync

```
rsync -aP -e "ssh -p $3" $1 root@$2

rsync -aP  /root/_bin root@remote:/root
rsync -aP -e "ssh -p 10220" /local root@remote:/dir   --remove-source-files
    -v, --verbose               increase verbosity
    -a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)
        --no-OPTION             turn off an implied OPTION (e.g. --no-D)
    -r, --recursive             recurse into directories
    -l, --links                 copy symlinks as symlinks
    -p, --perms                 preserve permissions
    -o, --owner                 preserve owner (super-user only)
    -g, --group                 preserve group
    -D                          same as --devices --specials
    -t, --times                 preserve modification times
    -S, --sparse                handle sparse files efficiently
    -e, --rsh=COMMAND           specify the remote shell to use
        --partial               keep partially transferred files
        --partial-dir=DIR       put a partially transferred file into DIR
    -z, --compress              compress file data during the transfer
        --progress              show progress during transfer
    -P                          same as --partial --progress
```

## history without line numbers

```
history | cut -c 8-
  -a	append history lines from this session to the history file  ~/.bash_history    
```

## hostname

```
hostnamectl set-hostname GZ2C8G
```

## font

```
apt-get install  xfonts-base
```

## SELinux

```
getenforce
semanage port -a -t mongod_port_t -p tcp 27017
```

## Dropbox

### link account

`~/.dropbox-dist/dropboxd`\
dropboxd will create a \~/Dropbox folder and start synchronizing it after this step!\
unlink: <https://www.dropbox.com/account#security>

## Ubuntu snap

run without `root`

### Proxy

```
vi /etc/environment
systemctl restart snapd
```

## JAVA\_HOME

```
echo export JAVA_HOME="/usr/lib/jvm/java-1.8.0-openjdk" >> /etc/profile
```

## I18N & I10N

```
apt install -y locales-all
locale -a
dpkg-reconfigure locales

yum grouplist chinese-support

sudo apt-get install -y ttf-wqy-microhei  #文泉驿-微米黑
sudo apt-get install -y ttf-wqy-zenhei  #文泉驿-正黑
sudo apt-get install -y xfonts-wqy #文泉驿-点阵宋体
```

## Chrome

```
chromium --no-sandbox # start as root
```

## AD

<https://wiki.samba.org/index.php/Setting\\_up\\_Samba\\_as\\_an\\_NT4\\_PDC\\_(Quick\\_Start)>

## cache diagnostics

<https://hoytech.com/vmtouch/>

```
git clone https://github.com/hoytech/vmtouch.git
cd vmtouch && make && sudo make install

Discovering which files your OS is caching
Telling the OS to cache or evict certain files or regions of files
Locking files into memory so the OS won't evict them
Preserving virtual memory profile when failing over servers
Keeping a "hot-standby" file-server
Plotting filesystem cache usage over time
Maintaining "soft quotas" of cache usage
Speeding up batch/cron jobs
```

## WOL

```
ethtool enp1s0  | grep Wake-on

p (PHY activity)
u (unicast activity)
m (multicast activity)
b (broadcast activity)
g (magic packet activity) *
a (ARP activity)
d (disabled)
```

## Tools - Online

<http://explainshell.com/>

## CPU

```
getconf LONG_BIT
```

### check\_cpu\_core\_mapping

<https://www.ibm.com/support/knowledgecenter/en/SSQPD3\\_2.6.0/com.ibm.wllm.doc/mappingcpustocore.html\\>
same physical/core ID =》 simultaneous multi threads (SMTs) / HT

```
cat /proc/cpuinfo  | grep -P 'processor|physical id|core id|^$'

pip install walnut    # pretty print
for c in sorted([ ( int(c['processor']), int(c['physical id']), int(c['core id']) ) for c in cpu.dict().values()]): print c
```

## USB Persistence

<https://docs.kali.org/downloading/kali-linux-live-usb-persistence\\>
<http://antix.mepis.org/index.php?title=Using\\_liveusb\\_with\\_persistence>

## kali

x86/M1/Live/VM/WSL/etc: <https://www.kali.org/get-kali\\>
Docker: <https://hub.docker.com/u/kalilinux/>

## ssh

Since 2022.1: <https://www.kali.org/docs/general-use/ssh-configuration/>

* kali-tweaks -> Hardening -> Strong Security (the default) and Wide Compatibility

  ls -l /etc/ssh/ssh\_host\_\* systemctl disable regenerate-ssh-host-keys.service

### tools

<https://www.kali.org/tools/\\>
screenshots/cheat sheet: <https://www.comparitech.com/net-admin/kali-linux-cheat-sheet/#Kali\\_Linux\\_tools>

## Video

<https://askubuntu.com/questions/28033/how-to-check-the-information-of-current-installed-video-drivers>

```
dpkg -l amdgpu-pro
glxinfo | grep direct
GALLIUM_HUD=help glxgears
```

## OpenCL

installable client driver loader (ICD Loader) may expose multiple separate vendor installable client drivers (Vendor ICDs) for OpenCL.

```
sudo apt install ocl-icd-opencl-dev
```

## zFCP

device driver that supplements the Linux SCSI stack.

![](https://www.ibm.com/support/knowledgecenter/linuxonibm/com.ibm.linux.z.lgdd/lxzfcp.jpg)

## Diagram

![](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7b/Free_and_open-source-software_display_servers_and_UI_toolkits.svg/1573px-Free_and_open-source-software_display_servers_and_UI_toolkits.svg.png)

## diskless

<https://help.ubuntu.com/community/DisklessUbuntuHowto>

<https://drbl.org/>

```
docker run --network=host -d leejoneshane/drbl-server
```

<http://web.mst.edu/\\~vojtat/pegasus/administration.htm\\>
based on Scientific Linux 7 / CentOS 7 / Red Hat Enterprise Linux 7




---

[Next Page](/llms-full.txt/1)

