2
0
mirror of https://github.com/chubin/cheat.sheets synced 2024-11-17 09:25:32 +00:00

Merge pull request #99 from terminalforlife/master

More Comments & Code Tweaks & Additions
This commit is contained in:
Igor Chubin 2020-03-01 16:50:36 +01:00 committed by GitHub
commit 4a1a6d1e77
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
70 changed files with 350 additions and 288 deletions

View File

@ -26,4 +26,3 @@ int functionName(int &referenceName) {}
// Pass by value (the caller and callee have two independent variables with the same value) // Pass by value (the caller and callee have two independent variables with the same value)
int functionName(int valueName) {} int functionName(int valueName) {}

View File

@ -1,8 +1,15 @@
int *int_Ptr; // Declare a pointer variable called iPtr pointing to an int (an int pointer) // Declare a pointer variable called iPtr pointing to an int (an int pointer)
// It contains an address. That address holds an int value. // It contains an address. That address holds an int value.
double *double_Ptr; // Declare a pointer of type double. int *int_Ptr;
int a = 5; // Initializes a to the integer value 5 // Declare a pointer of type double.
int *int_Ptr = &a // Set int_Ptr which is an int pointer to the address of a double *double_Ptr;
std::cout << int_Ptr; // Returns the address of a
std::cout << *int_Ptr; // Returns 5 because it dereference the pointer to retrieve the value of a. // Initializes a to the integer value 5
int a = 5;
// Set int_Ptr which is an int pointer to the address of `a`.
int *int_Ptr = &a
// Returns the address of `a`.
std::cout << int_Ptr;
// Returns 5 because it dereference the pointer to retrieve the value of `a`.
std::cout << *int_Ptr;

View File

@ -1,14 +1,24 @@
var a []int // declare a slice - similar to an array, but length is unspecified // declare a slice - similar to an array, but length is unspecified
var a = []int {1, 2, 3, 4} // declare and initialize a slice (backed by the array given implicitly) var a []int
a := []int{1, 2, 3, 4} // shorthand // declare and initialize a slice (backed by the array given implicitly)
chars := []string{0:"a", 2:"c", 1: "b"} // ["a", "b", "c"] var a = []int {1, 2, 3, 4}
// shorthand
a := []int{1, 2, 3, 4}
// ["a", "b", "c"]
chars := []string{0:"a", 2:"c", 1: "b"}
var b = a[lo:hi] // creates a slice (view of the array) from index lo to hi-1 // creates a slice (view of the array) from index lo to hi-1
var b = a[1:4] // slice from index 1 to 3 var b = a[lo:hi]
var b = a[:3] // missing low index implies 0 // slice from index 1 to 3
var b = a[3:] // missing high index implies len(a) var b = a[1:4]
a = append(a,17,3) // append items to slice a // missing low index implies 0
c := append(a,b...) // concatenate slices a and b var b = a[:3]
// missing high index implies len(a)
var b = a[3:]
// append items to slice a
a = append(a,17,3)
// concatenate slices a and b
c := append(a,b...)
// create a slice with make // create a slice with make
a = make([]byte, 5, 5) // first arg length, second capacity a = make([]byte, 5, 5) // first arg length, second capacity

View File

@ -32,17 +32,17 @@ else:
# Basic 'for' loop: # Basic 'for' loop:
for i in range(6): for i in range(6):
print(i) #prints 0, 1, 2, 3, 4, 5 print(i) #prints 0, 1, 2, 3, 4, 5
#
for i in range(2, 6): for i in range(2, 6):
print(i) #prints 2, 3, 4, 5 print(i) #prints 2, 3, 4, 5
#
for i in range(3, 10, 2): for i in range(3, 10, 2):
print(i) #prints 3, 5, 7, 9 print(i) #prints 3, 5, 7, 9
# Iterating through collections: # Iterating through collections:
for i in [0, 1, 1, 2, 3, 5]: for i in [0, 1, 1, 2, 3, 5]:
print(i) #prints 0, 1, 1, 2, 3, 5 print(i) #prints 0, 1, 1, 2, 3, 5
#
for i in 'qwerty': for i in 'qwerty':
print(i) #prints q, w, e, r, t, y print(i) #prints q, w, e, r, t, y

View File

@ -1,7 +1,7 @@
# sum integers from a file or stdin, one integer per line: # sum integers from a file or STDIN, one integer per line:
printf '1\n2\n3\n' | awk '{ sum += $1} END {print sum}' printf '1\n2\n3\n' | awk '{ sum += $1} END {print sum}'
# using specific character as separator to sum integers from a file or stdin # using specific character as separator to sum integers from a file or STDIN
printf '1:2:3' | awk -F ":" '{print $1+$2+$3}' printf '1:2:3' | awk -F ":" '{print $1+$2+$3}'
# print a multiplication table # print a multiplication table
@ -16,31 +16,36 @@ awk -v RS='' '/42B/' file
# display only first column from multi-column text # display only first column from multi-column text
echo "first-column second-column third-column" | awk '{print $1}' echo "first-column second-column third-column" | awk '{print $1}'
# Use awk solo; without the need for something via STDIN. # Use AWK solo; without the need for something via STDIN.
awk BEGIN'{printf("Example text.\n")}' awk BEGIN'{printf("Example text.\n")}'
# Accessing environment variables from within awk. # Accessing environment variables from within AWK.
awk 'BEGIN{print ENVIRON["LS_COLORS"]}' awk 'BEGIN{print ENVIRON["LS_COLORS"]}'
# One method to count the number of lines; in this case, read from STDIN. # One method to count the number of lines; in this case, read from STDIN.
free | awk '{i++} END{print i}' free | awk '{i++} END{print i}'
# Output a (unique) list of available sections under which to create a DEB package. # Output unique list of available sections under which to create a DEB package.
awk '!A[$1]++{print($1)}' <<< "$(dpkg-query --show -f='${Section}\n')" awk '!A[$1]++{print($1)}' <<< "$(dpkg-query --show -f='${Section}\n')"
# Using process substitution (`<()` is NOT command substitution), with AWK and its # Using process substitution (`<()` is NOT command substitution), with AWK and
# associative array variables, we can print just column 2 for lines whose first # its associative array variables, we can print just column 2 for lines whose
# column is equal to what's between the double-quotes. # first column is equal to what's between the double-quotes.
awk '{NR!=1&&A[$1]=$2} END{print(A["Mem:"])}' <(free -h) awk '{NR!=1&&A[$1]=$2} END{print(A["Mem:"])}' <(free -h)
# While below is an easier and simpler solution to the above, it's not at all the # While below is an easier and simpler solution to the above, it's not at all
# same, and in other cases, the above is definitely preferable; more accurate. # the same, and in other cases, the above is definitely preferable.
awk '/^Mem:/{print($2)}' <(free -h) awk '/^Mem:/{print($2)}' <(free -h)
# Output a unique-d list of uppercase-only, sigil-omitted variables used in [FILE]. # Output list of unique uppercase-only, sigil-omitted variables used in [FILE].
awk '{for(F=0; F<NF; F++){if($F~/^\$[A-Z_]+$/){A[$F]++}}} END{for(I in A){X=substr(I, 2, length(I)); printf("%s\n", X)}}' [FILE] awk '{for(F=0; F<NF; F++){if($F~/^\$[A-Z_]+$/){A[$F]++}}} END{for(I in A){X=substr(I, 2, length(I)); printf("%s\n", X)}}' [FILE]
# Output only lines from FILE between PATTERN_1 and PATTERN_2. Good for log files. # Output only lines from FILE between PATTERN_1 and PATTERN_2. Good for logs.
awk '/PATTERN_1/,/PATTERN_2/{print}' [FILE] awk '/PATTERN_1/,/PATTERN_2/{print}' [FILE]
# Pretty-print a table of an overview of the non-system users on the system. # Pretty-print a table of an overview of the non-system users on the system.
awk -SPF ':' 'BEGIN {printf("%-17s %-4s %-4s %-s\n", "NAME", "UID", "GID", "SHELL")} $3>=1000 && $1!="nobody" {printf("%-17s %-d %-d %-s\n", $1, $3, $4, $7)}' /etc/passwd awk -SPF ':' 'BEGIN {printf("%-17s %-4s %-4s %-s\n", "NAME", "UID", "GID", "SHELL")} $3>=1000 && $1!="nobody" {printf("%-17s %-d %-d %-s\n", $1, $3, $4, $7)}' /etc/passwd
# Display the total amount of MiB of RAM available in the machine. This is also
# a painful but useful workaround to get the units comma-separated, as would be
# doable with Bash's own `printf` built-in.
awk '/^MemTotal:/ {printf("%'"'"'dMiB\n", $2 / 1024)}'

View File

@ -1,2 +1,16 @@
# POSIX-ly correct way in which to cat(1); see cat(1posix). # POSIX-ly correct way in which to cat(1); see cat(1posix).
cat -u [FILE_1 [FILE_2] ...] cat -u [FILE_1 [FILE_2] ...]
# Output a file, expanding any escape sequences (default). Using this short
# one-liner let's you view the boot log how it was show at boot-time.
cat /var/log/boot.log
# This is an ever-popular useless use of cat.
cat /etc/passwd | grep '^root'
# The sane way:
grep '^root' /etc/passwd
# If in bash(1), this is often (but not always) a useless use of cat(1).
Buffer=`cat /etc/passwd`
# The sane way:
Buffer=`< /etc/passwd`

View File

@ -1,26 +1,42 @@
# Read from {/dev/urandom} 2*512 Bytes and put it into {/tmp/test.txt} # Read from {/dev/urandom} 2*512 Bytes and put it into {/tmp/test.txt}
# Note: At the first iteration, we read 512 Bytes. # Note: both iterations each read 512 Bytes (the selected block size).
# Note: At the second iteration, we read 512 Bytes. dd if=/dev/urandom of=/tmp/test.txt count=2 bs=512
dd if=/dev/urandom of=/tmp/test.txt count=512 bs=2
# Watch the progress of 'dd' # Watch the progress of dd(1).
dd if=/dev/zero of=/dev/null bs=4KB &; export dd_pid=`pgrep '^dd'`; while [[ -d /proc/$dd_pid ]]; do kill -USR1 $dd_pid && sleep 1 && clear; done dd if=/dev/zero of=/dev/null bs=4KB &
export dd_pid=`pgrep '^dd'`
while [[ -d /proc/$dd_pid ]]; do
kill -USR1 $dd_pid && sleep 1
clear
done
# Watch the progress of 'dd' with `pv` and `dialog` (apt-get install pv dialog) # Watch the progress of dd(1) with pv(1) and dialog(1), both of which can be
(pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror) 2>&1 | dialog --gauge "Running dd command (cloning), please wait..." 10 70 0 # installed with the following command: apt-get install pv dialog
(
pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror
) 2>&1 | dialog --gauge "Running dd command (cloning), please wait..." 10 70 0
# Watch the progress of 'dd' with `pv` and `zenity` (apt-get install pv zenity) # Watch the progress of dd(1) with pv(1) and zenity(1), both of which can be
(pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror) 2>&1 | zenity --title 'Running dd command (cloning), please wait...' --progress # installed with the following command: apt-get install pv zenity
(
pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror
) 2>&1 | zenity --title 'Running dd command (cloning), please wait...' --progress
# Watch the progress of 'dd' with the built-in `progress` functionality (introduced in coreutils v8.24) # Watch the progress of dd(1) with the built-in `progress` functionality, -
# introduced in coreutils v8.24.
dd if=/dev/zero of=/dev/null bs=128M status=progress dd if=/dev/zero of=/dev/null bs=128M status=progress
# DD with "graphical" return # DD with "graphical" return
dcfldd if=/dev/zero of=/dev/null bs=500K dcfldd if=/dev/zero of=/dev/null bs=500K
# This will output the sound from your microphone port to the ssh target computer's speaker port. The sound quality is very bad, so you will hear a lot of hissing. # This will output the sound from your microphone port to the ssh target
# computer's speaker port. The sound quality is very bad, so you will hear a
# lot of hissing.
dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp
# Show current progress without interruption (USR1) # Show current progress without interruption (USR1)
dd if=/dev/zero of=/dev/null & pid=$! dd if=/dev/zero of=/dev/null & pid=$!
kill -USR1 $pid kill -USR1 $pid
# Create a 1GiB file with nothing but zeros, ready to mkswap(8) it.
dd if=/dev/zero of=/swapfile count=1048576 bs=1024 status=progress

View File

@ -1,14 +1,17 @@
# Printout disk free space in a human readable format # Print free disk space in a [h]uman-readable format.
df -h df -h
# Disk free space for ext2 file systems # Free disk space for [t]ype EXT2 file systems.
df -t ext2 df -t ext2
# Disk free space for file systems except ext2 # Free disk space for filesystems, e[x]cluding EXT2.
df -x ext2 df -x ext2
# Show inode usage # Show [i]node usage.
df -i df -i
# Show information about a distinct file system /path # Show information about a distinct filesystem path.
df /path df [PATH]
# List [a]ll filesystems, + unreadable, duplicates, pseudo, and inaccessible.
df -a

View File

@ -1,17 +1,17 @@
# exec # exec
# #
# Shell builtin command # Shell builtin command
# It can start a new process to replace the shell, without a new process creation. # It can start a new process to replace the shell, without a new process
# It can make redirections take effect in the current shell # creation. It can make redirections take effect in the current shell
# Redirect the output of an entire shell script within the script itself # Redirect all STDOUT from within a script to the given file.
# Only stdout:
exec > foo.log exec > foo.log
# Redirect the output of an entire shell script within the script itself # Redirect all of both STDOUT & STDERR from within a script to the given file.
# Stdout and stderr:
exec > foo.log 2>&1 exec > foo.log 2>&1
# Or, if on bash(1), this syntax is also viable:
exec &> foo.log
# Copy output to a log file # Copy output to a log file, allowing the outputs to still work as usual.
exec > >(tee -ia foo.log) exec > >(tee -ia foo.log)
exec 2> >(tee -ia foo.log >&2) exec 2> >(tee -ia foo.log >&2)

View File

@ -1,10 +1,5 @@
# list partitions # List partitions on BLKDEV, such as `/dev/sda`.
fdisk -l /dev/sda fdisk -l [BLKDEV]
# delete a partition
fdisk /dev/sda
Command (m for help): d
Partition number (1-9): XXX
# Usage: # Usage:
# fdisk [options] <disk> change partition table # fdisk [options] <disk> change partition table

View File

@ -101,16 +101,18 @@ bindsym $mod+4 workspace $ws4
bindsym $mod+Shift+R exec custom-script-in-path.sh --flag1 --flag2 bindsym $mod+Shift+R exec custom-script-in-path.sh --flag1 --flag2
bindcode 172 exec playerctl play-pause bindcode 172 exec playerctl play-pause
# Always execute code when i3 starts: # Execute code when i3 starts, but only once per session:
exec --no-startup-id ~/.config/polybar/launch.sh exec --no-startup-id ~/.config/polybar/launch.sh
# Always execute code when i3 starts, even if it's simply restarted:
exec_always --no-startup-id ~/.config/polybar/launch.sh
# One can make special modes (much like resize mode) # One can make special modes (much like resize mode)
set $gamingMode "gaming_mode" set $gamingMode "gaming_mode"
bindsym $mod+g mode $gamingMode bindsym $mod+g mode $gamingMode
mode $gamingMode { mode $gamingMode {
# Insert declarations for this mode # Insert declarations for this mode. Useful when normal keybindings fight
# Useful when normal keybindings fight with keybindings of your games # with keybindings of your games. Don't forget to add option to return from
# Don't forget to add option to return from this mode! # this mode!
bindsym $mod+Escape mode default bindsym $mod+Escape mode default
} }

View File

@ -1,33 +1,33 @@
# lshw # lshw
# Get hardware information on Linux # Get hardware information on Linux
# Generate full information report about all detected hardware # Generate full information report about all detected hardware.
lshw lshw
# Display hardware information in short # Display brief hardware information.
lshw -short lshw -short
# Display only memory information # Display only memory information.
lshw -short -class memory lshw -short -class memory
# Display processor information # Display processor information.
lshw -class processor lshw -class processor
# Display the disk drives with the disk class # Display the disk drives with the disk class.
lshw -short -class disk lshw -short -class disk
# Display information about the partitions and controllers also, # Display information about the partitions and controllers also,
# specify the storage and volume class along with the disk class # specify the storage and volume class along with the disk class.
lshw -short -class disk -class storage -class volume lshw -short -class disk -class storage -class volume
# Network adapter information # Network adapter information.
lshw -class network lshw -class network
# Display the address details of pci, usb, scsi and ide devices # Display the address details of PCI, USB, SCSI and IDE devices.
lshw -businfo lshw -businfo
# Generate report in html format # Generate report in HTML format.
lshw -html > hardware.html lshw -html > hardware.html
# Generate report in xml format # Generate report in XML format.
lshw -html > hardware.html lshw -html > hardware.html

View File

@ -10,3 +10,9 @@ printf '%s\n' "$USER"
# one million, in a human-readable kind of way, by appropriately # one million, in a human-readable kind of way, by appropriately
# comma-separating the units. # comma-separating the units.
printf "%'d\n" {1..1000000} printf "%'d\n" {1..1000000}
# Zero-pad a number in order to maintain a width of 3 characters.
printf '%#.3d\n' 12
# As above, but instead, space-pad the number. Prefix the `3` with a hyphen
# (`-`) to left-align the number, causing the padding to occur on the right.
printf '%3d\n' 12

View File

@ -12,3 +12,6 @@ cat /proc/<pid>/status
# See every file the process has open # See every file the process has open
ls -l /proc/<pid>/fd ls -l /proc/<pid>/fd
# Display some useful memory statistics, often used by programs like htop(1).
cat /proc/meminfo

View File

@ -10,10 +10,10 @@ python -m SimpleHTTPServer
# Python 3 # Python 3
python -m http.server 8000 python -m http.server 8000
# SMTP-Server for debugging, messages will be discarded, and printed on stdout. # SMTP-Server for debugging, messages will be discarded, and printed on STDOUT.
python -m smtpd -n -c DebuggingServer localhost:1025 python -m smtpd -n -c DebuggingServer localhost:1025
# Pretty print a json # Pretty print a JSON
python -mjson.tool python -mjson.tool
# Zen of Python # Zen of Python

View File

@ -22,7 +22,7 @@ sgdisk -l=sgdisk-sda.bak
# Clone your current device's partition layout '/dev/sda' to another drive '/dev/sdc' # Clone your current device's partition layout '/dev/sda' to another drive '/dev/sdc'
sgdisk -R=/dev/sdc /dev/sda sgdisk -R=/dev/sdc /dev/sda
# If both drives will be in the same computer, you need to randomize the GUID's after cloning # If both drives will be in the same computer, you need to randomize the GUIDs after cloning
sgdisk -G /dev/sdc sgdisk -G /dev/sdc

View File

@ -1,7 +1,7 @@
# siteciphers (Bash-Snippets) # siteciphers (Bash-Snippets)
# Checks the available ciphers for the SSL of an https site. # Checks the available ciphers for the SSL of an HTTPS site.
# Determine the available SSL ciphers for an https website # Determine the available SSL ciphers for an HTTPS website
siteciphers github.com siteciphers github.com
# Determine the ciphers setting the delay between requests (default is 1 sec) # Determine the ciphers setting the delay between requests (default is 1 sec)

View File

@ -1,6 +1,6 @@
# This is a shell builtin available in bash, but not in the Bourne Shell (`sh`). # This is a shell built-in available in Bash, but not in the Bourne Shell
# The contents of FILE (assuming shell script) will be sourced into the current # (`sh`). The contents of FILE (assuming shell script) will be sourced into the
# session, allowing external use of things like its functions and variables. # current session, allowing external use of its functions, variables, etc.
source FILE source FILE
# The above can be written in short-hand, for the same effect: # The above can be written in short-hand, for the same effect:
. FILE . FILE

View File

@ -1,28 +1,30 @@
# svgo # svgo
# #
# SVG Optimizer: a Nodejs-based tool for optimizing Scalable Vector Graphics files. # SVG Optimizer: a Node.js-based tool for optimizing Scalable Vector Graphics
# It applies a series of transformation rules (plugins), which can be toggled individually. # files. It applies a series of transformation rules (plugins), which can be
# toggled individually.
# Optimize a file using the default plugins (overwrites the original file): # Optimize a file using the default plugins, overwriting the original file.
svgo test.svg svgo test.svg
# Optimize a file and save the result to another file: # Optimize a file and save the result to another file.
svgo test.svg test.min.svg svgo test.svg test.min.svg
# Optimize all SVG files within a folder (overwrites the original files): # Optimize all SVG files within a directory, overwriting the original files.
svgo -f path/to/folder/with/svg/files svgo -f path/to/directory/with/svg/files
# Optimize all SVG files within a folder and save the resulting files to another folder: # Optimize all SVG files within a directory and save the resulting files to
svgo -f path/to/input/folder -o path/to/output/folder # another directory.
svgo -f path/to/input/dir -o path/to/output/dir
# Optimize SVG content passed from another command, and save the result to a file: # Optimize SVG content passed from another command, then save result to a file.
cat test.svg | svgo -i - -o test.min.svg cat test.svg | svgo -i - -o test.min.svg
# Optimize a file and print out the result: # Optimize a file and print out the result.
svgo test.svg -o - svgo test.svg -o -
# Optimize a file making sure a given plugin is enabled: # Optimize a file making sure a given plugin is enabled.
svgo --enable=plugin_name svgo --enable=plugin_name
# Show available plugins: # Show available plugins.
svgo --show-plugins svgo --show-plugins

View File

@ -1,10 +1,10 @@
# weather (Bash-Snippets) # weather (Bash-Snippets)
# Provides a 3 day forecast on your current location or a specified location # Provides a 3-day forecast on your current location or a specified location
# Get a 3 day forecast for your current location as determined by your ip address # Get 3-day forecast for your current location as determined by your IP address
weather weather
# Get a 3 day forecast for any location # Get 3-day forecast for any location
weather Tokyo weather Tokyo
# Get the current moon phase # Get the current moon phase