cat /path/to/foo
cat -n /path/to/foo
cat -b /path/to/foo
aria2c
aria2c --follow-torrent=mem
aria2c -j 1 -c -d ~/Downloads -i /path/to/file
chmod a+x myscript.sh
chmod u=rwx, go=r myscript.sh
chmod a-w myscript.sh
chmod = myscript.sh
chmod 644 myscript.sh
chmod 755 myscript.sh
chmod 666 myscript.sh
u - 用户 (文件的所有者)
g - 组 (文件组的成员)
o - 全局 (所有非所有者和非组员的用户)
a - 所有 (上述所有3个角色)
7 - 完全 (rwx)
6 - 读写 (rw-)
5 - 读+执行 (r-x)
4 - 只读 (r--)
3 - 写+执行 (-wx)
2 - 只写 (-w-)
1 - 只执行 (--x)
0 - 无 (---)
apt-cache search "whatever"
apt-cache show pkg(s)
apt-cache rdepends package_name
apt-cache showpkg package_name
caffeinate -u -t 3600
caffeinate -s command
c := make(chan int)
c := make(chan string, 10)
x, ok = <- c
var c chan string
c <- "Hello, World!" 向一个Channel发送一个值
var c chan string
fmt.Println(<-c) 从一个Channel中接收一个值
var c = make(chan string, 1)
c <- "Hello, World!"
close(c)
c <- "Hello, Panic!"
var c = make(chan int, 2)
c <- 1
c <- 2
close(c)
for i := 0; i < 3; i++ {
fmt.Printf("%d ", <-c)
}
for i := range ch { ch关闭时,for循环会自动结束
println(i)
}
select {
case <- time.After(time.Second*2):
println("read channel timeout")
case i := <- ch:
println(i)
}
select {
case <- time.After(time.Second *2):
println("write channel timeout")
case ch <- "hello":
println("write ok")
}
figlet Cheat
toilet -F border Cheat
toilet Cheat
VACUUM [ FULL | FREEZE ] [ VERBOSE ] [ table ]
VACUUM [ FULL | FREEZE ] [ VERBOSE ] ANALYZE [ table [ (column [, ...] ) ] ]
FULL ------选择"完全"清理,这样可以恢复更多的空间, 但是花的时间更多并且在表上施加了排它锁。
FREEZE ---------选择激进的元组"冻结"。
VERBOSE --------- 为每个表打印一份详细的清理工作报告。
ANALYZE --------- 更新用于优化器的统计信息,以决定执行查询的最有效方法。
table ------- 要清理的表的名称(可以有模式修饰)。缺省时是当前数据库中的所有表。
column ---------要分析的具体的列/字段名称。缺省是所有列/字段。
mkfifo pipe
tail -s .5 -n 120 -f httpd_access_log httpd_error_log httpd_modsec_audit_log >pipe &
ccze < pipe
ifconfig wlan0
ifconfig -a
ifconfig wlan0 {up|down}
ifconfig eth0 192.168.1.100 netmask 255.255.255.0
route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.1
imgcat filename
i := strconv.Itoa(x)
i,err := strconv.Atoi(x)
int64,err := strconv.PareInt(string,10,64)
string := strconv.FormatInt(int64,10)
i := int(int64)
int64,err := int64(xxx)
string := strconv.FormatFloat(float32,'E',-1,32)
string := strconv.FormatFloat(float64,'E',-1,64)
float,err := strconv.ParseFLoat(string,64)
float,err := strconv.ParseFLoat(string,32)
http:localhost:631 (浏览器中)
lp myfile.txt
lpq
lprm 545
或者
lprm -
/var/log/cups
cupsreject printername
cupsaccept printername
figlet Cheat
toilet -F border Cheat
toilet Cheat
var foo int 普通定义
var foo int = 42 定义并初始化
var foo, bar int = 42, 1302 一次写义多个
var foo = 42 类型省略,将被推断为某个类型
foo := 42 简称,仅在func体中,省略var关键字,类型总是隐含的
const constant = "This is a constant" 常量
docker pull ${CONTAINER NAME}
docker images
docker ps
docker ps -a
docker rmi ${IMAGE NAME/ID}
docker rm ${CONTAINER NAME/ID}
docker save ${IMAGE NAME} > ${FILE NAME}.tar
docker load < ${FILE NAME}.tar
docker start ${CONTAINER NAME/ID}
docker stop ${CONTAINER NAME/ID}
docker logs ${CONTAINER NAME/ID}
docker run...
--name ${container name} #设置容器名称
-p ${host port}:${container port} #映射主机和容器内的端口
-e ${env name}=${env value} #添加环境变量
-d #后台运行
-v ${host folder path}:${container folder path} #将主机目录挂在到容器内
docker ps -f "status=exited"
docker ps -a -q
docker ps -f "status=exited" -q
docker restart $(docker ps -q)
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)
docker rm $(docker ps -f "status=exited" -q)
docker rm $(docker stop $(docker ps -a -q))
docker start $(docker ps -a -q)
docker rmi $(docker images -a -q)
docker exec -it ${CONTAINER NAME/ID} /bin/bash
docker exec -it ${CONTAINER NAME/ID} ping ${CONTAINER NAME/ID}
docker top ${CONTAINER NAME/ID}
docker stats
docker stats -a #显示所有容器的统计信息(包括没有运行的)
docker stats -a --no-stream #显示所有容器的统计信息(包括没有运行的) ,只显示一次
docker stats --no-stream | sort -k8 -h #统计容器信息并以使用流量作为倒序
docker system
docker system df #显示硬盘占用
docker system events #显示容器的实时事件
docker system info #显示系统信息
docker system prune #清理文件
cut -d# -f3
cut -c -24 BALANCE.txt
cut -c -24,36-59 BALANCE.txt
cut -c -24,36-59,93- BALANCE.txt
gcc file.c
gcc -o file file.c
gcc -g
gcc -ggdb3
gcc -m64
gcc -isystem /usr/include/myPersonnal/lib/
gcc -mwindows
cleanmgr [/d
参数 说明
/d
注意:/d选项不与 一起使用 。
/sageset:n 显示"磁盘设置"对话框,并创建一个注册表项来存储你选择的设置。 通过存储在注册表中的 值,可以指定要运行 n 磁盘清理的任务。 该值 n 可以是从 0 到 9999 的任何整数值。
/sagerun:n 如果使用 /sageset 选项,则运行分配给 n 值的指定任务。 将枚举计算机上的所有驱动器,并且所选配置文件针对每个驱动器运行。
/tuneup:n 为同一 运行 /sageset和 /sagerun。
/lowdisk 使用默认设置运行 。
/verylowdisk 使用默认设置运行,无用户提示。
/? 在命令提示符下显示帮助。
0 NUT 32 (space) 64 @ 96 、
1 SOH 33 ! 65 A 97 a
2 STX 34 " 66 B 98 b
3 ETX 35 # 67 C 99 c
4 EOT 36 $ 68 D 100 d
5 ENQ 37 % 69 E 101 e
6 ACK 38 & 70 F 102 f
7 BEL 39 , 71 G 103 g
8 BS 40 ( 72 H 104 h
9 HT 41 ) 73 I 105 i
10 LF 42 * 74 J 106 j
11 VT 43 + 75 K 107 k
12 FF 44 , 76 L 108 l
13 CR 45 - 77 M 109 m
14 SO 46 . 78 N 110 n
15 SI 47 / 79 O 111 o
16 DLE 48 0 80 P 112 p
17 DCI 49 1 81 Q 113 q
18 DC2 50 2 82 R 114 r
19 DC3 51 3 83 S 115 s
20 DC4 52 4 84 T 116 t
21 NAK 53 5 85 U 117 u
22 SYN 54 6 86 V 118 v
23 TB 55 7 87 W 119 w
24 CAN 56 8 88 X 120 x
25 EM 57 9 89 Y 121 y
26 SUB 58 : 90 Z 122 z
27 ESC 59 ; 91 [ 123 {
28 FS 60 < 92 \ 124 |
29 GS 61 = 93 ] 125 }
30 RS 62 > 94 ^ 126
31 US 63 ? 95 _ 127 DEL
scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
[-l limit] [-o ssh_option] [-P port] [-S program]
[[user@]host1:]file1 [...] [[user@]host2:]file2
-1: 强制scp命令使用协议ssh1
-2: 强制scp命令使用协议ssh2
-4: 强制scp命令只使用IPv4寻址
-6: 强制scp命令只使用IPv6寻址
-B: 使用批处理模式(传输过程中不询问传输口令或短语)
-C: 允许压缩。(将-C标志传递给ssh,从而打开压缩功能)
-p:保留原文件的修改时间,访问时间和访问权限。
-q: 不显示传输进度条。
-r: 递归复制整个目录。
-v:详细方式显示输出。scp和ssh(1)会显示出整个过程的调试信息。这些信息用于调试连接,验证和配置问题。
-c cipher: 以cipher将数据传输进行加密,这个选项将直接传递给ssh。
-F ssh_config: 指定一个替代的ssh配置文件,此参数直接传递给ssh。
-i identity_file: 从指定文件中读取传输时使用的密钥文件,此参数直接传递给ssh。
-l limit: 限定用户所能使用的带宽,以Kbit/s为单位。
-o ssh_option: 如果习惯于使用ssh_config(5)中的参数传递方式,
-P port:注意是大写的P, port是指定数据传输用到的端口号
-S program: 指定加密传输时所使用的程序。此程序必须能够理解ssh(1)的选项。
scp foo.txt user@example.com:remote/dir
scp user@example.com:remote/dir/foo.txt local/dir
cd path/to/directory
cd
cd ..
cd -
trap "exit 1" TERM
export TOP_PID=$$
function fatal()
{
echo "Goodbye"
kill -s TERM $TOP_PID
}
echo "Function call will abort"
echo $(func)
echo "This will never be printed"
screen -S session_name
Press Ctrl+A then press d
screen -r session_name
screen -ls
screen -x
scrreen -L -dmS test
ctrl+a d (按ctrl不放,分别按a和d)
chown user file
chown user:group file
chown -R user directory
chown --reference=/path/to/ref_file file
dict -I
dict -d fd-eng-nld understand
dict -D
ipconfig /all
ipconfig /release
ipconfig /renew
安装:apt-get install netcat
-l 用于指定nc将处于侦听模式。指定该参数,则意味着nc被当作server,侦听并接受连接,而非向其它地址发起连接。
-p
-s 指定发送数据的源IP地址,适用于多网卡机
-u 指定nc使用UDP协议,默认为TCP
-v 输出交互或出错信息,新手调试时尤为有用
-w 超时秒数,后面跟数字
-z 表示zero,表示扫描时不发送任何数据
nc -l -p 9999
nc -vz -w 2 10.0.1.161 9999
nc -vzw 2 10.0.1.161 9998-9999
nc -ul -p 9998
nc -vuz 10.0.1.161 1-1000
nc -l -p 9995 > file # 端口接收到文件存为file
nc 10.0.0.1 9995 < file # 发送文件file到ip和端口
或
nc -l -p 9992 < file # 准备发送文件file到端口9992
nc 10.0.0.1 9992 > file # 连接到指定ip和端口,将接收到的内容存为file
nc -l -p 9995 | tar xzvf - # 等待接收
tar cfz - * | nc 10.0.0.1 9995 # 把当前目录下的所有文件打包为-,然后nc发送给目标
nc -l 9991 >/dev/null # 目标机上等待接收数据,但不保存(用于观察两者之间的速率)
nc 10.0.0.1 9991 < /dev/zero # 给目标主机发送无限的0
nc -p 31337 -w 5 host.example.com 42
nc -l -p 1234 | dd of=/dev/sda # 目标,监听,写入
dd if=/dev/sda | nc 10.0.0.1 1234 # 源:读取,发送
nc -u host.example.com 53
nc -s 10.1.2.3 host.example.com 42
nc -lU /var/tmp/dsocket
nc -x10.2.3.4:8080 -Xconnect host.example.com 42
nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42
nc -zv -s source_IP target_IP Port
用于在 Go 中构建现代 HTML5 桌面应用程序. 它使用 Chrome 浏览器作为 UI 层
type Vertex struct {
X, Y int
}
var v = Vertex{1, 2}
var v = Vertex{X: 1, Y: 2} 通过使用键定义值来创建结构
var v = []Vertex{{1,2},{5,2},{5,5}} 初始化一个结构片
v.X = 4
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
调用方法
v.Abs()
func (v *Vertex) add(n float64) {
v.X += n
v.Y += n
}
point := struct {
X, Y int
}{1, 2}
blktrace /dev/sdb -a PC -o - | blkparse -i -
carthage update
carthage update --platform ios
carthage update --no-build
carthage bootstrap
carthage build dependency
接口声明
type Awesomizer interface {
Awesomize() string
}
类型Foo声明要实现接口
type Foo struct {}
相反,类型隐含地满足一个接口
如果它们实现了所有需要的方法
func (foo Foo) Awesomize() string {
return "Awesome!"
}
dir | clip
clip < readme.txt
echo off | clip
ipconfig /all | clip
echo Hello | clip
这是一个cheat.sh小抄的Go版实现 Chris Lane's cheatsheet。
微信版可以搜索小程序:腾图小抄
搜索规则:上一条规则未搜索出内容,将进行下一条搜索规则
浏览器:
例如 https:scwy.net/tar
命令行界面:
例如:curl https:scwy.net/tar
欢迎大家共同建立小抄数据,支持作者继续完善。
cp ~/Desktop/foo.txt ~/Downloads/foo.txt
cp -r ~/Desktop/cruise_pics/ ~/Pictures/
cp -i ~/Desktop/foo.txt ~/Documents/foo.txt
cp foo.txt{,."$(date +%Y%m%d-%H%M%S)"}
switch operatingSystem {
case "darwin":
fmt.Println("Mac OS Hipster")
case "linux":
fmt.Println("Linux Geek")
default:
Windows, BSD, ...
fmt.Println("Other")
}
switch os := runtime.GOOS; os {
case "darwin": ...
}
number := 42
switch {
case number < 42:
fmt.Println("Smaller")
case number == 42:
fmt.Println("Equal")
case number > 42:
fmt.Println("Greater")
}
如果 CLS 被重定向到文件、控制台或通过 FOR /F 执行,它将打印换行符 (ASCII 10)。
var a []int 声明一个切片-类似于数组,但长度未指定
var a = []int {1, 2, 3, 4} 声明并初始化切片(由隐式给定的数组支持)
a := []int{1, 2, 3, 4} 直接定义
chars := []string{0:"a", 2:"c", 1: "b"} ["a", "b", "c"]
var b = a[lo:hi] 创建从索引lo到hi-1的切片(数组视图)
var b = a[1:4] 从索引1到索引3切片
var b = a[:3] 缺少低索引意味着0
var b = a[3:] 缺少高指数意味着len(a)
a = append(a,17,3) 将项目附加到切片
c := append(a,b...) 连接切片a和切片b
a = make([]byte, 5, 5) 第1个参数长度,第2个参数容量
a = make([]byte, 5) 容量是可选的
x := [3]string{"Лайка", "Белка", "Стрелка"}
s := x[:] a slice referencing the storage of x
SELECT[ALL|DISTINCT|DISTINCTROW|TOP]
{*|talbe.*|[table.]field1[AS alias1][,[table.]field2[AS alias2][,…]]}
FROM tableexpression[,…][IN externaldatabase]
[WHERE…]
[GROUP BY…]
[HAVING…]
[ORDER BY…]
SELECT 列名称 FROM 表名称
SELECT * FROM 表名称
= 等于
<> 不等于
大于 小于
= 大于等于
<= 小于等于
BETWEEN 在某个范围内
LIKE 搜索某种模式
SELECT DISTINCT 列名称 FROM 表名称
SHELL=/bin/bash
- - - - -
| | | | |
| | | | +- 周几 (0 - 7) (一周是从0-7)
| | | +--- 月 (1 - 12)
| | +----- 日 (1 - 31)
| +------- 时 (0 - 23)
+--------- 分 (0 - 59)
*/15 * * * * /home/user/command.sh
0 0 * * * /home/user/command.sh
5 8 * * 6 /home/user/command.sh
iconv -f iso-8859-1 -t utf-8 iconv.src -o /tmp/iconv.out
cryptsetup open --type luks /dev/sdb1 backup
cryptsetup open --type luks --key-file hdd.key /dev/sdb1 hdd
cryptsetup close hdd
let foo = OptionalI32::AnI32(1);
match foo {
OptionalI32::AnI32(n) => println!("it’s an i32: {}", n),
OptionalI32::Nothing => println!("it’s nothing!"),
}
Advanced pattern matching
struct FooBar { x: i32, y: OptionalI32 }
let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) };
match bar {
FooBar { x: 0, y: OptionalI32::AnI32(0) } =>
println!("The numbers are zero!"),
FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m =>
println!("The numbers are the same"),
FooBar { x: n, y: OptionalI32::AnI32(m) } =>
println!("Different numbers: {} {}", n, m),
FooBar { x: _, y: OptionalI32::Nothing } =>
println!("The second number is Nothing!"),
}
Syntax
CACLS pathname [options]
Options:
/T Search the pathname including all subfolders. (/TREE)
/E Edit ACL, leave existing rights unchanged (/EDIT)
/C Continue on access denied errors. (/CONTINUE)
/L Work on the Symbolic Link itself versus the target (/LINK)
/M Change ACLs of volumes mounted to a directory (/MOUNT)
/G user:permission
Grant access rights (/GRANT), permision can be:
R Read
W Write
C Change (read/write)
F Full control
/R user
Revoke specified user's access rights, only valid with /E. (/REVOKE)
/P user:permission
Replace access rights (/REPLACE), permission can be:
R Read
W Write
C Change (read/write)
F Full control
N None
/D user
Deny access to user. (/DENY)
/S
Display the SDDL string for the DACL. (/SSDL)
/S:sddl
Replace the ACL(s) with those specified in the SDDL string
(not valid with /E, /G, /R, /P, or /D).
(The long /aliases in brackets are undocumented)
In all the options above "user" can be a UserName or a group (either local or global)
You can specify more than one user:permission in a single command.
Wildcards can be used to specify multiple files.
If a UserName or GroupName includes spaces then it must be surrounded with quotes e.g. "Authenticated Users"
If no options are specified CACLS will display the ACLs for the file(s)
Setting Deny permission (/D) will deny access to a user even if they also belong to a group that grants access.
Limitations
Cacls cannot display or modify the ACL state of files locked in exclusive use.
Cacls cannot set the following permissions: change permissions, take ownership, execute, delete use XCACLS to set any of these.
Using CACLS
The CACLS command does not provide a /Y switch to automatically answer 'Y' to the Y/N prompt. However, you can pipe the 'Y' character into the CACLS command using ECHO, use the following syntax:
ECHO Y| CACLS filename /g username:permission
To edit a file you must have the "Change" ACL (or be the file's owner)
To use the CACLS command and change an ACL requires "FULL Control"
File "Ownership" will always override all ACL's - you always have Full Control over files that you create.
If CACLS is used without the /E switch all existing rights on [pathname] will be replaced, any attempt to use the /E switch to change a [user:permission] that already exists will raise an error. To be sure the CACLS command will work without errors use /E /R to remove ACL rights for the user concerned, then use /E to add the desired rights.
The /T option will only traverse subfolders below the current directory
If no options are specified CACLS will display the current ACLs
To display the current folder:
CACLS .
Display permissions for one file:
CACLS MyFile.txt
Display permissions for multiple files:
CACLS *.txt
Inherited folder permissions are displayed as:
OI - Object inherit - This folder and files. (no inheritance to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current file/directory
ID - Inherited - The ACE was inherited from the parent directory's ACL.
These can be combined as follows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.
So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F' (Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)
To actually change the inheritance of a folder/directory use iCACLS /grant or iCACLs /deny
When cacls is applied to the current folder only there is no inheritance and so no output.
Errors when changing permissions
If a user or group has a permission on a file or folder and you grant a second permission to the same user/group on the same folder, NTFS will sometimes produce the error message "The parameter is incorrect" To fix this (or prevent it happening) revoke the permission first /e /r and then apply a fresh grant /e /g
No mapping between account names and security IDs was done
This error indicates that cacls looked up the group or username given in Active Directory and didn't find anything, often this means that you need to prefix the name with a domain name ss64dom\user64 or (for a local account) the name of the machine pc64\localUser2 also check for simple typos.
Examples:
Add Read-Only permission to a single file
CACLS myfile.txt /E /G "Power Users":R
Add Full Control permission to a second group of users
CACLS myfile.txt /E /G "FinanceUsers":F
Now revoke the Read permissions from the first group
CACLS myfile.txt /E /R "Power Users"
Now give the first group Full-control:
CACLS myfile.txt /E /G "Power Users":F
Give the Finance group Full Control of a folder and all sub folders
CACLS c:\docs\work /E /T /C /G "FinanceUsers":F
db.books.find({year: {$eq: 2016}})
db.books.find({year: {$lt: 2010}})
db.books.find({year: {$lte: 2008}})
db.books.find({year: {$gt: 2014}})
db.books.find({year: {$gte: 2008}})
db.books.find({year: {$ne: 2008}})
db.books.find({year: {$in: [2008, 2016]}})
db.books.find({year: {$nin: [2008, 2016]}})
Syntax
BCDBOOT source [/l locale] [/s volume-letter [/f firmware]] [/v]
[/vbcd] [/m [{OS_Loader_GUID}]] [/addlast] [/p] [/bcdclean [full]] [/c]
Options
source The location of the Windows directory to use as the source for
copying boot-environment files.
/l The locale to use when initialising the BCD store. default = US English.
/s Optional. Specifies the volume letter of the system partition.
This option should not be used in typical deployment scenarios.
Use this setting to specify a system partition when you are configuring a drive that will
be booted on another computer, such as a USB flash drive or a secondary hard drive.
The default is the system partition identified by the firmware.
/v Enable verbose mode.
/vbcd Enable BCD Logging.
/m If an OS_Loader_GUID is specified, merge the given loader object within
the system template to produce a bootable entry.
Otherwise, by default, merge only global objects.
/d Preserve the existing default Windows Boot entry.
/f Used with /S, specifies the firmware type of the target system partition
Options for firmware are 'UEFI', 'BIOS', or 'ALL'
If you specify 'ALL', BCDBoot will create both the \Boot and the \Efi\Microsoft\Boot
directories, and will copy all required boot-environment files for BIOS and UEFI.
/addlast Specifies that the Windows Boot Manager firmware entry should be added last.
The default behavior is to add it first. Cannot be used with /p.
/bcdclean Clean the BCD Store. By default, simply removes any duplicate entries in
the BCD. Can be followed by 'full'. In this case, each entry is scanned
If the corresponding device for that entry does not exist, the entry is deleted.
/p Specifies that the existing Windows Boot Manager firmware entry position should be
preserved in the UEFI boot order. If the entry does not exist, a new entry is
added in the first position. Cannot be used with /addlast.
By default, during an upgrade BCDBoot moves the Windows Boot Manager to be
the first entry in the UEFI boot order.
/c Specifies that any existing BCD elements should not be migrated.
By default, during an upgrade, BCD elements such as debugsettings or flightsigning are preserved.
bcdboot C:\Windows
bcdboot C:\Windows /l ja-jp /s S:
bcdboot c:\windows /m {d58d10c6-df53-11dc-878f-00064f4f4e08}
rclone config
rclone ls remote:path
rclone copy /local/path remote:path
rclone sync /local/path remote:path
rclone copy s3:oldbucket s3:newbucket
svcs
svcs -vx
svcs apache
svcs -L apache
tail $(svcs -L apache)
docker -d
docker run -ti
docker exec -ti
docker inspect
docker inspect --format {{.State.Pid}}
docker inspect --format='{{json .Volumes}}'
docker cp foo.txt mycontainer:/foo.txt
docker ps
docker ps -a
docker images
mkfifo pipe
tail -s .5 -n 120 -f httpd_access_log httpd_error_log httpd_modsec_audit_log >pipe &
ccze < pipe
libreoffice --headless --convert-to pdf *.pptx
libreoffice --headless --convert-to pdf *.docx --outdir ~/docs/
fd -e doc -e docx -x libreoffice --headless --convert-to pdf --outdir {} {}
() (empty parens)
This example would be a Tuple3
(1,2,3)
This example would be a Tuple2
(1 -> 2) same as
(1, 2)
var (x,y,z) = (1,2,3)
BAD
var x,y,z = (1,2,3)
var xs = List(1,2,3)
more on it: https:www.slideshare.net/Odersky/fosdem-2009-1013261/27
xs(2)
1 :: List(2,3)
Map(1 -> 'a', 2 -> 'b', 3 -> 'c') same as
Map((1, 'a'), (2, 'b'), (3, 'c'))
accepts start, end and step parameters
Range(1, 5) returns Range(1,2,3,4,5)
Range(1, 10, 2) returns Range(1,3,5,7,9)
1 to 5 same as
1 until 6
1 to 10 by 2
rsync -avz host:file1 :file1 /dest/
rsync -avz /source host:/dest
rsync -avc /source/ /dest/
rsync -auv /src/foo /dest
rsync -auv /src/foo/ /dest/foo
rsync -avz -e "ssh -p1234" /source/file1 remoteuser@X.X.X.X:~/destination/
CLUSTER ADDSLOTS slot [slot ...]
CLUSTER COUNT-FAILURE-REPORTS node-id
CLUSTER COUNTKEYSINSLOT slot
CLUSTER DELSLOTS slot [slot ...]
CLUSTER FAILOVER [FORCE|TAKEOVER]
CLUSTER FORGET node-id
CLUSTER GETKEYSINSLOT slot count
CLUSTER INFO
CLUSTER KEYSLOT key
CLUSTER MEET ip port
CLUSTER NODES
CLUSTER REPLICATE node-id
CLUSTER RESET [HARD|SOFT]
CLUSTER SAVECONFIG
CLUSTER SET-CONFIG-EPOCH config-epoch
CLUSTER SETSLOT slot IMPORTING|MIGRATING|STABLE|NODE [node-id]
CLUSTER SLAVES node-id
CLUSTER SLOTS
READONLY
READWRITE
cp ~/Desktop/foo.txt ~/Downloads/foo.txt
cp -r ~/Desktop/cruise_pics/ ~/Pictures/
cp -i ~/Desktop/foo.txt ~/Documents/foo.txt
cp foo.txt{,."$(date +%Y%m%d-%H%M%S)"}
svccfg validate smf.xml
svccfg export servicename > smf.xml
svccfg import smf.xml
chmod a+x myscript.sh
chmod u=rwx, go=r myscript.sh
chmod a-w myscript.sh
chmod = myscript.sh
chmod 644 myscript.sh
chmod 755 myscript.sh
chmod 666 myscript.sh
u - user (owner of the file)
g - group (members of file's group)
o - global (all users who are not owner and not part of group)
a - all (all 3 roles above)
7 - full (rwx)
6 - read and write (rw-)
5 - read and execute (r-x)
4 - read only (r--)
3 - write and execute (-wx)
2 - write only (-w-)
1 - execute only (--x)
0 - none (---)
db.books.find( { $or: [{year: {$lte: 2008}}, {year: {$eq: 2016}}]} )
db.books.find( { $and: [{year: {$eq: 2008}}, {category: {$eq: "Fiction"}}]} )
db.books.find( {$not: {year: {$eq: 2016} }})
db.books.find( { $nor: [{year: {$lte: 2008}}, {year: {$eq: 2016}}]} )
python -c 'import inspect; import itertools; print inspect.getdoc(itertools.starmap)'
print inspect.getdoc(itertools.starmap)
help(itertools.starmap)
itertools.starmap?
ssh-copy-id username@host
ssh-copy-id username@host -p 2222
ssh-copy-id ~/.ssh/otherkey "username@host -p 2222"
Syntax
CHKNTFS drive: [...]
CHKNTFS /C drive: [...]
CHKNTFS /X drive: [...]
CHKNTFS /t[:Time]
CHKNTFS /D
Key
drive Specifies a drive letter.
/C Check - schedules chkdsk to be run at the next reboot.
/X Exclude a drive from the default boot-time check.
Excluded drives are not accumulated between command invocations.
/T Change the Autochk.exe initiation countdown time (time in seconds)
If you don’t specify Time: displays the current countdown time.
/D Restore the machine to the default behavior; all drives are
checked at boot time and chkdsk is run on those that are dirty.
This undoes the effect of the /X option.
If no switches are specified, CHKNTFS will display the status of the dirty bit for each drive.
if (check) happy else sad
if (check) happy same as
if (check) happy else ()
if (check) happy else if(secondCheck) lessHappy else ()
while (x < 5) { println(x); x += 1}
do { println(x); x += 1} while (x < 5)
slides: https:www.slideshare.net/Odersky/fosdem-2009-1013261/21
import scala.util.control.Breaks._
breakable {
for (x <- xs) {
if (Math.random < 0.1) break
}
}
for (x <- xs if x%2 == 0) yield x*10
xs.filter(_%2 == 0).map(_*10)
for ((x,y) <- xs zip ys) yield x*y
(xs zip ys) map { case (x,y) => x*y }
for (x <- xs; y <- ys) yield x*y
xs flatMap {x => ys map {y => x*y}}
http:docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
for (x <- xs; y <- ys) {
println("%d/%d = %.1f".format(x, y, x/y.toFloat))
}
for (i <- 1 to 5) {
println(i)
}
for (i <- 1 until 5) {
println(i)
}
can yield a "java.lang.StackOverflowError" with large lists
this is because each recursive call of the function is waiting for the evaluation of the next
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
case x :: tail => x + sum(tail)
}
this type of recursion will not throw StackOverflowError
this is because each recursive call of the function is fully evaluated
def sum(ints: List[Int], accum: Int): Int = ints match {
case Nil => accum
case x :: tail => sum(tail, accum + x)
}
DISCARD
EXEC
MULTI
UNWATCH
WATCH key [key ...]
Syntax
DnsCmd ServerName Command [Command Parameters]
ServerName:
IP address or host name -- remote or local DNS server
. -- DNS server on local machine
Command:
/ageallrecords Set the current time on all time stamps in a zone or node.
/clearcache Clear the DNS server cache.
/config Reset the DNS server or zone configuration.
/createbuiltindirectorypartitions Create the built-in DNS application directory partitions.
/createdirectorypartition Create a DNS application directory partition.
/deletedirectorypartition Delete a DNS application directory partition.
/directorypartitioninfo List information about a DNS application directory partition.
/enlistdirectorypartition Add a DNS server to the replication set of a DNS application directory partition.
/enumdirectorypartitions List the DNS application directory partitions for a server.
/enumrecords List the resource records in a zone.
/enumzones List the zones hosted by the specified server.
/exportsettings Write server configuration information to a text file. NEW in Server 2012
%systemroot%\system32\dns\DnsSettings.txt
/info Get server information.
/ipvalidate Validate remote DNS servers. NEW in Server 2008
/nodedelete Delete all records for a node in a zone.
/recordadd Add a resource record to a zone.
/recorddelete Remove a resource record from a zone.
/resetforwarders Set DNS servers to forward recursive queries.
/resetlistenaddresses Set server IP addresses to serve DNS requests.
/startscavenging Initiate server scavenging.
/statistics Query or clear server statistics data.
/unenlistdirectorypartition Remove a DNS server from the replication set of a DNS application directory partition.
/writebackfiles Save all zone or root-hint data to a file.
/zoneadd Create a new zone on the DNS server.
/zonechangedirectorypartition Change the directory partition on which a zone resides.
/zonedelete Deletes a zone from the DNS server.
/zoneexport Write the resource records of a zone to a text file.
/zoneinfo Display zone information.
/zonepause Pause a zone.
/zoneprint Display all records in the zone.
/zonerefresh Force a refresh of the secondary zone from the master zone.
/zonereload Reload a zone from its database.
/zoneresetmasters Change the master servers that provide zone transfer information to a secondary zone.
/zoneresetscavengeservers Change the servers that can scavenge a zone.
/zoneresetsecondaries Reset secondary information for a zone.
/zoneresettype Change the zone type.
/zoneresume Resume a zone.
/zoneupdatefromds Update an active directory integrated zone with data from active directory Domain Services (AD DS).
/zonewriteback Save zone data to a file.
Detailed Usage:
DnsCmd ServerName /AgeAllRecords ZoneName [NodeName] [/Tree] [/f]
Zone -- ZoneName
ZoneName -- FQDN of a zone
NodeName -- name or node or subtree in which to enable aging
- "@" for zone root OR
- FQDN of a node (name with a '.' at the end) OR
- single label for name relative to zone root
/Tree -- force aging on entire subtree of node
or entire zone if node not given
/f -- execute without asking for confirmation
DnsCmd ServerName /clearcache
DnsCmd ServerName /Config ZoneName Property Value
run DnsCmd /Config /? for more
DnsCmd ServerName /CreateBuiltinDirectoryPartitions Option
run DnsCmd /CreateBuiltinDirectoryPartitions /? for more
DnsCmd ServerName /CreateDirectoryPartition FQDN of partition
DnsCmd ServerName /DeleteDirectoryPartition FQDN of partition
DnsCmd ServerName /DirectoryPartitionInfo FQDN of partition
DnsCmd ServerName /EnlistDirectoryPartition FQDN of partition
DnsCmd ServerName /EnumDirectoryPartitions [/Custom]
DnsCmd ServerName /EnumRecords ZoneName NodeName [DataOptions] [ViewOptions]
run DnsCmd /EnumRecords /? for more
DnsCmd ServerName /EnumZones [Filter1 Filter2 ...]
run DnsCmd /EnumZones /? for more
DnsCmd ServerName /exportsettings
DnsCmd Server /Info [Property]
run DnsCmd /Info /? for more
DnsCmd ServerName /IpValidate Context [ZoneName] [IPAddress] ..]
Tests remote DNS server IP addresses
Context can be one of:
/DnsServers-- test that IPs are DNS servers
/Forwarders -- test IPs to use as forwarders
/RootHints -- test IPs to use as root hints
/ZoneMasters -- test IPs to use as master servers for the zone named ZoneName
DnsCmd ServerName /NodeDelete Zone NodeName [/Tree] [/f]
run DnsCmd /NodeDelete /? for more
DnsCmd ServerName /RecordAdd Zone NodeName [/Aging] [/OpenAcl] [/CreatePTR] [Ttl] RRType RRData
run DnsCmd /RecordAdd /? for more
DnsCmd ServerName /RecordDelete Zone NodeName RRType RRData [/f]
run DnsCmd /RecordDelete /? for more
DnsCmd ServerName /ResetForwarders [IPAddress] ...] [ /[No]Slave ] [/TimeOut Time]
run DnsCmd /ResetForwarders /? for more
DnsCmd ServerName /ResetListenAddresses [ListenAddress] ...]
ListenAddress -- an IP address belonging to the DNS server
Default: listen to all server IP Address(es) for DNS requests
DnsCmd ServerName /startscavenging
DnsCmd ServerName /Statistics [StatId | /Clear]
run DnsCmd /RecordDelete /? for a list of StatIds
DnsCmd ServerName /UnenlistDirectoryPartition FQDN of partition
DnsCmd ServerName /WriteBackFiles [ZoneName]
ZoneName -- FQDN of a zone whose datafile to be written back
Default: write back datafile for all dirty zones
DnsCmd ServerName /ZoneAdd ZoneName ZoneType [Options]
ZoneName -- FQDN of zone
run DnsCmd /ZoneAdd /? for more
DnsCmd ServerName /ZoneChangeDirectoryPartition ZoneName NewPartition
ZoneName -- FQDN of zone to move to new partition
NewPartition -- FQDN of new directory partition or one of:
/domain - domain directory partition
/forest - forest directory partition
/legacy - legacy directory partition
DnsCmd ServerName /ZoneDelete ZoneName [/DsDel] [/f]
/DsDel -- Delete Zone from DS
/f -- Execute without asking for confirmation
Default: delete zone from DNS sever, but NOT from DS
DnsCmd ServerName /ZoneExport ZoneName ZoneExportFile (%systemroot%\system32\dns)
ZoneName -- FQDN of zone to export
/Cache -- export cache
DnsCmd Server /ZoneInfo ZoneName [Property]
Property -- zone property to view
Examples:
AllowUpdate
DsIntegrated
Aging
RefreshInterval
NoRefreshInterval
DnsCmd ServerName /ZonePause ZoneName
DnsCmd ServerName /ZonePrint [ZoneName] [/Detail]
ZoneName -- name of the zone (use ..Cache for DNS server cache)
/Detail -- explicit RPC node contents
DnsCmd ServerName /ZoneResetType ZoneName Property [Options]
ZoneName -- FQDN of zone
run DnsCmd /ZoneResetType /? for more
DnsCmd ServerName /ZoneRefresh ZoneName
DnsCmd ServerName /ZoneReload ZoneName
DnsCmd ServerName /ZoneResetMasters ZoneName [/Local] [Server IPs]
/Local -- Set the local master list for DS integrated zones.
Server IPs -- List of one or more IP addresses of master servers for
this zone. Masters may include the primary or other secondaries
for the zone, but should not make the replication graph cyclic.
DnsCmd ServerName /ZoneResetScavengeServers ZoneName [Server IPs]
Server IPs -- list of one or more IP addresses of servers to scavenge
this zone; if no addresses given ALL servers hosting this zone
will be allowed to scavenge the zone.
DnsCmd ServerName /ZoneResetSecondaries ZoneName
[Security] [SecondaryIPAddress] ...]
[Notify] [NotifyIPAddress] ...]
run DnsCmd /ZoneResetSecondaries /? for more
DnsCmd ServerName /ZoneResume ZoneName
DnsCmd ServerName /ZoneUpdateFromDs ZoneName
DnsCmd ServerName /ZoneWriteBack ZoneName
DNSCMD may be removed in a future version of Windows, Microsoft recommend moving over to the DNS cmdlets in PowerShell (Get-command -module DnsServer).
Examples
Backup Zone1.com in an Active Directory-integrated zone:
dnscmd DC1 /zoneexport Zone1.com backup\zone1.com.dns.bak
This will create a file in %systemroot%\system32\dns\backup
ALTER TABLE
ADD
ALTER TABLE
ALTER
ALTER TABLE
DROP
ALTER TABLE
ADD COLUMN
INSERT INTO
VALUES (DEFAULT,
--
INSERT INTO
VALUES (
Syntax
COMPRESS [-R] [-D] [-S] [ -Z | -ZX ] Source Destination
COMPRESS -R [-D] [-S] [ -Z | -ZX ] Source [Destination]
Key
-R Rename compressed files.
-D Update compressed files only if out of date.
-S Suppress copyright information.
-ZX LZX compression. This is default compression.
-Z MS-ZIP compression.
Source Source file specification. Wildcards can be used.
Destination
Destination file | path specification.
Destination can be a directory.
If Source is multiple files and -r is not specified, Destination must be a directory.
Examples:
COMPRESS demo.txt compressed.txt
COMPRESS -R *.*
COMPRESS -R *.exe *.dll compressed_dir
EXPLAIN query;
EXPLAIN ANALYZE query;
ANALYZE table_name;
C-x C-f "find" file i.e. open/create a file in buffer
C-x C-s save the file
C-x C-w write the text to an alternate name
C-x C-v find alternate file
C-x i insert file at cursor position
C-x b create/switch buffers
C-x C-b show buffer list
C-x k kill buffer
C-z suspend emacs
C-X C-c close down emacs
C-f forward char
C-b backward char
C-p previous line
C-n next line
M-f forward one word
M-b backward one word
C-a beginning of line
C-e end of line
C-v one page up
M-v scroll down one page
M-< beginning of text
M-> end of text
M-n repeat the following command n times
C-u repeat the following command 4 times
C-u n repeat n times
C-d delete a char
M-d delete word
M-Del delete word backwards
C-k kill line
C-Space Set beginning mark (for region marking for example)
C-W "kill" (delete) the marked region
M-W copy the marked region
C-y "yank" (paste) the copied/killed region/line
M-y yank earlier text (cycle through kill buffer)
C-x C-x exchange cursor and mark
C-t transpose two chars
M-t transpose two words
C-x C-t transpose lines
M-u make letters uppercase in word from cursor position to end
M-c simply make first letter in word uppercase
M-l opposite to M-u
C-g quit the running/entered command
C-x u undo previous action
M-x revert-buffer RETURN
(insert like this) undo all changes since last save
M-x recover-file RETURN
Recover text from an autosave-file
M-x recover-session RETURN
if you edited several files
C-h c which command does this keystroke invoke
C-h k which command does this keystroke invoke and what does it do?
C-h l what were my last 100 typed keys
C-h w what key-combo does this command have?
C-h f what does this function do
C-h v what\'s this variable and what is it\'s value
C-h b show all keycommands for this buffer
C-h t start the emacs tutorial
C-h i start the info reader
C-h C-k start up info reader and go to a certain key-combo point
C-h F show the emacs FAQ
C-h p show infos about the Elisp package on this machine
C-s Search forward
C-r search backward
C-g return to where search started (if you are still in search mode)
M-% query replace
Space or y replace this occurence
Del or n don\'t replace
. only replace this and exit (replace)
, replace and pause (resume with Space or y)
! replace all following occurences
^ back to previous match
RETURN or q quit replace
^ beginning of line
$ end of line
. single char
.* group or null of chars
\< beginning of a word
\> end of a word
[] every char inside the backets (for example [a-z] means every small letter)
M C-s RETURN search for regular expression forward
M C-r RETURN search for regular expression backward
M C-s incremental search
C-s repeat incremental search
M C-r incremental search backwards
C-r repeat backwards
M-x query-replace-regexp
search and replace
C-x 2 split window vertically
C-x o change to other window
C-x 0 delete window
C-x 1 close all windows except the one the cursors in
C-x ^ enlarge window
M-x shrink-window
command says it ;-)
M C-v scroll other window
C-x 4 f find file in other window
C-x 4 o change to other window
C-x 4 0 kill buffer and window
C-x 5 2 make new frame
C-x 5 f find file in other frame
C-x 5 o change to other frame
C-x 5 0 close this frame
C-x r m set a bookmark at current cursor pos
C-x r b jump to bookmark
M-x bookmark-rename
M-x bookmark-delete
M-x bookmark-save
C-x r l list bookmarks
d mark bookmark for deletion
r rename bookmark
s save all listed bookmarks
f show bookmark the cursor is over
m mark bookmarks to be shown in multiple window
v show marked bookmarks (or the one the cursor is over)
t toggle listing of the corresponding paths
w path to this file
x delete marked bookmarks
q quit bookmark list
M-x bookmark-write
write all bookmarks in given file
M-x bookmark-load
load bookmark from given file
M-x shell starts shell modus
C-c C-c same as C-c under unix (stop running job)
C-d delete char forward
C-c C-d Send EOF
C-c C-z suspend job (C-z under unix)
M-p show previous commands
C-x d start up dired
C (large C) copy
d mark for erase
D delete right away
e or f open file or directory
g reread directory structure from file
G change group permissions (chgrp)
k delete line from listing on screen (don\'t actually delete)
m mark with *
n move to next line
o open file in other window and go there
C-o open file in other window but don\'t change there
P print file
q quit dired
Q do query-replace in marked files
R rename file
u remove mark
v view file content
x delete files marked with D
z compress file
M-Del remove all marks (whatever kind)
~ mark backup files (name~ files) for deletion
*/ mark directory with * (C-u * removes that mark again)
= compare this file with marked file
M-= compare this file with it\'s backup file
! apply shell command to this file
M-} change to the next file marked with * od D
M-{ change to the previous file marked with * od D
% d mark files described through regular expression for deletion
% m mark files described through regular expression for deletion (with *)
changed to next dir change to previous dir
s toggle between sorting by name or date
M-x speedbar starts up a separate window with a directory view
M-x telnet starts up telnet-modus
C-d either delete char or send EOF
C-c C-c stop running job (similar to C-c under unix)
C-c C-d send EOF
C-c C-o clear output of last command
C-c C-z suspend execution of command
C-c C-u kill line backwards
M-p recall previous command
M-s center line
M-S center paragraph
M-x center-region
C-x ( start macro definition
C-x ) end of macro definition
C-x e execute last defined macro
M-n C-x e execute last defined macro n times
M-x name-last-kbd-macro
give name to macro (for saving)
M-x insert-keyboard-macro
save named macro into file
M-x load-file
load macro
M-x macroname
execute macroname
M C-\ indent region between cursor and mark
M-m move to first (non-space) char in this line
M-^ attach this line to previous
M-; formatize and indent comment
M-a beginning of statement
M-e end of statement
M C-a beginning of function
M C-e end of function
C-c RETURN Set cursor to beginning of function and mark at the end
C-c C-q indent the whole function according to indention style
C-c C-a toggle modus in which after electric signs (like {}:\';./*) emacs does the indention
C-c C-d toggle auto hungry mode in which emacs deletes groups of spaces with one del-press
C-c C-u go to beginning of this preprocessor statement
C-c C-c comment out marked area
M-x outline-minor-mode
collapses function definitions in a file to a mere {...}
M-x show-subtree
If you are in one of the collapsed functions, this un-collapses it
M-. (Meta dot) If you are in a function call, this will take you to it\'s definition
M-x tags-search ENTER
Searches through all you etaged
M-, (Meta comma) jumps to the next occurence for tags-search
M-x tags-query-replace yum.
This lets you replace some text in all the tagged files
M-x gdb starts up gdm in an extra window
C-x v d show all registered files in this dir
C-x v = show diff between versions
C-x v u remove all changes since last checkin
C-x v ~ show certain version in different window
C-x v l print log
C-x v i mark file for version control add
C-x v h insert version control header into file
C-x v r check out named snapshot
C-x v s create named snapshot
C-x v a create changelog file in gnu-style
redis-cli
redis-cli -h host
redis-cli -h host -p port
redis-cli -a password
redis-cli redis_command
redis-cli KEYS "prefix:*"
redis-cli DEL abc
(xs zip ys) map { case (x,y) => x*y } GOOD
(xs zip ys) map( (x,y) => x*y ) BAD
BAD
val v42 = 42
Some(3) match {
case Some(v42) => println("42")
case _ => println("Not 42")
}
v42
" with backticks is interpreted as the existing val v42, and “Not 42” is printed.
GOOD
val v42 = 42
Some(3) match {
case Some(v42
) => println("42")
case _ => println("Not 42")
}
Thus, the value contained within UppercaseVal is checked against 3, and “Not 42” is printed.
GOOD
val UppercaseVal = 42
Some(3) match {
case Some(UppercaseVal) => println("42")
case _ => println("Not 42")
}
This will maintain the original value passed into the match function, using the '@' symbol, and print "Matched Some(3)"
Some(3) match {
case foundSome @ Some(_) => println("Matched " + foundSome)
case _ => println("Matched nothing")
}
This method allows you to match on any combination of properties of a case class
case class Example(a: Int, b: String, c: Boolean)
Example(1, "word", true) match {
case Example(3, _, _) => println("Matches any Example where a = 3")
case Example(_, "foo", _) => println("Matches any Example where b = foo")
case Example(_, _, false) => println("Matches any Example where c = false")
case Example(1, "word", true) => println("Matches our Example")
case Example(_, _, _) => println("Matches any other Example")
}
prctl ${PID}
prctl -P ${PID}
prctl -n process.max-file-descriptor ${PID}
wc -w /path/to/foo.txt
cat /path/to/foo.txt | wc -w
wc -l /path/to/foo.txt
cat /path/to/foo.txt | wc -l
wc -c /path/to/foo.txt
cat /path/to/foo.txt | wc -c
ls -l | wc -l
wc
in a shell script and need to compare the output with an int you can
ls -l | wc -l | xargs
xctool -project YourProject.xcodeproj -scheme YourScheme build
xctool -workspace YourWorkspace.xcworkspace -scheme YourScheme build
xctool -workspace YourWorkspace.xcworkspace -scheme YourScheme clean build test
import scala.collection._
import scala.collection.Vector
import scala.collection.{Vector, Sequence}
import scala.collection.{Vector => Vec28}
import java.util.{Date => _, _}
package pkg at start of file
package pkg { ... }
def factorial(n) :
if n == 0 :
return 1
else :
return n * factorial(n-1)
def gcd(x, y) :
if y == 0 :
return x
else :
return gcd(y, x%y)
dict -I
dict -d fd-eng-nld understand
dict -D
sudo pip install percol
ps aux | percol | awk '{ print $2 }'
ps aux | percol | awk '{ print $2 }' | xargs kill
wacaw filename
wacaw --video filename -D duration_in_seconds
wacaw -x width -y height filename
wacaw --to-clipboard
wacaw -L
exec > foo.log
exec > foo.log 2>&1
exec > >(tee -ia foo.log)
exec 2> >(tee -ia foo.log >&2)
ObjectName className {
Sets everything below it to be private.
private:
Declaration of variables
int a;
string b;
Implement any private / helper functions below
Sets everything below it to be public.
public:
Constructor
structName(new_a, new_b) {
a = new_a;
b = new_b;
}
accessors or getters functions
int getA() {
return a;
}
string getB() {
return b;
}
mutators or setter functions
void setA(int new_a) {
a = new_a;
}
void setB(int new_b) {
b = new_b;
}
Implement any public functions below
};
ObjectName v = structName(5, "Hello"); Creates a struct via the constructor
std::cout << v.a << " " << v.b << std::endl; Prints to console "5 Hello"
dscacheutil -flushcache
killall -HUP mDNSResponder
dscacheutil -statistics
Syntax
DISPLAYSWITCH /Option
Options
/internal Switch to use the primary display only.
1 All other connected displays will be disabled.
/clone The primary display will be mirrored on a second screen.
2
/extend Expand the Desktop to a secondary display.
3 This allows one desktop to span multiple displays. (Default).
/external Switch to the external display only (second screen).
4 The current main display will be disabled.
Running DisplaySwitch.exe without any options will open a GUI.
The command is located at: "%SystemRoot%\System32\DisplaySwitch.exe"
Examples
Mirror the current Desktop on a secondary display:
C:\> DisplaySwitch /clone
Extend the Desktop to a secondary display:
C:\> DisplaySwitch 3
crypt -e fileToEncrypt outputFile
crypt -d fileToDecrypt outputFile
convert original-image.jpg -resize 100x converted-image.jpg
convert original-image.jpg -resize x100 converted-image.jpg
convert original-image.jpg -resize 100x100 converted-image.jpg
convert original-image.jpg -resize 100x converted-image.png
for file in ls original/image/path/
;
do new_path=${file%.*};
new_file=basename $new_path
;
convert $file -resize 150 conerted/image/path/$new_file.png;
done
convert flower.jpg -font courier -fill white -pointsize 20 -annotate +50+50 'Flower' flower_annotate1.jpg
convert flower.jpg -crop 128×128+50+50 flower_crop.jpg
convert flower.jpg -rotate 45 flower_rotate45.jpg
convert -border 1x1 -bordercolor "#FFFFFF" image.png new-image.png
convert -quality 70 image.png new_image.jpg
sudo sockstat -l
tcpdump -i eth0
tcpdump host 173.194.40.120
tcpdump -nn -i any host 173.194.40.120 and port 80
tcpdump -i -A any host 173.194.40.120 and port 80 | grep 'User-Agent'
ngrep 'User-Agent' host 173.194.40.120 and port 80
tcpdump 'host ( 8.8.8.8 or 173.194.40.127 ) and port 80' -i any
tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0'
tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-fin) != 0 and not src and dst net local_addr'
tcpdump 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'
tcpdump -w file.cap
tcpdump -r file.cap
tcpdump -x
tcpdump -X
Dump and display certification authority (CA) configuration information, configure Certificate Services, back up and restore CA components, verify certificates, key pairs or certificate chains.
Syntax:
Dump (read config information) from a certificate file
CertUtil [Options] [-dump] [File]
Options: [-f] [-silent] [-split] [-p Password] [-t Timeout]
Parse ASN.1 file
CertUtil [Options] -asn File
Options: [-f] [decoding_type]
Decode a Hex-encoded file to binary
CertUtil [-f] [-v] -decodehex InFile OutFile
Decode Base64-encoded file to binary
CertUtil [-f] [-v] -decode InFile OutFile
Encode a binary file to Base64
CertUtil [-f] [-v] -encode InFile OutFile [-UnicodeText]
Encode a file as Hex
CertUtil [-f] [-v] -encodehex InFile OutFile Format
Hex encoded files are around 3x larger than base64
Examples of the Hex formats:
certutil -encodehex -f strings64.exe strings12.hex 12 - One line HEX value without spaces, columns, addresses,
certutil -encodehex -f strings64.exe strings5.hex 5 - without addresses.
certutil -encodehex -f strings64.exe strings2.hex 2 - pure binary (rarely used).
certutil -encodehex -f strings64.exe strings1.hex 1 - base64 without certificate headers.
certutil -encodehex -f strings64.exe strings0.hex 0 - base64 with certificate headers.
certutil -encodehex -f strings64.exe strings4.hex 4 - in columns with spaces, without the characters and the addresses.
certutil -encodehex -f strings64.exe strings7.hex 7 - base64 - X509 without headers (slightly bigger than the normal b64)
certutil -encodehex -f strings64.exe strings8.hex 8 - base64 - x509 with headers.
Deny pending request
CertUtil [Options] -deny RequestId
Options: [-v] [-config Machine\CAName]
Resubmit pending request
CertUtil [Options] -resubmit RequestId
Options: [-v] [-config Machine\CAName]
Set attributes for pending request
CertUtil [Options] -setattributes RequestId AttributeString
Options: [-v] [-config Machine\CAName]
RequestId : Numeric Request Id of pending request.
AttributeString : Request Attribute name and value pairs.
Names and values are colon separated. Multiple name, value pairs are newline separated.
Example: "CertificateTemplate:User\nEMail:User@Domain.com"
Each "\n" sequence is converted to a newline separator.
Set extension for pending request
CertUtil [Options] -setextension RequestId ExtensionName Flags {Long | Date | String | @InFile}
Options: [-v] [-config Machine\CAName]
RequestId : Numeric Request Id of a pending request.
ExtensionName : ObjectId string of the extension.
Flags : 0 is recommended. 1 makes the extension critical, 2 disables it, 3 does both.
If the last parameter is numeric, it is taken as a Long. If it can be parsed as a date, it is taken as a Date.
If it starts with '@', the rest of the token is the filename containing binary data or an ascii-text hex dump.
Anything else is taken as a String.
Revoke Certificate
CertUtil [Options] -revoke SerialNumber [Reason]
Options: [-v] [-config Machine\CAName]
SerialNumber: Comma separated list of certificate serial numbers to revoke
Reason: numeric or symbolic revocation reason
0: CRL_REASON_UNSPECIFIED: Unspecified (default)
1: CRL_REASON_KEY_COMPROMISE: Key Compromise
2: CRL_REASON_CA_COMPROMISE: CA Compromise
3: CRL_REASON_AFFILIATION_CHANGED: Affiliation Changed
4: CRL_REASON_SUPERSEDED: Superseded
5: CRL_REASON_CESSATION_OF_OPERATION: Cessation of Operation
6: CRL_REASON_CERTIFICATE_HOLD: Certificate Hold
8: CRL_REASON_REMOVE_FROM_CRL: Remove From CRL
-1: Unrevoke: Unrevoke
Display current certificate disposition
CertUtil [Options] -isvalid SerialNumber | CertHash
Options: [-v] [-config Machine\CAName]
Get default configuration string
CertUtil [Options] -getconfig
Options: [-v] [-config Machine\CAName]
Ping Active Directory Certificate Services Request interface
CertUtil [Options] -ping [MaxSecondsToWait | CAMachineList]
Options: [-v] [-config Machine\CAName]
Request interface CAMachineList -- Comma-separated CA machine name list
For a single machine, use a terminating comma
Displays the site cost for each CA machine
Ping Active Directory Certificate Services Admin interface
CertUtil [Options] -pingadmin [MaxSecondsToWait | CAMachineList]
Options: [-v] [-config Machine\CAName]
Request interface CAMachineList -- Comma-separated CA machine name list
For a single machine, use a terminating comma
Displays the site cost for each CA machine
Display CA Information
CertUtil [Options] -CAInfo [InfoName [Index | ErrorCode]]
Options: [-v] [-config Machine\CAName]
InfoName : indicates the CA property to display. Use "*" for all properties.
Index : optional zero-based property index
ErrorCode : numeric error code [-f] [-split] [-config Machine\CAName]
Retrieve the CA's certificate
CertUtil [Options] -ca.cert OutCACertFile [Index]
Options: [-f] [-v] [-split] [-config Machine\CAName]
OutCACertFile: output file
Index: CA certificate renewal index (defaults to most recent)
Retrieve the CA's certificate chain
CertUtil [Options] -ca.chain OutCACertChainFile [Index]
Options: [-f] [-v] [-split] [-config Machine\CAName]
OutCACertChainFile: output file
Index: CA certificate renewal index (defaults to most recent)
Get CRL
CertUtil [Options] -GetCRL OutFile [Index] [delta]
Options: [-f] [-v] [-split] [-config Machine\CAName]
Index : CRL index or key index (defaults to CRL for newest key)
delta : delta CRL (default is base CRL)
Publish new CRLs [or delta CRLs only]
CertUtil [Options] -CRL [dd:hh | republish] [delta]
Options: [-v] [-split] [-config Machine\CAName]
dd:hh -- new CRL validity period in days and hours
republish -- republish most recent CRLs
delta -- delta CRLs only (default is base and delta CRLs)
Shutdown Active Directory Certificate Services
CertUtil [Options] -shutdown
Options: [-v] [-config Machine\CAName]
Install Certification Authority certificate
CertUtil [Options] -installCert [CACertFile]
Options: [-f] [-v] [-silent] [-config Machine\CAName]
Renew Certification Authority certificate
CertUtil [Options] -renewCert [ReuseKeys] [Machine\ParentCAName]
Options: [-f] [-v] [-silent] [-config Machine\CAName]
Use -f to ignore an outstanding renewal request, and generate a new request.
Dump Certificate Schema
CertUtil [Options] -schema [Ext | Attrib | CRL]
Options: [-v] [-split] [-config Machine\CAName]
Ext : Extension table
Attrib : Attribute table
CRL : CRL table
Defaults to Request and Certificate table.
Dump Certificate View
CertUtil [Options] -view [Queue | Log | LogFail | Revoked | Ext | Attrib | CRL] [csv]
Options: [-v] [-silent] [-split] [-config Machine\CAName] [-restrict RestrictionList] [-out ColumnList]
Queue : Request queue.
Log : Issued or revoked certificates, plus failed requests.
LogFail : Failed requests.
Revoked : Revoked certificates.
Ext : Extension table.
Attrib : Attribute table.
CRL : CRL table.
csv : Output as Comma Separated Values.
To display the StatusCode column for all entries: -out StatusCode
To display all columns for the last entry: -restrict "RequestId==$"
To display RequestId and Disposition for three requests:
-restrict "RequestId>=37,RequestId<40" -out "RequestId,Disposition"
To display Row Ids and CRL Numbers for all Base CRLs: -restrict "CRLMinBase=0" -out "CRLRowId,CRLNumber" CRL
To display Base CRL Number 3: -v -restrict "CRLMinBase=0,CRLNumber=3" -out "CRLRawCRL" CRL
To display the entire CRL table: CRL Use "Date[+|-dd:hh]" for date restrictions Use "now+dd:hh" for a date relative to the current time.
Dump Raw Database
CertUtil [Options] -db
Options: [-v] [-config Machine\CAName] [-restrict RestrictionList] [-out ColumnList]
Delete server database row
CertUtil [Options] -deleterow RowId | Date [Request | Cert | Ext | Attrib | CRL]
Options: [-f] [-v] [-config Machine\CAName]
Request : Failed and pending requests (submission date)
Cert : Expired and revoked certificates (expiration date)
Ext : Extension table Attrib: Attribute table
CRL : CRL table (expiration date)
To delete failed and pending requests submitted by January 22, 2001: 1/22/2001 Request
To delete all certificates that expired by January 22, 2001: 1/22/2001 Cert
To delete the certificate row, attributes and extensions for RequestId 37: 37
To delete CRLs that expired by January 22, 2001: 1/22/2001 CRL [-f] [-config Machine\CAName]
Backup Active Directory Certificate Services
CertUtil [Options] -backup BackupDirectory [Incremental] [KeepLog]
Options: [-f] [-v] [-config Machine\CAName] [-p Password]
BackupDirectory : directory to store backed up data
Incremental : perform incremental backup only (default is full backup)
KeepLog : preserve database log files (default is to truncate log files)
Backup Active Directory Certificate Services database
CertUtil [Options] -backupDB BackupDirectory [Incremental] [KeepLog]
Options: [-f] [-v] [-config Machine\CAName]
BackupDirectory : directory to store backed up data
Incremental : perform incremental backup only (default is full backup)
KeepLog : preserve database log files (default is to truncate log files)
Backup Active Directory Certificate Services certificate and private key
CertUtil [Options] -backupKey BackupDirectory
Options: [-f] [-v] [-config Machine\CAName] [-p Password] [-t Timeout]
BackupDirectory : directory to store backed up PFX file
Restore Active Directory Certificate Services
CertUtil [Options] -restore BackupDirectory
Options: [-f] [-v] [-config Machine\CAName] [-p Password]
BackupDirectory : directory containing data to be restored
Restore Active Directory Certificate Services database
CertUtil [Options] -restoreDB BackupDirectory
Options: [-f] [-v] [-config Machine\CAName] [-p Password]
BackupDirectory : directory containing database files to be restored
Restore Active Directory Certificate Services certificate and private key
CertUtil [Options] -restoreKey BackupDirectory | PFXFile
Options: [-f] [-v] [-config Machine\CAName] [-p Password]
BackupDirectory : directory containing PFX file to be restored
PFXFile : PFX file to be restored
Import certificate and private key
CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers] [-csp Provider]
Options: [-f] [-v] [-user] [-p Password]
CertificateStoreName : Certificate store name. See -store.
PFXFile : PFX file to be imported
Modifiers : Comma separated list of one or more of the following:
AT_SIGNATURE : Change the KeySpec to Signature
AT_KEYEXCHANGE : Change the KeySpec to Key Exchange
NoExport : Make the private key non-exportable
NoCert : Do not import the certificate
NoChain : Do not import the certificate chain
NoRoot : Do not import the root certificate
Protect : Protect keys with password
NoProtect : Do not password protect keys
Defaults to personal machine store.
Display dynamic file List
CertUtil [Options] -dynamicfilelist
Options: [-v] [-config Machine\CAName]
Display database locations
CertUtil [Options] -databaselocations
Options: [-v] [-config Machine\CAName]
Generate and display cryptographic hash over a file.
CertUtil [Options] -hashfile InFile [HashAlgorithm]
Options: [-v]
Dump certificate store
CertUtil [Options] -store [CertificateStoreName [CertId [OutputFile]]]
Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-silent] [-split] [-dc DCName]
CertificateStoreName : Certificate store name.
CertId : Certificate or CRL match token. This can be a serial number, an SHA-1 certificate, CRL, CTL or public key hash, a numeric cert index (0, 1, and so on), a numeric CRL index (.0, .1, and so on), a numeric CTL index (..0, ..1, and so on), a public key, signature or extension ObjectId, a certificate subject Common Name, an e-mail address, UPN or DNS name, a key container name or CSP name, a template name or ObjectId, an EKU or Application Policies ObjectId, or a CRL issuer Common Name. These can result in multiple matches.
OutputFile : File to save matching cert.
Use -user to access a user store instead of a machine store.
Use -enterprise to access a machine enterprise store.
Use -service to access a machine service store.
Use -grouppolicy to access a machine group policy store.
Add certificate to store
CertUtil [Options] -addstore CertificateStoreName InFile
Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-dc DCName]
CertificateStoreName : Certificate store name. See -store.
InFile : Certificate or CRL file to add to store.
Delete certificate from store
CertUtil [Options] -delstore CertificateStoreName CertId
Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-dc DCName]
CertificateStoreName : Certificate store name. See -store.
CertId : Certificate or CRL match token. See -store.
Verify certificate in store
CertUtil [Options] -verifystore CertificateStoreName [CertId]
Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-silent] [-split] [-dc DCName] [-t Timeout]
CertificateStoreName : Certificate store name. See -store.
CertId : Certificate or CRL match token. See -store.
Repair key association or update certificate properties or key security descriptor
CertUtil [Options] -repairstore CertificateStoreName CertIdList [PropertyInfFile | SDDLSecurityDescriptor]
Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-silent] [-split] [-csp Provider]
CertificateStoreName : Certificate store name. See -store.
CertIdList : comma separated list of Certificate or CRL match tokens. See -store CertId description.
PropertyInfFile : INF file containing external properties:
Dump certificate store
CertUtil [Options] -viewstore [CertificateStoreName [CertId [OutputFile]]]
Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-dc DCName]
CertificateStoreName : Certificate store name.
CertId : Certificate or CRL match token. This can be a serial number, an SHA-1 certificate, CRL, CTL or public key hash, a numeric cert index (0, 1, and so on), a numeric CRL index (.0, .1, and so on), a numeric CTL index (..0, ..1, and so on), a public key, signature or extension ObjectId, a certificate subject Common Name, an e-mail address, UPN or DNS name, a key container name or CSP name, a template name or ObjectId, an EKU or Application Policies ObjectId, or a CRL issuer Common Name. These can result in multiple matches.
OutputFile : file to save matching cert.
Use -user to access a user store instead of a machine store.
Use -enterprise to access a machine enterprise store.
Use -service to access a machine service store.
Use -grouppolicy to access a machine group policy store.
Delete certificate from store
CertUtil [Options] -viewdelstore [CertificateStoreName [CertId [OutputFile]]]
Options: [-f] [-v] [-enterprise] [-user] [-GroupPolicy] [-dc DCName]
CertificateStoreName : Certificate store name.
CertId : Certificate or CRL match token. This can be a serial number, an SHA-1 certificate, CRL, CTL or public key hash, a numeric cert index (0, 1, and so on), a numeric CRL index (.0, .1, and so on), a numeric CTL index (..0, ..1, and so on), a public key, signature or extension ObjectId, a certificate subject Common Name, an e-mail address, UPN or DNS name, a key container name or CSP name, a template name or ObjectId, an EKU or Application Policies ObjectId, or a CRL issuer Common Name. These can result in multiple matches.
OutputFile : File to save matching cert.
Use -user to access a user store instead of a machine store.
Use -enterprise to access a machine enterprise store.
Use -service to access a machine service store.
Use -grouppolicy to access a machine group policy store.
Publish certificate or CRL to Active Directory
CertUtil [Options] -dsPublish CertFile [NTAuthCA | RootCA | SubCA | CrossCA | KRA | User | Machine]
Options: [-f] [-v] [-user] [-dc DCName]
CertUtil [Options] -dsPublish CRLFile [DSCDPContainer [DSCDPCN]] [-f] [-user] [-dc DCName]
Options: [-f] [-v] [-user] [-dc DCName]
CertFile : certificate file to publish
NTAuthCA : Publish cert to DS Enterprise store
RootCA : Publish cert to DS Trusted Root store
SubCA : Publish CA cert to DS CA object
CrossCA : Publish cross cert to DS CA object
KRA : Publish cert to DS Key Recovery Agent object
User : Publish cert to User DS object
Machine : Publish cert to Machine DS object
CRLFile : CRL file to publish
DSCDPContainer : DS CDP container CN, usually the CA machine name
DSCDPCN : DS CDP object CN, usually based on the sanitized CA short name and key index
Use -f to create DS object.
Display AD templates
CertUtil [Options] -ADTemplate [Template]
Options: [-f] [-v] [-user] [-ut] [-mt] [-dc DCName]
Display Enrollment Policy templates
CertUtil [Options] -Template [Template]
Options: [-f] [-v] [-user] [-dc DCName] [-user] [-silent] [-PolicyServer URLOrId]
[-Anonymous] [-Kerberos] [-ClientCertificate ClientCertId] [-UserName UserName] [-p Password]
Display CAs for template
CertUtil [Options] -TemplateCAs Template
Options: [-f] [-v] [-user] [-dc DCName]
Display templates for CA
CertUtil [Options] -CATemplates [Template]
Options: [-f] [-v] [-user] [-ut] [-mt] [-config Machine\CAName] [-dc DCName]
Set, Verify or Delete CA site names
CertUtil [Options] -SetCASites [set] [Sitename]
CertUtil [Options] -SetCASites verify [Sitename]
CertUtil [Options] -SetCASites delete
Options: [-f] [-v] [-config Machine\CAName] [-dc DCName]
Use the -config option to target a single CA (Default is all CAs)
Sitename is allowed only when targeting a single CA
Use -f to override validation errors for the specified Sitename
Use -f to delete all CA site names
Display, add or delete enrollment server URLs associated with a CA
CertUtil [Options] -enrollmentServerURL [URL AuthenticationType [Priority] [Modifiers]]
CertUtil [Options] -enrollmentServerURL URL delete
Options: [-f] [-config Machine\CAName] [-dc DCName]
AuthenticationType: Specify one of the following client authentication methods while adding a URL:
Kerberos : Use Kerberos SSL credentials.
UserName : Use named account for SSL credentials.
ClientCertificate : Use X.509 Certificate SSL credentials.
Anonymous : Use anonymous SSL credentials.
delete : Delete the specified URL associated with the CA
Priority : Defaults to '1' if not specified when adding a URL
Modifiers : Comma separated list of one or more of the following:
AllowRenewalsOnly : Only renewal requests can be submitted to this CA via this URL
AllowKeyBasedRenewal : Allow use of a certificate that has no associated account in the AD.
This applies only with ClientCertificate and AllowRenewalsOnly Mode
Display AD CAs
CertUtil [Options] -ADCA [CAName]
Options: [-f] [-split] [-dc DCName]
Display Enrollment Policy CAs
CertUtil [Options] -CA [CAName | TemplateName]
Options: [-f] [-user] [-silent] [-split] [-PolicyServer URLOrId]
[-Anonymous] [-Kerberos] [-ClientCertificate ClientCertId] [-UserName UserName] [-p Password]
Display Enrollment Policy
CertUtil [Options] -Policy
Options: [-f] [-user] [-silent] [-split] [-PolicyServer URLOrId] [-Anonymous]
[-Kerberos] [-ClientCertificate ClientCertId] [-UserName UserName] [-p Password]
Display or delete Enrollment Policy Cache entries
CertUtil [Options] -PolicyCache [delete]
Options: [-f] [-user] [-PolicyServer URLOrId]
delete: delete Policy Server cache entries
-f: use -f to delete all cache entries
Display, add or delete Credential Store entries
CertUtil [Options] -CredStore [URL]
CertUtil [Options] -CredStore URL add
CertUtil [Options] -CredStore URL delete
Options: [-f] [-user] [-silent] [-Anonymous] [-Kerberos]
[-ClientCertificate ClientCertId] [-UserName UserName] [-p Password]
URL : target URL. Use * to match all entries. Use https:machine* to match a URL prefix.
add : add a Credential Store entry. SSL credentials must also be specified.
delete : delete Credential Store entries
-f : use -f to overwrite an entry or to delete multiple entries.
Install default certificate templates
CertUtil [Options] -InstallDefaultTemplates
Options: [-f] [-v] [-dc DCName]
Display or delete URL cache entries
CertUtil [Options] -URLCache [URL | CRL | * [delete]]
Options: [-f] [-v] [-split]
URL : Cached URL
CRL : Operate on all cached CRL URLs only
delete : Delete relevant URLs from the current user's local cache
-f : Force fetch of a specific URL and update the cache.
-split : Dump the file to disk
-v : Will display the whole IE internet history and cache file locations (…\Content.IE5…)
e.g.
certutil.exe -urlcache -split -f "https:download.sysinternals.com/files/SysinternalsSuite.zip" pstools.zip
Pulse autoenrollment events
CertUtil [Options] -pulse
Options: [-v] [-user]
Display Active Directory computer object information
CertUtil [Options] -MachineInfo DomainName\MachineName$
Options: [-v]
Display domain controller information
CertUtil [Options] -DCInfo [Domain] [Verify | DeleteBad | DeleteAll]
Options: [-f] [-v] [-user] [-urlfetch] [-dc DCName] [-t Timeout]
Default is to display DC certs without verification.
Display Enterprise CA information
CertUtil [Options] -EntInfo DomainName\MachineName$
Options: [-f] [-v] [-user]
Display CA information
CertUtil [Options] -TCAInfo [DomainDN | -]
Options: [-f] [-v] [-enterprise] [-user] [-urlfetch] [-dc DCName] [-t Timeout]
Display smart card information
CertUtil [Options] -SCInfo [ReaderName [CRYPT_DELETEKEYSET]]
Options: [-v] [-silent] [-split] [-urlfetch] [-t Timeout]
CRYPT_DELETEKEYSET : Delete all keys on the smart card
Manage smart card root certificates
CertUtil [Options] -SCRoots update [+][InputRootFile] [ReaderName]
CertUtil [Options] -SCRoots save @OutputRootFile [ReaderName]
CertUtil [Options] -SCRoots view [InputRootFile | ReaderName]
CertUtil [Options] -SCRoots delete [ReaderName]
Options: [-f] [-split] [-p Password]
Verify public/private key set
CertUtil [Options] -verifykeys [KeyContainerName CACertFile]
Options: [-f] [-v] [-user] [-silent] [-config Machine\CAName]
KeyContainerName : Key container name of the key to verify. Defaults to machine keys. Use -user for user keys.
CACertFile : Signing or encryption certificate file
If no arguments are specified, each signing CA cert is verified against its private key.
This operation can only be performed against a local CA or local keys.
Verify certificate, CRL or chain
CertUtil [Options] -verify CertFile [ApplicationPolicyList | - [IssuancePolicyList]]
CertUtil [Options] -verify CertFile [CACertFile [CrossedCACertFile]]
CertUtil [Options] -verify CRLFile CACertFile [IssuedCertFile]
CertUtil [Options] -verify CRLFile CACertFile [DeltaCRLFile]
Options: [-f] [-v] [-enterprise] [-user] [-silent] [-split] [-urlfetch] [-t Timeout]
CertFile : Certificate to verify Application
PolicyList : Optional comma separated list of required Application Policy ObjectIds
IssuancePolicyList : Optional comma separated list of required Issuance Policy ObjectIds
CACertFile : Optional issuing CA certificate to verify against
CrossedCACertFile : optional certificate cross-certified by CertFile
CRLFile : CRL to verify IssuedCertFile: optional issued certificate covered by CRLFile
DeltaCRLFile : Optional delta CRL
If ApplicationPolicyList is specified, chain building is restricted to chains valid for
the specified Application Policies.
If IssuancePolicyList is specified, chain building is restricted to chains valid for the
specified Issuance Policies.
If CACertFile is specified, fields in CACertFile are verified against CertFile or CRLFile.
If CACertFile is not specified, CertFile is used to build and verify a full chain.
If CACertFile and CrossedCACertFile are both specified, fields in CACertFile and CrossedCACertFile
are verified against CertFile.
If IssuedCertFile is specified, fields in IssuedCertFile are verified against CRLFile.
If DeltaCRLFile is specified, fields in DeltaCRLFile are verified against CRLFile.
Verify AuthRoot or Disallowed Certificates CTL
CertUtil [Options] -verifyCTL CTLObject [CertDir] [CertFile]
Options: [-f] [-user] [-split]
CTLObject : Identifies the CTL to verify:
AuthRootWU : read AuthRoot CAB and matching certificates from the URL cache. Use -f to download from Windows Update instead.
DisallowedWU : read Disallowed Certificates CAB and disallowed certificate store file from the URL cache. Use -f to download from Windows Update instead.
AuthRoot : read registry cached AuthRoot CTL. Use with -f and a CertFile that is not already trusted to force updating the registry cached AuthRoot and Disallowed Certificate CTLs.
Disallowed : read registry cached Disallowed Certificates CTL. -f has the same behavior as with AuthRoot.
CTLFileName : file or http: path to CTL or CAB
CertDir : folder containing certificates matching CTL entries. An http: folder path must end with a path separator. If a folder is not specified with AuthRoot or Disallowed, multiple locations will be searched for matching certificates: local certificate stores, crypt32.dll resources and the local URL cache. Use -f to download from Windows Update when necessary.
Otherwise defaults to the same folder or web site as the CTLObject.
CertFile : file containing certificate(s) to verify. Certificates will be matched against CTL entries,
and match results displayed. Suppresses most of the default output.
Re-sign CRL or certificate
CertUtil [Options] -sign InFileList|SerialNumber|CRL OutFileList [StartDate+dd:hh]
[+SerialNumberList | -SerialNumberList | -ObjectIdList | @ExtensionFile] [-nullsign]
CertUtil [Options] -sign InFileList|SerialNumber|CRL OutFileList [#HashAlgorithm]
[+AlternateSignatureAlgorithm | -AlternateSignatureAlgorithm] [-nullsign]
Options: [-f] [-silent] [-Cert CertId]
InFileList : comma separated list of Certificate or CRL files to modify and re-sign
SerialNumber : Serial number of certificate to create. Validity period and other options must not be present.
CRL : Create an empty CRL. Validity period and other options must not be present.
OutFileList : comma separated list of modified Certificate or CRL output files. The number of files must match InFileList.
StartDate+dd:hh : new validity period: optional date plus; optional days and hours validity period;
If both are specified, use a plus sign (+) separator.
Use "now[+dd:hh]" to start at the current time. Use "never" to have no expiration date (for CRLs only).
SerialNumberList : Comma separated serial number list to add or remove
ObjectIdList : Comma separated extension ObjectId list to remove
@ExtensionFile : INF file containing extensions to update or remove:
HashAlgorithm : Name of the hash algorithm preceded by a # sign: #MD2 #MD4 #MD5 #SHA1 #SHA256 #SHA384 or #SHA512
AlternateSignatureAlgorithm : alternate Signature algorithm specifier
A minus sign causes serial numbers and extensions to be removed. A plus sign causes serial numbers to be added to a CRL.
When removing items from a CRL, the list can contain both serial numbers and ObjectIds.
A minus sign before AlternateSignatureAlgorithm causes the legacy signature format to be used.
A plus sign before AlternateSignatureAlgorithm causes the alternature signature format to be used.
If AlternateSignatureAlgorithm is not specified then the signature format in the certificate or CRL is used.
Create/delete web virtual roots and file shares
CertUtil [Options] -vroot [delete]
Create/delete web virtual roots for OCSP web proxy
CertUtil [Options] -vocsproot [delete]
Add an Enrollment Server application
CertUtil [Options] -addEnrollmentServer Kerberos | UserName | ClientCertificate [AllowRenewalsOnly] [AllowKeyBasedRenewal]
Options: [-f] [-config Machine\CAName]
Add an Enrollment Server application and application pool if necessary, for the specified CA.
This command does not install binaries or packages.
One of the following authentication methods with which the client connects to a Certificate Enrollment Server.
Kerberos : Use Kerberos SSL credentials
UserName : Use named account for SSL credentials
ClientCertificate : Use X.509 Certificate SSL credentials
AllowRenewalsOnly : Only renewal requests can be submitted to this CA via this URL
AllowKeyBasedRenewal : Allows use of a certificate that has no associated account in the AD.
This applies only with ClientCertificate and AllowRenewalsOnly mode.
Delete an Enrollment Server application
CertUtil [Options] -deleteEnrollmentServer Kerberos | UserName | ClientCertificate
Options: [-f] [-config Machine\CAName]
Delete an Enrollment Server application and application pool if necessary, for the specified CA.
This command does not remove binaries or packages.
One of the following authentication methods with which the client connects to a Certificate Enrollment Server.
Kerberos : Use Kerberos SSL credentials
UserName : Use named account for SSL credentials
ClientCertificate : Use X.509 Certificate SSL credentials
Add a Policy Server application
CertUtil [Options] -addPolicyServer Kerberos | UserName | ClientCertificate [KeyBasedRenewal]
Add a policy server application and application pool if necessary.
This command does not install binaries or packages.
One of the following authentication methods with which the client connects to a Certificate Policy Server.
Kerberos : Use Kerberos SSL credentials.
UserName : Use named account for SSL credentials.
ClientCertificate : Use X.509 Certificate SSL credentials.
KeyBasedRenewal : Only policies that contain KeyBasedRenewal templates are returned to the client.
This flag applies only for UserName and ClientCertificate authentication.
Delete a Policy Server application
CertUtil [Options] -deletePolicyServer Kerberos | UserName | ClientCertificate [KeyBasedRenewal]
Delete a policy server application and application pool if necessary.
This command does not remove binaries or packages.
One of the following authentication methods with which the client connects to a Certificate Policy Server.
Kerberos : Use Kerberos SSL credentials.
UserName : Use named account for SSL credentials.
ClientCertificate : Use X.509 Certificate SSL credentials.
KeyBasedRenewal : KeyBasedRenewal policy server.
Display ObjectId or set display name
CertUtil [Options] -oid ObjectId [DisplayName | delete [LanguageId [Type]]] [-f]
CertUtil [Options] -oid GroupId
CertUtil [Options] -oid AlgId | AlgorithmName [GroupId] [-f]
ObjectId : ObjectId to display or to add display name
GroupId : Decimal GroupId number for ObjectIds to enumerate
AlgId : Hexadecimal AlgId for ObjectId to look up
AlgorithmName : Algorithm Name for ObjectId to look up
DisplayName : Display Name to store in DS
delete : Delete display name
LanguageId : Language Id (defaults to current: 1033)
Type : DS object type to create: 1 for Template (default), 2 for Issuance Policy, 3 for Application Policy
Use -f to create DS object.
Display error code message text
CertUtil [-v] -error ErrorCode
Display registry value
CertUtil [Options] -getreg [{ca|restore|policy|exit|template|enroll|chain|PolicyServers}[ProgId]] [RegistryValueName]
Options: [-f] [-user] [-GroupPolicy] [-config Machine\CAName]
ca : Use CA's registry key
restore : Use CA's restore registry key
policy : Use policy module's registry key
exit : Use first exit module's registry key
template : Use template registry key (use -user for user templates)
enroll : Use enrollment registry key (use -user for user context)
chain : Use chain configuration registry key
PolicyServers : Use Policy Servers registry key
ProgId : Use policy or exit module's ProgId (registry subkey name)
RegistryValueName : registry value name (use "Name*" to prefix match)
Set registry value
CertUtil [Options] -setreg [{ca|restore|policy|exit|template|enroll|chain|PolicyServers}[ProgId]]
[RegistryValueName] Value
Options: [-f] [-user] [-GroupPolicy] [-config Machine\CAName]
ca : Use CA's registry key
restore : Use CA's restore registry key
policy : Use policy module's registry key
exit : Use first exit module's registry key
template : Use template registry key (use -user for user templates)
enroll : Use enrollment registry key (use -user for user context)
chain : Use chain configuration registry key
PolicyServers : Use Policy Servers registry key
ProgId : Use policy or exit module's ProgId (registry subkey name)
RegistryValueName : registry value name (use "Name*" to prefix match)
Value : new numeric, string or date registry value or filename.
If a numeric value starts with "+" or "-", the bits specified in the new value are set or cleared in the existing registry value. If a string value
starts with "+" or "-", and the existing value is a REG_MULTI_SZ value, the string is added to or removed from the existing registry value.
To force creation of a REG_MULTI_SZ value, add a "\n" to the end of the string value. If the value starts with "@", the rest of the value is the name of the file containing the hexadecimal text representation of a binary value.
If it does not refer to a valid file, it is instead parsed as [Date][+|-][dd:hh] -- an optional date plus or minus optional days and hours.
If both are specified, use a plus sign (+) or minus sign (-) separator.
Use "now+dd:hh" for a date relative to the current time.
Use "chain\ChainCacheResyncFiletime @now" to effectively flush cached CRLs.
Delete registry value
CertUtil [Options] -delreg [{ca|restore|policy|exit|template|enroll|chain|PolicyServers}[ProgId]]
[RegistryValueName]
Options: [-f] [-user] [-GroupPolicy] [-config Machine\CAName]
ca : Use CA's registry key
restore : Use CA's restore registry key
policy : Use policy module's registry key
exit : Use first exit module's registry key
template : Use template registry key (use -user for user templates)
enroll : Use enrollment registry key (use -user for user context)
chain : Use chain configuration registry key
PolicyServers : Use Policy Servers registry key
ProgId : Use policy or exit module's ProgId (registry subkey name)
RegistryValueName : registry value name (use "Name*" to prefix match)
Import user keys and certificates into server database for key archival
CertUtil [Options] -ImportKMS UserKeyAndCertFile [CertId]
Options: [-f] [-v] [-silent] [-split] [-config Machine\CAName] [-p Password] [-symkeyalg SymmetricKeyAlgorithm[,KeyLength]]
UserKeyAndCertFile : Data file containing user private keys and certificates to be archived.
This can be any of the following:
Exchange Key Management Server (KMS) export file
PFX file
CertId : KMS export file decryption certificate match token. See -store.
Use -f to import certificates not issued by the CA.
Import a certificate file into the database
CertUtil [Options] -ImportCert Certfile [ExistingRow]
Options: [-f] [-v] [-config Machine\CAName]
Use ExistingRow to import the certificate in place of a pending request for the same key.
Use -f to import certificates not issued by the CA. The CA might also need to be configured to support foreign certificate import: certutil -setreg ca\KRAFlags +KRAF_ENABLEFOREIGN
Retrieve archived private key recovery blob, generate a recovery script, or recover archived keys
CertUtil [Options] -GetKey SearchToken [RecoveryBlobOutFile]
CertUtil [Options] -GetKey SearchToken script OutputScriptFile
CertUtil [Options] -GetKey SearchToken retrieve | recover OutputFileBaseName
Options: [-f] [-v] [-UnicodeText] [-silent] [-config Machine\CAName] [-p Password]
[-ProtectTo SAMNameAndSIDList] [-csp Provider]
script : generate a script to retrieve and recover keys (default behavior if multiple matching recovery candidates are found, or if
the output file is not specified).
retrieve : retrieve one or more Key Recovery Blobs (default behavior if exactly one
matching recovery candidate is found, and if the output file is specified)
recover : retrieve and recover private keys in one step (requires Key Recovery Agent
certificates and private keys)
SearchToken : Used to select the keys and certificates to be recovered.
any of the following:
Certificate Common Name
Certificate Serial Number
Certificate SHA-1 hash (thumbprint)
Certificate KeyId SHA-1 hash (Subject Key Identifier)
Requester Name (domain\user)
UPN (user@domain)
RecoveryBlobOutFile : output file containing a certificate chain and an associated private key, still encrypted to one or more Key Recovery Agent certificates.
OutputScriptFile : output file containing a batch script to retrieve and recover private keys.
OutputFileBaseName : output file base name. For retrieve, any extension is truncated and a certificate-specific string and the .rec extension are appended for each key recovery blob. Each file contains a certificate chain and an associated private key, still encrypted to
one or more Key Recovery Agent certificates. For recover, any extension is truncated and the .p12 extension is appended.
Contains the recovered certificate chains and associated private keys, stored as a PFX file.
Recover archived private key
CertUtil [Options] -RecoverKey RecoveryBlobInFile [PFXOutFile [RecipientIndex]]
Options: [-f] [-user] [-silent] [-split] [-p Password] [-ProtectTo SAMNameAndSIDList] [-csp Provider] [-t Timeout]
Merge PFX files
CertUtil [Options] -MergePFX PFXInFileList PFXOutFile [ExtendedProperties]
Options: [-f] [-user] [-split] [-p Password] [-ProtectTo SAMNameAndSIDList] [-csp Provider]
PFXInFileList : Comma separated PFX input file list
PFXOutFile : PFX output file
ExtendedProperties: Include extended properties
The password specified on the command line is a comma separated password list.
If more than one password is specified, the last password is used for the output file.
If only one password is provided or if the last password is "*", the user will be prompted for
the output file password.
Convert PFX files to EPF file
CertUtil [Options] -ConvertEPF PFXInFileList EPFOutFile [cast | cast-] [V3CACertId][,Salt]
Options: [-f] [-split] [-p Password] [-csp Provider]
PFXInFileList : Comma separated PFX input file list
EPF : EPF output file
cast : Use CAST 64 encryption
cast- : Use CAST 64 encryption (export)
V3CACertId : V3 CA Certificate match token. See -store CertId description.
Salt: EPF output file salt string
The password specified on the command line is a comma separated password list.
If more than one password is specified, the last password is used for the output file.
If only one password is provided or if the last password is "*", the user will be prompted for
the output file password.
OPTIONS
These options must be entered on the command line before the main Verb
-nullsign Use hash of data as signature
-f Force overwrite
-enterprise Use local machine Enterprise registry certificate store
-user Use HKEY_CURRENT_USER keys or certificate store
-GroupPolicy Use Group Policy certificate store
-ut Display user templates
-mt Display machine templates
-Unicode Write redirected output in Unicode
-UnicodeText Write output file in Unicode
-gmt Display times as GMT
-seconds Display times with seconds and milliseconds
-silent Use silent flag to acquire crypt context
-split Split embedded ASN.1 elements, and save to files
-v Verbose operation
-privatekey Display password and private key data
-pin PIN Smart Card PIN
-urlfetch Retrieve and verify AIA Certs and CDP CRLs
-config Machine\CAName CA and computer name string
-PolicyServer URLOrId Policy Server URL or Id. For selection U/I, use -PolicyServer.
For all Policy Servers, use -PolicyServer *
-Anonymous Use anonymous SSL credentials
-Kerberos Use Kerberos SSL credentials
-ClientCertificate ClientCertId Use X.509 Certificate SSL credentials. For selection U/I, use -clientCertificate.
-UserName UserName Use named account for SSL credentials. For selection U/I, use -UserName.
-Cert CertId Signing certificate
-dc DCName Target a specific Domain Controller
-restrict RestrictionList Comma separated Restriction List. Each restriction consists
of a column name, a relational operator and a constant integer, string or date.
One column name can be preceded by a plus or minus sign to indicate the sort order.
Examples: "RequestId = 47" "+RequesterName >= a, RequesterName < b"
"-RequesterName > DOMAIN, Disposition = 21"
-out ColumnList Comma separated Column List
-p Password Password
-ProtectTo SAMNameAndSIDList Comma separated SAM Name/SID List
-csp Provider Provider
-t Timeout URL fetch timeout in milliseconds
-symkeyalg SymmetricKeyAlgorithm[,KeyLength] Name of Symmetric Key Algorithm with
optional key length, example: AES,128 or 3DES
Certutil is sensitive to the order of command-line parameters.
Certutil replaces the File Checksum Integrity Verifier (FCIV) found in earlier versions of Windows.
There are a some documentation inconsistencies between the command-line help (Certutil -?) and the various MSDN help pages.
e.g. -encodehex is completely missing from the command-line help.
The -decode option might not always restore spaces - see forum thread.
Examples
Display the SHA256 hash of a file:
certutil -hashfile c:\demo\anything.txt SHA256
Dump (read config information) from a certificate file:
certutil -dump c:\demo\sample.CER
Copy a certificate revocation list (CRL) to a file:
certutil -getcrl F:\ss64.crl
Purge local policy cache (Certificate Enrollment Policy Web Services):
certutil -f -policyserver * -policycache delete
View the content of the client computer’s Trusted Root Certification Authorities Enterprise certificate store:
certutil -enterprise -viewstore Root
Check the browsers Trusted Certificate list against the WindowsUpdate servers:
certutil -f -verifyCTL AuthRootWU
Stop Certificate Services:
certutil -shutdown
Convert a hex-encoded file to a binary executable. This is primarily intended for converting X.509 certificates from a human-readable format (.asn) into a computer-readable format (.bin):
certutil -decodehex hex.dat ss64.exe
vector
a.push_back(1); Appends/Adds an element whose value is 1 to vector a.
std::cout << a.at(0) << std::endl; Accessing index 0 of vector a.
a.size(); Returns the size of the vector
a.at(0) = 420; Changing the value at index 0 to 420.
for
loops/iteration
let array = [1, 2, 3];
for i in array.iter() {
println!("{}", i);
}
for i in 0u32..10 {
print!("{} ", i);
}
println!("");
prints `0 1 2 3 4 5 6 7 8 9 `
if
if 1 == 1 {
println!("Maths is working!");
} else {
println!("Oh no...");
}
if
as expression
let value = if true {
"good"
} else {
"bad"
};
while
loop
while 1 == 1 {
println!("The universe is operating normally.");
}
loop {
println!("Hello!");
}
AUTH password
ECHO message
PING [message]
QUIT
SELECT index
SWAPDB index index
journalctl -f
journalctl -b -p err
journalctl --since=2012-10-15 --until="2011-10-16 23:59:59"
journalctl -F _SYSTEMD_UNIT
journalctl -u dbus
journalctl /usr/bin/dbus-daemon
journalctl _PID=123
journalctl _COMM=sshd
journalctl _COMM=crond --since '10:00' --until '11:00'
journalctl --list-boots
journalctl _UID=1000
Syntax
coreinfo [-c][-f][-g][-l][-n][-s][-m][-v] -c
Key:
-c Dump information on cores.
-f Dump core feature information.
-g Dump information on groups.
-l Dump information on caches.
-n Dump information on NUMA nodes.
-s Dump information on sockets.
-m Dump NUMA access cost.
-v Dump only virtualization-related features including support
for second level address translation.
(requires administrative rights on Intel systems).
All options except -v are selected by default.
Examples
Drop all the coreinfo data into a text file:
coreinfo.exe > coreinfo.txt
Syntax
CHANGE USER /options
CHANGE LOGON /options
CHANGE PORT /options
Options:
To change .INI file mapping: (administrator rights required)
CHANGE USER /INSTALL Enable install mode. This command has to be run before
installing any new software on a Terminal Server.
This will create a .ini file for the application
in the TS system directory.
CHANGE USER /EXECUTE Enable execute mode (default)
Run this when an installation is complete.
CHANGE USER /QUERY Display current settings.
To enable or disable terminal session logins:
CHANGE LOGON /QUERY Query current terminal session login mode.
CHANGE LOGON /ENABLE Enable user login from terminal sessions.
CHANGE LOGON /DISABLE Disable user login from terminal sessions.
To list or change COM port mappings for the current session.
This can allow DOS applications to access high numbered ports e.g. COM12
CHANGE PORT portx=porty Map port x to port y.
CHANGE PORT /D portx Delete mapping for port x.
CHANGE PORT /QUERY Display current mapping ports.
How .ini files work:
Installing an application will create a .ini file in the TS system directory.
The first time a user runs the application, the application looks in the home directory for its .ini file. If none is found then Terminal Server will copy the .ini file from the system directory to the users home directory.
Each user will have a unique copy of the application's .ini file in their home directory.
To learn more about what happens when the system is put into install mode run CHANGE USER /?
The CHANGE command replaces CHGLOGON, CHGUSER, and CHGPORT from Citrix Winframe.
gcc file.c
gcc -o file file.c
gcc -g
gcc -ggdb3
gcc -m64
gcc -isystem /usr/include/myPersonnal/lib/
gcc -mwindows
Request certificate from a certification authority (CA), retrieve a response to a previous request from a CA, create a new request from an .inf file, accept and install a response to a request, construct a cross-certification or qualified subordination request from an existing CA certificate or request, or to sign a cross-certification or qualified subordination request.
Syntax
Certreq [-submit] [-retrieve RequestID] [-new] [-accept] [-policy] [-sign]
[-attrib AttributeString] [-binary] [-config CAMachineName\CAName]
[-crl] [-rpc] [-cert CertID]
[RequestFileIn | CertChainFileIn | FullResponseFileIn | CertFileIn | PolicyFileIn]
[RequestFileOut | CertChainFileOut | FullResponseFileOut | CertFileOut | PKCS10FileOut]
Key
-submit
Submit a request to a CA.
-retrieve RequestID
Retrieve a response to a previous request from a CA.
-new
Create a new request from an .inf file.
-accept
Accept and install a response to a certificate request.
-policy
Set the policy for a request.
-sign
Sign a cross-certification or qualified subordination request.
-attrib AttributeString
The Name and Value string pairs, separated by a colon.
Separate Name and Value string pairs with \n (for example, Name1:Value1\nName2:Value2).
-binary
Format output files as binary instead of base64-encoded.
-config CAMachineName\CAName
Process the operation using the CA specified in the configuration
string, which is CAMachineName\CAName.
-crl
Include certificate revocation lists (CRLs) in the output to the base64-encoded
PKCS #7 file specified by CertChainFileOut or to the base64-encoded file
specified by RequestFileOut.
-rpc
Instructs Active Directory Certificate Services (AD CS) to use a
remote procedure call (RPC) server connection instead of Distributed COM.
-cert CertID
The signing certificate by common name, serial number, Secure Hash Algorithm
(SHA-1) key, or certificate hash.
CertChainFileIn
The base64-encoded or binary certificate chain input file to use.
FullResponseFileIn
The base64-encoded or binary full response input file to use.
CertFileIn
The base64-encoded or binary certificate input file to use.
RequestFileIn
The base64-encoded or binary input file to use.
The file can be a PKCS #10 certificate request, a PKCS #7 certificate renewal
request, a KEYGEN tag format certificate request, a Certificate Management protocol
using Cryptographic Message Syntax (CMS) request (this protocol is also known as CMC),
or a certificate file of the CA that you want to cross-certify.
PolicyFileIn
The .inf input file that contains the extension definitions to use to qualify a request.
RequestFileOut
The base64-encoded file to which you want to send output.
PKCS10FileOut
The base64-encoded PKCS #10 file to which you want to send output.
CertFileOut
The binary or base64-encoded X.509 v3 file to which you want to send output.
CertChainFileOut
The binary or base64-encoded PKCS #7 file to which you want to send output.
FullResponseFileOut
The binary or base64-encoded full response file to which you want to send output.
-? Display a list of certreq commands.
You must specify the CAComputerName or CAName in -config CAComputerName\CAName. Otherwise, the Select Certificate Authority dialog box appears and displays a list of all CAs that are available.
To retrieve the certificate after the CA has actually issued it use certreq -retrieve RequestID, you can also use this command to retrieve any certificate that has ever been issued by the CA, including revoked or expired certificates, without regard to whether the certificate's request was ever in the pending state.
If you submit a request to the CA, the policy module of the CA might temporarily leave the request in a pending state and return the RequestID for display. Eventually, the CA’s administrator will issue the certificate or deny the request.
Examples
Sample request.inf
;----------------- request.inf
[Version]
Signature="$Windows NT$
[NewRequest]
Subject = "CN=dc01.ss64.com" ; must be the FQDN of domain controller
;EncipherOnly = FALSE
Exportable = FALSE ; TRUE = Private key is exportable
KeyLength = 1024 ; Common key sizes: 512, 1024, 2048,
; 4096, 8192, 16384
KeySpec = 1 ; Key Exchange
KeyUsage = 0xA0 ; Digital Signature, Key Encipherment
MachineKeySet = True
ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
ProviderType = 12
RequestType = CMC
; Omit entire section if CA is an enterprise CA
[EnhancedKeyUsageExtension]
OID=1.3.6.1.5.5.7.3.1 ; Server Authentication
[RequestAttributes]
CertificateTemplate = WebServer ;Omit line if CA is a stand-alone CA
;SAN="dns=dc01.ss64.com&dns=.ss64.com&dns=ldap.ss64.com"
;-----------------
Create a new request from an .inf file:
certreq -new request.inf result.txt
Supply the text of result.txt to your CA to obtain a signed certificate (and an intermediate CA certificate, if applicable.)
Submit a request to a CA:
certreq -submit result.txt certificate.cer
Retrieve a response to a previous request from a CA:
certreq -retrieve [-binary] [-config CAMachineName\CAName] [-crl] [-rpc] RequestID [CertFileOut [CertChainFileOut [FullResponseFileOut]]]
Accept and install a response to a certificate request:
certreq -accept c:\certificates\certificate.cer
Construct a cross-certification or qualified subordination request from an existing CA certificate or request:
certreq -policy [-attrib AttributeString] [-binary] [-cert CertID] [RequestFileIn [PolicyFileIn [RequestFileOut [PKCS10FileOut]]]]
Sign a cross-certification or qualified subordination request:
certreq -sign [-binary] [-certCertID] [-crl] [RequestFileIn [RequestFileOut]]
setup-apkcache
mkdir -p /var/cache/apk
ln -s /var/cache/apk /etc/apk/cache
Syntax
DSACLS "[\Computer]ObjectDN" [/A] [/D PermissionStatement [PermissionStatement]...]
[/G PermissionStatement [PermissionStatement]...] [/I:{T | S | P}]
[/N] [/P:{Y | N}]
[/R {User | Group} [{User | Group}]...] [/S [/T]]
PermissionStatements:
{User | Group}:Permissions[;{ObjectType | Property}][;InheritedObjectType]
Key
ObjectDN Distinguished name of the object.
If omitted will be taken from standard input (stdin)
/A Add ownership and auditing information to the results.
/D Deny permissions to a user or group
/G Grant permissions to a user or group.
/I: Inheritance
T The object and its child objects (default)
S The child objects only
P The object and child objects down one level only
/N Replace the current ACEs in the ACL.
By default, dsacls adds the ACE to the ACL.
/P: Inherit permissions from parent objects (Y/N).
/R Revoke/Delete all ACEs for the users or groups.
/S Restore the default security.
Default security for each object class is defined in the Active Directory schema.
/S /T Restore the default security on the tree of objects.
Permissions
GR: Generic Read
GE: Generic Execute
GW: Generic Write
GA: Generic All
SD: Delete an object
DT: Delete an object and all of its child objects
RC: Read security information
WD: Change security information
WO: Change owner information
LC: List the child objects of the object
CC: Create a child object•
DC: Delete a child object•
WS: Write to a self object (group membership) group object + {ObjectType | Property} = "member."
RP: Read a property•
WP: Write to a property•
CA: Control access (normally a specific extended right for control access)
If you do not specify {ObjectType | Property} this permission will apply to all
meaningful control accesses on the object.
LO: List the object access, AD DS does not enforce this permission by default.
Grant list access to a specific object when List Children (LC) is not granted to the parent.
Deny list access to a specific object when the user or group has LC permission on the parent.
ObjectType | Property
Limit the permission to the specified object type or property.
Enter the display name of the object type or the property.
Default=all object types and properties.
For example, Grant the user rights to create all types of child objects:
/G Domain\User:CC
Grant the user rights to create only child computer objects:
/G Domain\User:CC;computer
InheritedObjectType
Limit inheritance of the permission to the specified object type.
For example, Grant only User objects to inherit the permission:
/G Domain\User:CC;;user
Object Types
User,Contact,Group,Shared Folder,Printer,Computer,Domain Controllers,OU
• If you do not specify {ObjectType | Property} to define a specific child object type, this permission will apply to all types of child objects; otherwise, it will apply only to the child object type that you specify.
You can Grant, Deny or Delete ACEs for multiple users and groups with a single parameter (/G /D /R), list the users/groups separated with spaces.
Examples
Grant Generic Read (GR) and Generic Execute (GE) on computer objects in the Laptops OU to Jdoe:
C:\> dsacls "OU=Laptops,OU=AcmeCo,DC=ss64,DC=Com" /G Domain\JDoe:GRGE;computer
mkdir ~/.ncmpcpp
cat <
ncmpcpp_directory = "~/.ncmpcpp"
mpd_host = "127.0.0.1"
mpd_port = "6600"
mpd_music_dir = "/var/lib/mpd/music/"
EOF
Up k Move cursor up
Down j Move cursor down
[ Move cursor up one album
] Move cursor down one album
{ Move cursor up one artist
} Move cursor down one artist
Page Up Page up
Page Down Page down
Home Home
End End
Tab Switch to next screen in sequence
Shift-Tab Switch to previous screen in sequence
F1 Show help
1 Show playlist
2 Show browser
3 Show search engine
4 Show media library
5 Show playlist editor
6 Show tag editor
7 Show outputs
8 Show music visualizer
= Show clock
@ Show server info
s Stop
p Pause
Next track Previous track
Ctrl-H Backspace Replay playing song
f Seek forward in playing song
b Seek backward in playing song
- Left Decrease volume by 2%
Right + Increase volume by 2%
t Toggle space mode (select/add)
T Toggle add mode (add or remove/always add)
| Toggle mouse support
v Reverse selection
V Remove selection
B Select songs of album around the cursor
a Add selected items to playlist
Add random items to playlist
r Toggle repeat mode
z Toggle random mode
y Toggle single mode
R Toggle consume mode
Y Toggle replay gain mode
Z Shuffle playlist
x Toggle crossfade mode
X Set crossfade
u Start music database update
: Execute command
Ctrl-F Apply filter
/ Find item forward
? Find item backward
, Jump to previous found item
. Jump to next found item
w Toggle find mode (normal/wrapped)
G Locate song in browser
~ Locate song in media library
Ctrl-L Lock/unlock current screen
Left h Switch to master screen (left one)
Right l Switch to slave screen (right one)
E Locate song in tag editor
P Toggle display mode
\ Toggle user interface
! Toggle displaying separators between albums
g Jump to given position in playing song (formats: mm:ss, x%)
i Show song info
I Show artist info
L Toggle lyrics fetcher
F Toggle fetching lyrics for playing songs in background
q Quit
Enter Play selected item
Delete Delete selected item(s) from playlist
c Clear playlist
C Clear playlist except selected item(s)
Ctrl-P Set priority of selected items
Ctrl-K m Move selected item(s) up
n Ctrl-J Move selected item(s) down
M Move selected item(s) to cursor position
A Add item to playlist
e Edit song
S Save playlist
Ctrl-V Sort playlist
Ctrl-R Reverse playlist
o Jump to current song
U Toggle playing song centering
Enter Enter directory/Add item to playlist and play it
Space Add item to playlist/select it
e Edit song/directory/playlist name
2 Browse MPD database/local filesystem
Toggle sort mode
o Locate playing song
Ctrl-H Backspace Jump to parent directory
Delete Delete selected items from disk
G Jump to playlist editor (playlists only)
Enter Add item to playlist and play it/change option
Space Add item to playlist
e Edit song
y Start searching
3 Reset search constraints and clear results
4 Switch between two/three columns mode
Left h Previous column
Right l Next column
Enter Add item to playlist and play it
Space Add item to playlist
e Edit song
e Edit tag (left column)/album (middle/right column)
Toggle type of tag used in left column
m Toggle sort mode
Left h Previous column
Right l Next column
Enter Add item to playlist and play it
Space Add item to playlist/select it
e Edit song/playlist name
Ctrl-K m Move selected item(s) up
n Ctrl-J Move selected item(s) down
Delete Delete selected playlists (left column)
C Clear playlist except selected item(s)
Ctrl-P Set priority of selected items
Ctrl-K m Move selected item(s) up
n Ctrl-J Move selected item(s) down
M Move selected item(s) to cursor position
A Add item to playlist
e Edit song
S Save playlist
Ctrl-V Sort playlist
Ctrl-R Reverse playlist
o Jump to current song
U Toggle playing song centering
Enter Enter directory/Add item to playlist and play it
Space Add item to playlist/select it
e Edit song
e Edit directory name
e Edit playlist name
2 Browse MPD database/local filesystem
Toggle sort mode
o Locate playing song
Ctrl-H Backspace Jump to parent directory
Delete Delete selected items from disk
G Jump to playlist editor (playlists only)
Enter Add item to playlist and play it/change option
Space Add item to playlist
e Edit song
y Start searching
3 Reset search constraints and clear results
4 Switch between two/three columns mode
Left h Previous column
Right l Next column
Enter Add item to playlist and play it
Space Add item to playlist
e Edit song/tag (left column)/album (middle/right column)
Toggle type of tag used in left column
m Toggle sort mode
Left h Previous column
Right l Next column
Enter Add item to playlist and play it
Space Add item to playlist/select it
e Edit song/playlist name
Ctrl-K m Move selected item(s) up
n Ctrl-J Move selected item(s) down
Delete Delete selected playlists (left column)
Delete Delete selected item(s) from playlist (right column)
c Clear playlist
C Clear playlist except selected items
Space Toggle reloading lyrics upon song change
e Open lyrics in external editor
Refetch lyrics
Enter Edit tag
y Save
Enter Edit tag/filename of selected item (left column)
Enter Perform operation on all/selected items (middle column)
Space Switch to albums/directories view (left column)
Space Select item (right column)
Left h Previous column
Right l Next column
Ctrl-H Backspace Jump to parent directory (left column, directories view)
cloudup -a
cloudup
cloudup repositoryName
db.books.insert({"isbn": 9780060859749, "title": "After Alice: A Novel", "author": "Gregory Maguire", "category": "Fiction", "year":2016})
db.books.insert([
{ "isbn":"9781853260001", "title": "Pride and Prejudice", "author": "Jane Austen", "category": "Fiction"},
{"isbn": "9780743273565", "title": "The Great Gatsby", "author": "F. Scott Fitzgerald"}
])
db.collection.find()
db.books.find({"title":"Treasure Island"})
db.books.find({"title":"Treasure Island"}, {title:true, category:true, _id:false})
db.books.findOne({}, {_id:false})
db.books.update({title : "Treasure Island"}, {$set : {category :"Adventure Fiction"}})
$unset
db.books.update({title : "Treasure Island"}, {$unset : {category:""}})
$unset, {multi:true}
db.books.update({category : "Fiction"}, {$unset : {category:""}}, {multi:true})
{justOne:true}
db.books.remove({title :"Treasure Island"}, {justOne:true})
db.books.remove({"category" :"Fiction"})
db.books.remove({})
db.books.drop()
cat /path/to/foo
cat -n /path/to/foo
cat -b /path/to/foo
stocks Tesla
stocks AAPL
Syntax
Copy from the console to a new file:
COPY CON filename.txt
Type from the console to a new file:
TYPE CON > Newfile.txt
Type from the console to overwrite a file:
TYPE CON >> Newfile.txt
Copy a file to the console:
COPY file.txt CON
The console accepts this input and acts like TYPE file.txt
Pass an Echo command as input to the console:
Echo some text >CON
Without context this may not look useful, but when used within a redirected block,
it allows one line to break out of the redirection and display on the screen:
(
Echo Start
Echo Something happened >CON
Echo end of demo
) >logfile.txt
After entering COPY CON or TYPE CON, type in the text required, note there is no prompt for this, then end the file by typing CTRL-Z, this will insert an EOF marker: ASCII 0x1a (SUB).
When using COPY the CTRL-Z can be placed anywhere, but when using TYPE it is important that the CTRL-Z is only entered at the beginning of a new line, otherwise it will just be saved into the file and you will have two EOF markers in the same file.
Most basic text editors will stop reading after the first EOF marker.
Some commands e.g. CLS, do not work as expected when redirected to CON and will output extra control characters.
To read text from the console in PowerShell use the following function:
function copycon {
[system.console]::in.readtoend()
}
con is a reserved filename.
A more advanced use of the console device is to redirect the console CON into FIND and then redirect the output from FIND into a file, this will make FIND discard any lines which do not contain the desired text. This can be useful for condensing large log files to return only the lines of interest.
Example:
C:\> FIND /i "Jones"
asdf
asdf
zz Jones 2
asdf
^Z
C:\> TYPE logfile.txt
zz Jones 2
lvcreate -L 10G vg1
lvcreate -L 1500 -n mylv vg1
lvcreate -l 60%VG -n mylv vg1
lvcreate -l 100%FREE -n mylv vg1
lvcreate -L 10G -s -n lvsnap /dev/vgA/lv1
lvconvert --type mirror --alloc anywhere -m1 /dev/mylv/test
lvs -a -o +devices | egrep "LV|test"
lvconvert --splitmirrors 1 --name testCopy /dev/rootvg/test
function factorial:
input: integer n such that n >= 0
output: n * (n-1) * (n-2) * ... * 1 = n!
Syntax
COMP [pathname1] [pathname2] [/D] [/A] [/L] [/N=number] [/C]
Key
pathname1 The path and filename of the first file(s)
pathname2 The path and filename of the second file(s)
/D Display differences in decimal format. (default)
/A Display differences in ASCII characters.
/L Display line numbers for differences.
/N=number Compare only the first number of lines in the file.
/C Do a Case insensitive string comparison
Running COMP with no parameters will result in a prompt for the 2 files and any options
To compare sets of files, use wildcards in pathname1 and pathname2 parameters.
When used with the /A option COMP is similar to the FC command but it displays the individual characters that differ between the files rather than the whole line.
To compare files of different sizes, use /N= to compare only the first n lines (common portion of each file.)
COMP will normally finish with a Compare more files (Y/N) prompt,
to suppress this: ECHO n|COMP
Errorlevel
COMP will return an ErrorLevel as follows:
0 Files are identical
1 Files are different
2 Cannot open one of the files or invalid arguments or invalid switch
Syntax
COPY [options] [/A|/B] source [/A|/B] [+ source2 [/A|/B]...] [destination [/A|/B]]
COPY source1 + source2.. destination [options]
Key
source Pathname for the file or files to be copied.
/A ASCII text file (default)
/B Binary file copy - will copy extended characters.
/D Allow the destination file to be created decrypted.
destination Pathname for the new file(s).
/V Verify that the destination file, once written, can be read.
No comparison with the source files occurs.
/N If at all possible, create only short filenames (8.3) in the destination.
This option can help when copying between disks that are formatted differently
e.g NTFS and VFAT, or when archiving data to an ISO9660 CDROM.
/L If source is a symbolic link copy the link to the target
instead of the actual file the source link points to.
/Y Suppress confirmation prompt, when overwriting files.
/-Y Enable confirmation prompt, when overwriting files.
/Z Copy files in restartable mode. If the copy is interrupted part way through,
it will restart if possible. Also displays a '% complete' which counts up to 100%.
/? Display help.
Combining files
To combine files, specify a single file for the destination, but multiple files as the source. To specify more than one file use wildcards or list the files with a + in between each (file1+file2+file3).
When copying multiple files in this way the first file must exist or else the copy will fail, a workaround for this is COPY null + file1 + file2 dest1
Binary copies
"COPY /B ... " will copy files in binary mode.
The /A and /B options can appear in multiple locations, with different meanings depending on location.
Before any source - they will set the default mode for all source and destination files.
After a source - they will set the mode for that source.
After the destination - they will set the mode for the destination.
Copy from the console (accept user input)
COPY CON filename.txt
Then type the input text followed by ^Z (Control key & Z)
Prompt to overwrite destination file
Under Windows 2000 and above, the default action is to prompt on overwrite unless the command is being executed from within a batch script.
To force the overwriting of destination files use the COPYCMD environment variable:
SET COPYCMD=/Y
Errorlevels
If the file(s) were successfully copied %ERRORLEVEL% = 0
If the file was not found or bad parameters given = 1
COPY will accept UNC pathnames.
COPY is an internal command.
Examples:
Copy a file in the current folder
COPY source_file.doc newfile.doc
Copy from a different folder/directory:
COPY "C:\my work\some file.doc" "D:\New docs\newfile.doc"
Specify the source only, with a wildcard will copy all the files into the current directory:
COPY "C:\my work*.doc"
Specify the source with a wildcard and the destination as a single file, this is generally only useful with plain text files.
COPY "C:\my work*.txt" "D:\New docs\combined.txt"
Create an empty (zero byte) file:
COPY NUL EmptyFile.txt
Quiet copy (no feedback on screen)
COPY source_file.doc newfile.doc >nul
Copy a file, but do not overwrite if the destination file already exists, this technique only works for a single file, no wildcards:
Echo n|COPY /-y c:\demo\source_file.txt c:\dir\dest.txt
smartctl -H /dev/sda
smartctl -i /dev/sda
smartctl --test=short /dev/sda
smartctl --test=long /dev/sda
smartctl -X
Syntax
CHANGE USER /options
CHANGE LOGON /options
CHANGE PORT /options
Options:
To change .INI file mapping: (administrator rights required)
CHANGE USER /INSTALL Enable install mode. This command has to be run before
installing any new software on a Terminal Server.
This will create a .ini file for the application
in the TS system directory.
CHANGE USER /EXECUTE Enable execute mode (default)
Run this when an installation is complete.
CHANGE USER /QUERY Display current settings.
To enable or disable terminal session logins:
CHANGE LOGON /QUERY Query current terminal session login mode.
CHANGE LOGON /ENABLE Enable user login from terminal sessions.
CHANGE LOGON /DISABLE Disable user login from terminal sessions.
To list or change COM port mappings for the current session.
This can allow DOS applications to access high numbered ports e.g. COM12
CHANGE PORT portx=porty Map port x to port y.
CHANGE PORT /D portx Delete mapping for port x.
CHANGE PORT /QUERY Display current mapping ports.
How .ini files work:
Installing an application will create a .ini file in the TS system directory.
The first time a user runs the application, the application looks in the home directory for its .ini file. If none is found then Terminal Server will copy the .ini file from the system directory to the users home directory.
Each user will have a unique copy of the application's .ini file in their home directory.
To learn more about what happens when the system is put into install mode run CHANGE USER /?
The CHANGE command replaces CHGLOGON, CHGUSER, and CHGPORT from Citrix Winframe.
masscan -p80,8000-8100 10.0.0.0/8
masscan 0.0.0.0/0 -p0-65535 --excludefile exclude.txt --max-rate 100000
Syntax
CHCP code_page
Key
code_page A code page number (e.g. 437)
This command is rarely required as most GUI programs and PowerShell now support Unicode. When working with characters outside the ASCII range of 0-127, the choice of code page will determine the set of characters displayed.
Programs that you start after you assign a new code page will use the new code page, however, programs (except Cmd.exe) that you started before assigning the new code page will use the original code page.
Code page Country/ Region/ Language
437 United States default code page in the US
850 Multilingual (Latin I) default code page in most of Europe
852 Slavic (Latin II)
855 Cyrillic (Russian)
857 Turkish
860 Portuguese
861 Icelandic
863 Canadian-French
865 Nordic
866 Russian
869 Modern Greek
1252 West European Latin
65000 UTF-7 *
65001 UTF-8 *
Even if you use CHCP to run the Windows Console in a unicode code page, many applications will assume that the default still applies, e.g. Java requires the-Dfile option: java -Dfile.encoding=UTF-8
Unicode characters will only display if the current console font contains the characters. So use a TrueType font like Lucida Console instead of the CMD default Raster Font.
The CMD Shell (which runs inside the Windows Console)
CMD.exe only supports two character encodings Ascii and Unicode (CMD /A and CMD /U)
If you need full unicode support use PowerShell. There is still VERY limited support for unicode in the CMD shell, piping, redirection and most commands are still ANSI only. The only commands that work are DIR, FOR /F and TYPE, this allows reading and writing (UTF-16LE / BOM) files and filenames but not much else.
Code Pages
The number of supported code pages was greatly increased in Windows 7.
For a full list of code pages supported on your machine, run NLSINFO (Resource Kit Tools).
Files saved in Windows Notepad will be in ANSI format by default, but can also be saved as Unicode UTF-16LE or UTF -8 and for unicode files, will include a BOM.
A BOM will make a batch file not executable on Windows, so batch files must be saved as ANSI, not Unicode.
Examples:
View the current code page:
chcp
Change the code page to Unicode/65001:
chcp 65001
chown user file
chown user:group file
chown -R user directory
chown --reference=/path/to/ref_file file
Ctrl-s Ctrl-u
Ctrl-p, Alt-left
Ctrl-n, Alt-right
Alt-a
Alt-0...9
F9/F10
F11/F12
patch version1 < version.patch
patch -R version1 < version.patch
$ cd dir
$ patch -p1 -i ../big.patch
patch -p1 -r version1/ < version.patch
ci -u
co -l
ci -u
co -px.y
co -rx.y
rcsdiff
rcsdiff -rx.y -rx.z
rlog
rcs -u
pacman -Ss
pacman -Suy
pacman -S
pacman -R
pacman -Rcs
pacman -Si
pacman -U
pacman -Ql
pacman -Qe
pacman -Qdt
wget "https:aur.archlinux.org/packages/${pkgname::2}/$pkgname/$pkgname.tar.gz"
tar zxvf "$pkgname.tar.gz"
cd "$pkgname"
makepkg -s
sudo pacman -U
cd path/to/directory
cd
cd ..
cd -
ZEROCONF='+zeroconf' make -j4 CXX='distcc g++'
DISTCC_HOSTS='127.0.0.1 192.168.1.69' make -j4 CXX='distcc g++'
ZEROCONF='+zeroconf' distcc --show-hosts
nmcli d wifi connect
nmcli d wifi disconnect iface
nmcli radio wifi
nmcli radio wifi
nmcli dev wifi list
nmcli dev wifi rescan
nmcli con
nmcli con show --active
nmcli dev status
nmcli con add type ethernet con-name
nmcli con import type openvpn file
nmcli con up
ObjectName structName {
Declaration of variables
int a;
string b;
Constructor
structName(new_a, new_b) {
a = new_a;
b = new_b;
}
Implement any public functions below
};
ObjectName v = structName(5, "Hello"); Creates a struct via the constructor
std::cout << v.a << " " << v.b << std::endl; Prints to console "5 Hello"
SELECT * FROM table_name;
Query data from specified columns of all rows in a table
SELECT column, column2... FROM table;
SELECT DISTINCT (column) FROM table;
SELECT * FROM table WHERE condition;
SELECT column_1 AS new_column_1, ...
FROM table;
SELECT * FROM table_name
WHERE column LIKE '%value%'
SELECT * FROM table_name
WHERE column BETWEEN low AND high;
SELECT * FROM table_name
WHERE column IN (value1, value2,...);
SELECT * FROM table_name
LIMIT limit OFFSET offset
ORDER BY column_name;
SELECT * FROM table1 INNER JOIN table2 ON conditions
SELECT * FROM table1 LEFT JOIN table2 ON conditions
SELECT * FROM table1 FULL OUTER JOIN table2 ON conditions
SELECT * FROM table1 CROSS JOIN table2;
SELECT * FROM table1 NATURAL JOIN table2;
SELECT COUNT (*)
FROM table_name;
SELECT column, column2, ...
FROM table
ORDER BY column ASC [DESC], column2 ASC [DESC],...;
SELECT *
FROM table
GROUP BY column_1, column_2, ...;
SELECT *
FROM table
GROUP BY column_1
HAVING condition;
SELECT * FROM table1
UNION
SELECT * FROM table2;
SELECT * FROM table1
EXCEPT
SELECT * FROM table2;
SELECT * FROM table1
INTERSECT
SELECT * FROM table2;
dracut --add-drivers nvme -f /boot/initrd-$(uname -r).img $(uname -r)
class C(x: R) same as
class C(private val x: R)
var c = new C(4)
class C(val x: R)
var c = new C(4)
c.x
class C(var x: R) {
constructor is class body
assert(x > 0, "positive please")
declare a public member
var y = x
declare a gettable but not settable member
val readonly = 5
declare a private member
private var secret = 1
alternative constructor
def this = this(42)
}
new{ ... }
abstract class D { ... }
class C extends D { ... }
class D(var x: R)
class C(x: R) extends D(x)
object O extends D { ... }
trait T { ... }
mixin-able: http:docs.scala-lang.org/tutorials/tour/mixin-class-composition.html
class C extends T { ... }
class C extends D with T { ... }
trait T1; trait T2
class C extends T1 with T2
class C extends D with T1 with T2
class C extends D { override def f = ...}
new java.io.File("f")
new List[Int] BAD type error: abstract type
List(1,2,3) GOOD instead, convention: callable factory shadowing the type
classOf[String]
x.isInstanceOf[String]
x.asInstanceOf[String]
x: String
pbcopy < file
find . -type t -name "*.png" | pbcopy
ncat
ncat -l [
ncat -l [
ncat -l --keep-open [
ncat [
ncat -l --broker [
ncat -l --ssl [
ncat -l --allow
ncat -l --deny
ncat --proxy
ncat -l --chat [
iwconfig wlan0
iwconfig wlan0 txpower {on|auto|off}
iwconfig wlan0 mode {managed|ad-hoc|monitor}
Syntax
cmdkey [{/add:TargetName|/generic:TargetName}]
{/smartcard|/user:UserName [/pass:Password]}
[/delete{:TargetName|/ras}]
/list:TargetName
Key:
/add Add a user name and password to the list.
TargetName The computer or domain name that this entry will be associated with.
/generic Add generic credentials to the list (used by RDC).
/smartcard Retrieve the credential from a smart card.
/user:UserName The user or account name to store with this entry.
If UserName is not supplied, it will be requested.
/pass:Password The password to store with this entry. If Password is not supplied, it will be requested.
/delete: Delete a user name and password from the list.
If TargetName is specified, that entry will be deleted.
If /ras is specified, the stored remote access entry will be deleted.
/list Display the list of stored user names and credentials.
If TargetName is not specified, all stored user names and credentials will be listed.
The credentials created by CMDKEY can also be created and edited in the GUI Control Panel | Credential Manager
Credentials setup as type /generic:TERMSRV will be used by Remote Desktop Connection, so you will be able to connect as the given user without being prompted for a password. If the password is changed you will need to update the stored credential.
By default the credentials are stored in C:\users\username\AppData\Roaming\Microsoft\Credentials\
(around 400 bytes per credential)
If more than one smart card is found, cmdkey will prompt the user to specify which one to use.
Once stored, passwords are not displayed by cmdkey.
Examples
Display a list of stored user names and credentials:
cmdkey /list
Add a generic TERMSRV credential for user PeteZ (on domain dom64) to access the computer Server64:
cmdkey /generic:TERMSRV/Server64 /user:dom64\PeteZ /pass:p4g67hjyy23
Delete the stored TERMSRV credential for Server64:
cmdkey /delete TERMSRV/Server64
Add a user name and password for user Kate to access computer Server64 with the password z5rd63hGtjH7:
cmdkey /add:server64 /user:Kate /pass:z5rd63hGtjH7
Add a user name for user Kate to access computer Server64 and prompt for a password whenever Server64 is accessed:
cmdkey /add:server64 /user:Kate
Delete the stored credential for Server64:
cmdkey /delete:Server64
xcodebuild -workspace workspace_name.workspace -scheme scheme_name -configuration configuration_name clean build SYMROOT=SYMROOT_path
xcodebuild -target target_name -configuration configuration_name clean build SYMROOT=SYMROOT_path
xcodebuild -showsdks
csplit input.file '/PATTERN/'
csplit -f 'prefix-' -b '%d.extension' input.file '/PATTERN/' '{*}'
truncate -s 0 file.txt
truncate -s 100 file.txt
truncate -s 100K file.txt
eject
eject /dev/cdrom
eject -t
eject -i on
eject -i off
svcadm enable service_name
svcadm disable service_name
svcadm restart service_name
svcadm refresh service_name
svcadm clear service_name
wget https:luarocks.org/releases/luarocks-2.4.1.tar.gz
tar zxpf luarocks-2.4.1.tar.gz
cd luarocks-2.4.1
./configure; sudo make bootstrap
luarocks install luasocket
luarocks search luasec
strace
strace -o strace.out
strace -e trace=open
strace -e trace=file
strace -e trace=process
strace -f
strace -c
strace -p
http:localhost:631 (in web browser)
lp myfile.txt
lpq
lprm 545
or
lprm -
/var/log/cups
cupsreject printername
cupsaccept printername
siteciphers github.com
siteciphers -d 0.75 travis-ci.org
db.books.find().count()
db.books.find().limit(2)
db.books.find().skip(2)
db.books.find().sort( {title : 1} )
value = 1 for ascending, -1 for descending
db.books.find({}).pretty()
carthage update
carthage update --platform ios
carthage update --no-build
carthage bootstrap
carthage build dependency
ncdu -o ncdu.file
ncdu -f ncdu.file
ncdu -o-| gzip > ncdu.file.gz
zcat ncdu.file.gz | ncdu -f-
xsltproc --output output.html stylesheet.xslt xmlfile.xml
xsltproc --output output.html --stringparam name value stylesheet.xslt xmlfile.xml
works by applying a function to each element in the list
val l = List(1,2,3,4,5)
l map (num => num * 2) returns List(2,4,6,8,10)
this subsititutes "_" for the current value when iterating over the collection
l map (_ * 2) returns List(2,4,6,8,10)
allows the ability to provide different map functions for different discrete cases
this example will increment odd numbers by one, but double even numbers
l map { note: the curly brackets allow us to make the map multi-line and use 'case' statements (see PatternMatching)
case num if num % 2 == 0 => num * 2
case other => other + 1
} returns List(2,4,4,8,6)
removes elements from a collection where the filter function returns false
l filter (_ % 2 == 0) returns List(2,4)
l filter (_ % 2 == 0) returns List(1,3,5)
this is like a combination of filter and map
this example shows that collect essentially filters by "i < 3" then maps with "_ + 20"
l collect { note: collect requires a partial function, so we have to use curly brackets and 'case' statements
case i if i < 3 => i + 20
} returns List(21, 22)
this will return the first element (going left to right) that returns true
it returns an option to handle the case where no element is found
l find (_ % 2 == 0) returns Some(2)
l find (_ == 55) returns None
similar to find but returns a boolean instead if an element exists rather than an option
l exists (_ % 2 == 0) returns true
l exists (_ % 2 != 0) returns true
l exists (_ == 10) returns false
very similar to exists. Will check a condition applies to all elements on a collection and return a boolean
List(1,2,3) forall (_ < 5) returns true
List(1,2,6) forall (_ < 5) returns false
collapses a collection into a single element using a given function (this will fail with an empty list)
operates on two elements at a time, "reducing" them into one, so only one element is returned
l reduce ( (a, b) => a + b ) same as
l reduce (_ + _) returns 15, the result of adding 1, 2, 3, 4 and 5
this is the same as reduce except a "default" is provided, in case of an empty list.
List(1,2,3,4,5).fold(50)(_ + _) returns 15
List() .fold(50)(_ + _) returns 50, the default
must be used on something in the shape F[F[A]] eg. List[List[Int]]
squashes two-dimensional collections into one-dimensional collections
List(List(1,2,3), List(4,5)).flatten returns List(1,2,3,4,5)
maps then flattens in one function
in this example, we will map and flatMap a List[Int] using a function that turns each Int into a List[Int]
List(1,2,3) map {
num => List(num, num)
}
vs
List(1,2,3) flatMap {
num => List(num, num)
} returns List(1,1,2,2,3,3)
returns true if the collections is empty
List(1,2,3).isEmpty returns false
List().isEmpty returns true, same as
Nil.isEmpty
note: All lists terminate with "Nil" meaning that List() == List.empty == Nil
returns the "difference" of two collections, these are the elements that exist in the first but not the second
val oneToSix = List(1, 2, 3, 4, 5, 6)
val fourToNine = List(4, 5, 6, 7, 8, 9)
oneToSix diff (fourToNine) returns List(1,2,3)
fourToNine diff (oneToSix) returns List(7,8,9)
returns the "intersection" of two collections, these are the elements that exist in both collections
val oneToSix = List(1, 2, 3, 4, 5, 6)
val fourToNine = List(4, 5, 6, 7, 8, 9)
oneToSix intersect (fourToNine) returns List(4,5,6)
fourToNine intersect (oneToSix) returns List(4,5,6)
returns the concatenation of the two lists
val oneToSix = List(1, 2, 3, 4, 5, 6)
val fourToNine = List(4, 5, 6, 7, 8, 9)
oneToSix union fourToNine same as
oneToSix ++ fourToNine returns List(1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9)
removes duplicates from a collection
List(1,1,2,3,3,4,5).distinct returns List(1,2,3,4,5)
this will remove a given amount of elements from the front of a collection
List(1,2,3,4,5).drop(1) returns List(2,3,4,5)
List(1,2,3,4,5).drop(3) returns List(4,5)
this will continue to remove elements until the condition returns false
List(1,2,3,4,5).dropWhile(_ < 4) returns List(4,5), removing all elements smaller than four
List(1,2,3,4,5).dropWhile(_ % 2 == 0) returns List(1,2,3,4,5), it removes nothing as the first element returned false
the opposite of drop, returns the given number of elements from the front of a collection
List(1,2,3,4,5).take(1) returns List(1)
List(1,2,3,4,5).take(3) returns List(1,2,3)
this will continue to take elements until the condition returns false
List(1,2,3,4,5).takeWhile(_ < 4) returns List(1,2,3), taking all elements smaller than four
List(1,2,3,4,5).takeWhile(_ % 2 == 0) returns List(), it takes nothing as the first element returned false
this will create a List of a given length, filled with given elements
List.fill(3)(5) returns List(5,5,5)
List.fill(5)(3) returns List(3,3,3,3,3)
List.fill(3)("a") returns List("a", "a", "a")
returns the length of a collection
List(1,2,3,2).size returns 4
returns the minimum value
List(1,2,3).min returns 1
returns the maximum value
List(1,2,3).min returns 3
returns two collections as a Tuple2 eg. (List[Int], List[Int]), see DataStructures for more on Tuple
one collection containing all the "false" and another containing all the "true" elements
List(1,2,3,4).partition(_ % 2 == 0) returns (List(2,4), List(1,3))
List(1,2,3,4).partition(_ < 4) returns (List(1,2,3), List(4))
similar to partition, will split the list at the point that a condition returns false
List(1,3,5,4,2).span(_ < 3) returns (List(1), List(3,5,4,2))
List(1,3,5,4,2).span(_ != 5) returns (List(1, 3), List(5,4,2))
returns two collections as a Map
List(1,2,3,4).groupBy(_ % 2 == 0) returns Map(false -> List(1,3), true -> List(2,4))
List(1,2,3,4).groupBy(identity) returns Map(1 -> List(1), 2 -> List(2), 3 -> List(3), 4 -> List(4))
splits a collection before the given index
List(1,7,4,6,5).splitAt(2) returns (List(1,7), List(4,6,5))
returns a subset a collection between two indexes
List("a","b","c","d","e").slice(2,4) returns List("c","d")
joins two collections as a List of Tuple2, joining index 0 from one list to index 0 of the second list, 1 to 1, 2 to 2 etc.
List(1,2,3) zip List("x", "y", "z") returns List((1,"a"), (2,"b"), (3,"c"))
List(1,2,3,4,5) zip List("x", "y", "z") returns List((1,"a"), (2,"b"), (3,"c")) as there are only 3 elements to zip with
adds index numbers to a collection, returning a List of Tuple2
List("a", "b", "c").zipWithIndex returns List(("a",0), ("b",1), ("c", 2))
opposite of zip, converts a List of Tuple2 into a Tuple2 of Lists
List(("a",0), ("b",1), ("c", 2)).unzip returns (List("a", "b", "c"), List(0, 1, 2))
List(1,2,3).reverse returns List(3,2,1)
returns the first element of a collection
List(1,2,3).head returns 1
returns the first element of a collection as an Option, returns None in the case of an empty collection
List(1,2,3).headOption returns Some(1)
List().headOption returns None
returns everything after the Head of a collection
List(1,2,3).tail returns List(2,3), same as
List(1,2,3).drop(1)
List(1,2,3).last returns 3
cut -d# -f3
nc -p 31337 -w 5 host.example.com 42
nc -u host.example.com 53
nc -s 10.1.2.3 host.example.com 42
nc -lU /var/tmp/dsocket
nc -x10.2.3.4:8080 -Xconnect host.example.com 42
nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42
nc -zv -s source_IP target_IP Port
Syntax
convert [Volume] /fs:ntfs [/v] [/cvtarea:FileName] [/nosecurity] [/x]
Key
Volume The drive letter (followed by a colon), mount point,
or volume name to convert to NTFS.
/fs:ntfs Convert the volume to NTFS. Required.
/v Run convert in verbose mode, which displays all messages
during the conversion process.
/cvtarea:FileName
Specifies that the Master File Table (MFT) and other NTFS metadata
files are written to an existing, contiguous placeholder file.
This file must be in the root directory of the file system to be converted.
Use of the /cvtarea parameter can result in a less fragmented file system
after conversion.
For best results, the size of this file should be 1 KB multiplied by the number of files
and directories in the file system, although the convert utility accepts files of any size.
Important You must create the placeholder file by using the fsutil file createnew command
prior to running convert. Convert does not create this file for you.
Convert overwrites this file with NTFS metadata.
After conversion, any unused space in this file is freed.
/nosecurity
The security settings on the converted files and directories allow access by all users.
/x Dismount the volume, if necessary, before it is converted.
Any open handles to the volume will no longer be valid.
/? Display help at the command prompt.
If convert cannot lock the drive (for example, the drive is the system volume or the current drive), you are given the option to convert the drive the next time you restart the computer. If you cannot restart the computer immediately to complete the conversion, plan a time to restart the computer and allow extra time for the conversion process to complete.
For volumes converted from FAT or FAT32 to NTFS:
Due to existing disk usage, the MFT is created in a different location than on a volume originally formatted with NTFS, so volume performance might not be as good as on volumes originally formatted with NTFS. For optimal performance, consider recreating these volumes and formatting them with the NTFS file system. Volume conversion from FAT or FAT32 to NTFS leaves the files intact, but the volume might lack some performance benefits compared to volumes initially formatted with NTFS. For example, the MFT might become fragmented on converted volumes. In addition, on converted boot volumes, convert applies the same default security that is applied during Windows Setup.
Example
Convert the volume on drive E: to NTFS and display all messages during the conversion process:
C:\> convert e: /fs:ntfs /v
scrot -u
scrot -ub
scrot -s
scrot -u -d 5 -c
Syntax
CHKDSK [drive:][[path]filename] [/F] [/V] [/R] [/L[:size]]
Key
[drive:] The drive to check. Drive letter followed by a colon, mount point or volume name.
filename File(s) to check for fragmentation (FAT only).
/F Automatically Fix file system errors on the disk.
/X Fix file system errors on the disk, Implies /F
dismounts the volume first, closing all open file handles.
/R Scan for and attempt Recovery of bad sectors.
/B NTFS only: Re-evaluate bad clusters on the volume. Implies /R Windows10+
/V Display the full path and name of every file on the disk.
/L:size NTFS only: change the log file size to the specified number of kilobytes.
If size is not specified, displays the current log size and the drive type
(FAT or NTFS).
/C NTFS only: Skip directory corruption checks.
/I NTFS only: Skip corruption checks that compare directory entries to the
file record segment (FRS) in the volume's master file table (MFT)
/scan NTFS only: Run an online scan on the volume.
/forceOfflineFix
NTFS only: Must be used with /scan
Bypass all online repair; all defects found are queued for offline repair
i.e. chkdsk /spotfix
/perf NTFS only: Must be used with /scan
Uses more system resources to complete a scan as fast as possible. This may
have a negative impact on other running tasks.
/spotfix NTFS only: Run spot fixing on the volume.
/sdCleanup NTFS only: Garbage collect unneeded security descriptor data, implies /F
/offlineScanandFix
Run an offline scan and fix on the volume.
/freeOrphanedChains
FAT/FAT32/exFAT only: Free any orphaned cluster chains instead of recovering
their contents.
/markClean FAT/FAT32/exFAT only: Mark the volume clean if no corruption was detected even
if /F was not specified.
Examples
CHKDSK C: /F
Fixing Errors /F
If the drive is the boot partition, you will be prompted to run the check during the next boot
If you specify the /f switch, chkdsk will show an error if open files are found on the disk.
Chkdsk /f will lock the volume, making data unavailable until chkdsk is finished.
If you use chkdsk /f on a disk with a very large number of files (millions), chkdsk can take a long time to complete.
When you delete a file or folder that has 'custom' permissions, the ACL is not deleted, it is cached. Chkdsk /f will remove ACLs that are no longer used. This is often the cause of the rather worrying message: "Windows found problems with the file system. Run chkdsk with the /F (fix) option to correct these."
It is normal for chkdsk /F to remove unused index entries and unused security descriptors every time you run it, these do not indicate a problem with the file system.
Scan only (without /f switch)
If a file needs to be fixed chkdsk will alert you with a message but will not fix the error(s).
chkdsk can report lost allocation units on the disk - it will produce this report even if the files are in-use (open). If corruption is found, consider closing all files and repairing the disk with /F.
Running chkdsk on a data volume that is in use by another program or process can incorrectly report errors when none are present. To avoid this, close all programs or processes that have open handles to the volume.
On computers running Windows 2003 SP1 and later, chkdsk automatically creates a shadow copy, so you can check volumes that are 'in use' by another program or process. This enables an accurate report against a live file server. On earlier versions of Windows, chkdsk would always lock the volume, making data unavailable.
Run at Bootup
Running at bootup is often the easiest way to close all open file handles.
Use chkdsk, chkntfs or the FSUTIL dirty commands to set or query the volumes 'dirty' bit so that Windows will run chkdsk when the computer is restarted. This setting is also found in the BootExecute value under HKLM\System\CurrentControlSet\Control\Session Manager
Event Logs
Chkdsk will log error messages in the Event Viewer - System Log.
Chkdsk /f removes ACLs that are no longer used and reports this in the Event Viewer - Application Log.
Cluster (or block) Size
CHKDSK produces a report that shows the the block /cluster size
typically: "4096 bytes in each allocation unit."
When the cluster size is greater than 4 KB on an NTFS volume, none of the NTFS compression functions are available.
Exit codes
0 No errors were found
1 Errors were found and fixed.
2 Could not check the disk, did not or could not fix errors.
Notes:
Consider the time required to run Chkdsk to repair any errors that occur. Chkdsk times are determined by the number of files on the volume and by the number of files in the largest folder. Chkdsk performance was improved by 30% under Windows 2003 and around 50% in 2008 R2.
To issue chkdsk on a hard drive you must be a member of the Administrators group.
When CHKDSK is set to run at boot-up there is a delay to allow the check to be cancelled - this can be configured in the registry:
HKLM\System\CurrentControlSet\Control\Session Manager
REG_DWORD:AutoChkTimeOutData
The value is the time in seconds that you want CHKDSK to wait (0 = no delay) default is 10 seconds.
Chkdsk is also available from the Recovery Console (with different parameters.)
currency
currency USD EUR 14.38
Syntax
COLOR [background][foreground]
Colour attributes are specified by 2 of the following hex digits. There should be no space between the two color numbers.
Each digit can be any of the following values:
0 = Black
8 = Gray
1 = Blue
9 = Light Blue
2 = Green
A = Light Green
3 = Aqua
B = Light Aqua
4 = Red
C = Light Red
5 = Purple
D = Light Purple
6 = Yellow
E = Light Yellow
7 = White
F = Bright White
If no argument is given, COLOR restores the colour to what it was when CMD.EXE started.
Colour values are assigned in the following order:
The DefaultColor registry value.
The CMD /T command line switch
The current colour settings when cmd was launched
The COLOR command sets ERRORLEVEL to 1 if an attempt is made to execute the COLOR command with a foreground and background colour that are the same.
The default terminal color is COLOR 07, white on black
The COLOR command will change the color of all the text in the window. To change the color of individual words/characters/paragraphs ANSI color escapes can be used. These are available in Windows versions greater than 1511.
New default Color schemes
In Windows 10 clean-install versions greater than build 16257 the default colour scheme has been changed to modernize the look of the Windows Console suitable for modern high-contrast LCD displays.
Samples of the new colors can be found on the ANSI color page, you can also display them with ColorTool.exe -c
If using ColorTool, you may want to tinker with the new values: "So up until very recently the console only supported 16 colours at a time. When the PowerShell team decided they wanted a very specific dark blue as the background colour, rather than altering the colour value for dark or light blue, they instead changed dark magenta to blue and used that as the background colour".
24 bit colors
The new W10 Console also adds full 24-bit color support, this is primarily for Linux compatibility so the console properties page and the default Windows color mappings still use just 16 colors, there is no plan to add additional console colors to the Win32 API.
To take advantage of the new colors use ColorTool.exe and install a theme, or use the VT100 sequences described here.
When the VT100 sequences are used with a version of the Windows Console that supports 24-bit colors they will display the desired RGB color, older consoles will choose the nearest appropriate color from the existing 16 color table.
Errorlevels
If the color was successfully changed %ERRORLEVEL% = 0
Background and foreground colors are the same (will fail) = 1
e.g. COLOR 00
COLOR is an internal command.
If Command Extensions are disabled, the COLOR command will not function.
SELECT schema_name FROM information_schema.schemata;
SELECT nspname FROM pg_catalog.pg_namespace;
CREATE SCHEMA IF NOT EXISTS
DROP SCHEMA IF EXISTS
ch := make(chan int) create a channel of type int
ch <- 42 Send a value to the channel ch.
v := <-ch Receive a value from ch
Create a buffered channel.
Writing to a buffered channels does not block
if less than
ch := make(chan int, 100)
Non-buffered channels block.
Read blocks when no value is available,
write blocks if a value already has been written but not read.
close(ch) closes the channel (only sender should close)
read from channel and test if it has been closed
v, ok := <-ch
if ok is false, channel has been closed
Read from channel until it is closed
for i := range ch {
fmt.Println(i)
}
select blocks on multiple channel operations,
if one unblocks, the corresponding case is executed
func doStuff(channelOut, channelIn chan int) {
select {
case channelOut <- 42:
fmt.Println("We could write to channelOut!")
case x := <- channelIn:
fmt.Println("We could read from channelIn")
case <-time.After(time.Second * 1):
fmt.Println("timeout")
}
}
Syntax
COMPACT [/C | /U] [/S[:dir]] [/A] [ /I] [/F] [/Q] [/EXE[:algorithm]]
[/CompactOs[:option] [/WinDir:dir] [filename [...]]
Key
/C Compress the specified files.
Directories will be marked so that files added afterward will be compressed.
/U Uncompress the specified files.
Directories will be marked so that files added afterward will not be compressed.
/S Perform the specified operation on files in the given directory and all subdirectories.
The default "dir" is the current directory.
/A Display files with the hidden or system attributes. These files are omitted by default.
/I Continue performing the specified operation even after errors have occurred.
By default, COMPACT will stop when an error is encountered.
/F Force the compress operation on all specified files, even those which are already
compressed. Already-compressed files are skipped by default.
/Q Report only the most essential information.
/EXE Use compression optimised for executable files which are read frequently and not modified,
Supported algorithms are:
XPRESS4K (fastest) default
XPRESS8K
XPRESS16K
LZX (most compact)
/CompactOs Set or query the systems compression state.
Supported options are:
query - Query the systems compact state.
always - Compress all OS binaries and set the system state to non-compact.
never - Uncompress all OS binaries and set the system state to compact which remains
unless an administrator changes it.
/WinDir Used with /CompactOs:query, when querying the offline OS. Specifies the directory where
Windows is installed.
filename Specifies a pattern, file, or directory.
Used without parameters, COMPACT displays the compression state of the current directory and any files it contains.
You can use multiple filenames and wildcards. You must put spaces between multiple parameters.
xscreensaver-command -lock
GOOD
def f(x: Int) = { x*x }
BAD
hidden error: without = it’s a Unit-returning procedure; causes havoc
def f(x: Int) { x*x }
GOOD
def f(x: Any) = println(x)
BAD
syntax error: need types for every arg.
def f(x) = println(x)
type R = Double
def f(x: R)
def f(x: => R)
(x:R) => x*x
(1 to 5).map(_*2) vs.
(1 to 5).reduceLeft( _+_ )
(1 to 5).map( x => x*x )
GOOD
(1 to 5).map(2*)
BAD
(1 to 5).map(*2)
(1 to 5).map { x => val y=x*2; println(y); y }
(1 to 5) filter {_%2 == 0} map {_*2}
def compose(g:R=>R, h:R=>R) = (x:R) => g(h(x))
val f = compose({_*2}, {_-1})
val zscore = (mean:R, sd:R) => (x:R) => (x-mean)/sd
def zscore(mean:R, sd:R) = (x:R) => (x-mean)/sd
def zscore(mean:R, sd:R)(x:R) = (x-mean)/sd
val normer = zscore(7, 0.4) _
can be called as "add(1)(2)" to return "3"
def add(x: Int) = x + (_: Int)
def mapmakeT(seq: List[T]) = seq.map(g)
5.+(3); 5 + 3
(1 to 5) map (_*2)
def sum(args: Int*) = args.reduceLeft(_+_)
def countTo(i: Int = 5) = 1 to i
countTo(3) = Range(1,2,3)
countTo() = Range(1,2,3,4,5)
as long as a function returns the correct type, it can be used as a parameter in another function
def sum(a: Int, b: Int): Int = a + b
def double(x: Int): Int = x * 2
double(sum(1, 1)) returns 4
udisksctl info -b
udisksctl mount --block-device
udisksctl unmount --block-device
udisksctl help
rpm2cpio foo.rpm | cpio -vt
rpm2cpio foo.rpm | cpio -vid
Syntax
CD [/D] [drive:][path]
CD [..]
Key
/D : change the current DRIVE in addition to changing folder.
CHDIR is a synonym for CD.
Tab Completion
Tab completion allows changing the current folder by entering just part of the path and pressing TAB.
C:> CD Prog [PRESS TAB]
Will go to C:\Program Files\
Tab Completion is disabled by default, it has been known to create difficulty when using a batch script to process text files that contain TAB characters.
Tab Completion is turned on by setting the registry value shown below:
REGEDIT4
[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"CompletionChar"=dword:00000009
A Current Directory for each drive?
Originally in MS-DOS, each drive had its own current directory, for complex historical reasons.
Now in Win32, there is one global current directory, but at the command line the appearance is still maintained that each drive has its own current directory, this is a fake-out by cmd.exe.
The location for each drive is stored using the undocumented environment variables =A:, =B:, =C: etc.
The only reason you need to be aware of this is that GUI Windows applications may have a different current directory than the command prompt. Similarly two CMD sessions can each have a different current directory.
Errorlevels
If the Current directory was changed: %ERRORLEVEL% = 0
If the Directory does not exist or is not accessible or if a bad switch given: %ERRORLEVEL% = 1
CHDIR is a synonym for CD
CD is an internal command.
Examples
Change to the parent directory:
C:\Work> CD ..
Change to the grant-parent directory:
C:\Work\backup\January> CD ..\..
Change to the ROOT directory:
C:\Work\backup\January> CD \
Display the current directory in the specified drive:
C:\> CD D:
Display the current drive and directory:
C:\Work> CD
Display the current drive and directory:
C:\Work> ECHO "%CD%"
In a batch file to display the location of the batch script file (%0)
C:\> ECHO "%~dp0"
In a batch file to CD to the location of the batch script file (%0)
C:\> CD /d "%~dp0"
Move down the folder tree with a full path reference to the ROOT folder...
C:\windows> CD \windows\java
C:\windows\java>
Move down the folder tree with a reference RELATIVE to the current folder...
C:\windows> CD java
C:\windows\java>
Move up and down the folder tree in one command...
C:\windows\java> CD ..\system32
C:\windows\system32>
If Command Extensions are enabled, which they are by default, the CD command is enhanced as follows:
The current directory string is not CASE sensitive.
So CD C:\wiNdoWs will set the current directory to C:\Windows
CD does not treat spaces as delimiters, so it is possible to CD into a subfolder name that contains a space without surrounding the name with quotes.
For example:
cd \My folder
is the same as:
cd "\My folder"
An asterisk can be used to complete a folder name
e.g. C:> CD pro* will move to C:\Program Files
Change the Current Drive
Enter the drive letter followed by a colon
C:> E:
E:>
To change drive and directory at the same time, use CD with the /D switch
C:> cd /D E:\utils
E:\utils\>
launchctl load ~/Library/LaunchAgents/my_script.plist
sudo launchctl load /Library/LaunchAgents/root_script.plist
sudo launchctl load /Library/LaunchDaemons/system_daemon.plist
launchctl list
launchctl unload ~/Library/LaunchAgents/my_script.plist
launchctl start my_script
launchctl stop my_script
p6doc build
p6doc -f slurp
p6doc -f Type::IO.slurp
void functionName() {}
void functionName(int param1, int param2) {}
int functionName() {
return 420;
}
(C++ uses pairs [ 2 values ] and tuple [ more than 2 values ])
Please refer pairs and tuple respectively for more information
std::tuple
return std::make_tuple( double1, double2 );
}
pair
std::cout << result.first << std::endl;
std::cout << result.second << std::endl;
int functionName(int &referenceName) {}
int functionName(int valueName) {}
def functionName():
return True
def functionName(a, b):
if a < b:
return a
else:
return b
def functionName(a, b, c):
return a, b, c # Returns a tuple
return {'return_a':a, 'return_b':b ,'return_c':c } # Returns a dictionary
def functionName(a=0, b=1):
print(a, b)
functionName() # 0 1
functionName(3) # 3 1
functionName(3, 4) # 3 4
def functionName(a, b, c):
print(a, b, c)
functionName(0, 1, 2) # 0 1 2
functionName(a=2, c=3, b=4) # 2 4 3
functionName(2, 3, c=4) # 2 3 4
def functionName(*args):
...
functionName(*[1, 2]) # Equivalent of functionName(1, 2)
functionName(*[1, 2, 3]) # Equivalent of functionName(1, 2, 3)
def functionName(kwargs):
...
functionName({'a' : 3, 'b' : 4}) # Equivalent of functionName(a=3, b=4)
sudo dhclient -r
sudo dhclient
sudo dhclient eth0
Syntax
CLEANMGR [/d driveletter] option
CLEANMGR [/d driveletter] /sageset:n option
CLEANMGR [/d driveletter] /sagerun:n option
Options
/D driveletter The drive that you want Disk Cleanup to clean.
NOTE: The /d option is not utilized with /SAGERUN:n.
Specify the %systemroot% drive to see all the available options.
/SAGESET:n Display the Disk Cleanup Settings dialog box and create
a registry key to store the settings you select.
REQUIRES ELEVATION
The n value is stored in the registry and allows you to
specify different tasks for Disk Cleanup to run.
n can be any integer from 0 to 9999.
/SAGERUN:n Run task 'n'
All drives in the computer will be enumerated, and the
selected profile will be run against each drive.
/TUNEUP:n Run /sageset and /sagerun for the same n
/LOWDISK Disk Cleanup will open with all options checked.
Normally invoked when Windows notifies that of disk space is running out.
/VERYLOWDISK Disk Cleanup will open with all options checked, no user prompts.
/SETUP Analyze the system files left over from a previous Windows version. [Undocumented]
/Autoclean Analyze the system files left over from a previous Windows version/in-place upgrade.
and also remove those files automatically. [Undocumented]
/HELP Display help
/USAGE Display help
/? Display help
If CLEANMGR is run without /sageset or /sagerun, it will start by calculating how much disk space could be saved. This makes the process slower to startup.
Although many of these files are often described as "junk" you should carefully evaluate what they do before deleting them. By default only the Downloaded Program Files and Temporary Internet Files will be selected.
Having a hard drive that is over 75% - 80% full will affect performance because file fragmentation (and automatic defragmentation) will increase. Also assuming you have the default 'system managed size' for the page file, that will automatically shrink to fit in the available space. For a drive that has more than 25% free space, deleting files will not make any difference to performance.
Some cleanup options require elevation, when run without elevation the GUI will include an option [Clean up System Files] which will relaunch CLEANMGR in Elevated mode. When necessary CLEANMGR can take ownership of the files before deleting them.
To enable Cleanmgr on older servers of Windows Server, open Server Manager and choose Add feature, then select "Desktop Experience"
After running cleanmgr on a server you may want to disable "Desktop Experience" again.
Cleanup Settings: Files to delete
The following options can be toggled on or off when running /SAGESET:n
Branch Cache
Catalog Files for the Content Indexer
Compress Old Files
Delivery Optimization Files
Diagnostic data viewer database files
DirectX Shader cache
Downloads (Personal downloads folder)
Downloaded Program Files *
Language resources Files
Offline Files
Old Chkdsk Files
Recycle Bin * (empties the recycle bin to recover the disc space)
Retail Demo Offline Content
Setup Log files
System Error memory dump files
System Error minidump files
Temporary Files
Temporary Internet Files *
Temporary Setup Files
Temporary Offline Files
Thumbnails
Update package Backup Files
User file history
Windows Defender Antivirus
Windows error reports and feedback diagnostics
Windows Update Cleanup
Windows Upgrade log files
Items marked with * have a [View Files] option in the GUI to view the individual files.
The Recycle Bin and Catalog Files for the Content Indexer may appear for more than one drive.
Application Data
The user's 'Application Data' folder is not available for cleanup in the above list. Many files in Application Data hold system data that should not be deleted. However if you have an application that leaves a significant number of temporary/junk files in App Data, these can be selectively removed from a roaming profile with a VBScript like this.
Recent files
The 'User Profile/Recent Items' folder can contain many more shortcuts than are useful. A very large number of these can affect logon/logoff times. To clear out the shortcuts:
CD %userprofile%\AppData\Roaming\Microsoft\Windows\Recent
Echo y| del *.*
Close Locked files by restarting Windows Explorer
Save the following batch script:
@Echo off
Taskkill /f /im Explorer.exe
Start Explorer.exe
Exit
Then to restart Windows Explorer, just run the batch file.
Registry
Registry settings for CLEANMGR are held in:
[HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches]
Here are a set of registry entries to turn on a typical selection of cleanmgr options, these can be used with REG or Regedit to pre-populate the regisitry as a scriptable alternative to running /SAGESET
Log files for CLEANMGR are stored in:
C:\Windows\System32\LogFiles\setupcln\
Examples
Choose a set of options for cleanup (this will display the GUI) and Save as settings group #64:
CLEANMGR /sageset:64
Run the saved settings group #64
CLEANMGR /sagerun:64
To run Disk Cleanup this way regularly, you can create a shortcut which can be run from the Windows Startup folder or via a regular schedule. To run the saved settings group #64
%systemroot%\system32\cmd.exe /c CLEANMGR /sagerun:64
DEL key [key ...]
DUMP key
EXISTS key [key ...]
EXPIRE key seconds
EXPIREAT key timestamp
KEYS pattern
MIGRATE host port key|"" destination-db timeout [COPY] [REPLACE] [KEYS key [key ...]]
MOVE key db
OBJECT subcommand [arguments [arguments ...]]
PERSIST key
PEXPIRE key milliseconds
PEXPIREAT key milliseconds-timestamp
PTTL key
RANDOMKEY
RENAME key newkey
RENAMENX key newkey
RESTORE key ttl serialized-value [REPLACE]
SORT key [BY pattern] [LIMIT offset count] [GET pattern [GET pattern ...]] [ASC|DESC] [ALPHA] [STORE destination]
TOUCH key [key ...]
TTL key
TYPE key
UNLINK key [key ...]
WAIT numslaves timeout
SCAN cursor [MATCH pattern] [COUNT count]
Syntax
BCDEdit /Command [Argument1] [Argument2] ...
Key
/? commmand To display detailed help for a particular command, run bcdedit /? command,
where command is the name of the command you are searching for more information about.
e.g. bcdedit /? createstore
Store commands:
/createstore Creates a new empty boot configuration data store.
The created store is not a system store.
/export Export the contents of the system store into a file.
This file can be used later to restore the state of the system store.
Valid only for the system store.
/import Restore the state of the system store by using a backup data file
previously generated with /export.
This command deletes any existing entries in the system store before
the import takes place. Valid only for the system store.
/store This option can be used with most BCDedit commands to specify
the store to be used. If this option is not specified, then
BCDEdit operates on the system store.
Running the bcdedit /store command by itself is equivalent to running
the bcdedit /enum active command.
/sysstore Set the system store device. This only affects EFI-based systems.
It does not persist across reboots, and is only used in cases where the system
store device is ambiguous.
Operating on entries in a store:
/copy Make a copy of a specified boot entry in the same system store.
/create Create a new entry in the boot configuration data store.
If a well-known identifier is specified, then the /application, /inherit, and
/device options cannot be specified. If an identifier is not specified or not well
known, an /application, /inherit, or /device option must be specified.
/delete Delete an element from a specified entry.
/mirror Create a mirror of entries in the store.
Changing entry options:
/deletevalue Delete a specified element from a boot entry.
/set Set an entry option value.
List current settings:
/enum [type | id] [/v]
List entries in a store.
Types: ACTIVE, FIRMWARE, BOOTAPP, BOOTMGR, OSLOADER, RESUME, INHERIT, ALL
The /enum option is the default value for BCEdit, so running
the bcdedit command without options is equivalent to running the bcdedit /enum active command.
/v Verbose mode.
Usually, any well-known entry identifiers are represented by their friendly shorthand form.
Specifying /v as a command-line option displays all identifiers in full.
Running the bcdedit /v command by itself is equivalent to running the bcdedit /enum active /v command.
Controlling the boot manager:
/bootsequence Specifies a one-time display order to be used for the next boot.
This command is similar to the /displayorder option, except that it is used only the
next time the computer starts. Afterwards, the computer reverts to the original
display order.
/default Specifies the default entry that the boot manager selects when the timeout expires.
/displayorder Specifies the display order that the boot manager uses when displaying boot options
to a user.
/timeout Specifies the time to wait, in seconds, before the boot manager selects the default entry.
/toolsdisplayorder Specifies the display order for the boot manager to use when displaying the Tools menu.
Emergency Management Services options:
/bootems Enable or disable Emergency Management Services (EMS) for the specified entry.
/ems Enable or disable EMS for the specified operating system boot entry.
/emssettings Set the global EMS settings for the computer.
/emssettings does not enable or disable EMS for any particular boot entry.
Debugging:
/bootdebug Enable or disable the boot debugger for a specified boot entry.
Although this command works for any boot entry, it is effective only for boot applications.
/dbgsettings Specifies or displays the global debugger settings for the system.
This command does not enable or disable the kernel debugger; use the /debug option for
that purpose. To set an individual global debugger setting, use the
bcdedit /setdbgsettings type value command.
/debug Enable or disable the kernel debugger for a specified boot entry.
/hypervisorsettings Set the hypervisor parameters.
Undocumented:
/loglevel level [/raw]
level is one of the following:
t : trace (stdout)
i : info (stdout)
w : warning (stderr)
e : error (stderr)
/raw : Display extra details for the device and osdevice fields.
Normal display:
device partition=\Device\HarddiskVolume2
osdevice partition=C:
With /raw
device PartEx 2800000 HD MBR Sig:151767d7
osdevice PartEx 3ed200000 HD MBR Sig:151767d7
Bcdedit /set {bootmgr} flightsigning on
Bcdedit /set flightsigning on
Reboot after running the command.
Bcdedit /set {bootmgr} flightsigning off
Bcdedit /set flightsigning off
/usr/lib/dracut/skipcpio /boot/initramfs-$(uname -r).img | zcat | cpio -ivd
yum install MegaCli # CentOS
apt-get install megacli # Ubuntu
MegaCli -AdpAllInfo -aALL
MegaCli -CfgDsply -aALL
MegaCli -EncInfo -aALL
MegaCli -LDInfo -Lall -aALL
MegaCli -PDList -aALL
MegaCli -PDInfo -PhysDrv [E:S] -aALL
MegaCli -AdpBbuCmd -aALL
Syntax
curl [options...] url
Options:
These options are 'Case Sensitive' which is typical for Unix utilities but unusual for Microsoft Windows.
--abstract-unix-socket path Connect via abstract Unix domain socket
--anyauth Pick any authentication method
-a, --append Append to target file when uploading
--basic Use HTTP Basic Authentication
-A, --user-agent name Send User-Agent name to server
--cacert CA certificate CA certificate to verify peer against
--capath dir CA directory to verify peer against
-B, --use-ascii Use ASCII/text transfer
-E, --cert certificate[:password] Client certificate file and password
--cert-status Verify the status of the server certificate
--cert-type type Certificate file type (DER/PEM/ENG)
--ciphers SSL ciphers to use
--compressed Request compressed response
-K, --config file Read config from a file
--connect-timeout seconds Maximum time allowed for connection
--connect-to HOST1:PORT1:HOST2:PORT2 Connect to host
-C, --continue-at offset Resumed transfer offset
-b, --cookie data Send cookies from string/file
-c, --cookie-jar filename Write cookies to filename after operation
--create-dirs Create necessary local directory hierarchy
--crlf Convert LF to CRLF in upload
--crlfile file Get a CRL list in PEM format from the given file
-d, --data data HTTP POST data
--data-ascii data HTTP POST ASCII data
--data-binary data HTTP POST binary data
--data-raw data HTTP POST data, '@' allowed
--data-urlencode data HTTP POST data url encoded
--delegation LEVEL GSS-API delegation permission
--digest Use HTTP Digest Authentication
-q, --disable Disable .curlrc
--disable-eprt Inhibit using EPRT or LPRT
--disable-epsv Inhibit using EPSV
--dns-interface interface Interface to use for DNS requests
--dns-ipv4-addr address IPv4 address to use for DNS requests
--dns-ipv6-addr address IPv6 address to use for DNS requests
--dns-servers addresses DNS server addrs to use
-D, --dump-header filename Write the received headers to filename
--egd-file file EGD socket path for random data
--engine name Crypto engine to use
--expect100-timeout seconds How long to wait for 100-continue
-f, --fail Fail silently (no output at all) on HTTP errors
--fail-early Fail on first transfer error, do not continue
--false-start Enable TLS False Start
-F, --form name=content Specify HTTP multipart POST data
--form-string name=string Specify HTTP multipart POST data
--ftp-account data Account data string
--ftp-alternative-to-user command String to replace USER [name]
--ftp-create-dirs Create the remote dirs if not present
--ftp-method method Control CWD usage
--ftp-pasv Use PASV/EPSV instead of PORT
-P, --ftp-port address Use PORT instead of PASV
--ftp-pret Send PRET before PASV
--ftp-skip-pasv-ip Skip the IP address for PASV
--ftp-ssl-ccc Send CCC after authenticating
--ftp-ssl-ccc-mode active/passive Set CCC mode
--ftp-ssl-control Require SSL/TLS for FTP login, clear for transfer
-G, --get Put the post data in the URL and use GET
-g, --globoff Disable URL sequences and ranges using {} and []
-I, --head Show document info only
-H, --header header/@file Pass custom header(s) to server
-h, --help This help text
--hostpubmd5 md5 Acceptable MD5 hash of the host public key
-0, --http1.0 Use HTTP 1.0
--http1.1 Use HTTP 1.1
--http2 Use HTTP 2
--http2-prior-knowledge Use HTTP 2 without HTTP/1.1 Upgrade
--ignore-content-length Ignore the size of the remote resource
-i, --include Include protocol response headers in the output
-k, --insecure Allow insecure server connections when using SSL
--interface name Use network INTERFACE (or address)
-4, --ipv4 Resolve names to IPv4 addresses
-6, --ipv6 Resolve names to IPv6 addresses
-j, --junk-session-cookies Ignore session cookies read from file
--keepalive-time seconds Interval time for keepalive probes
--key key Private key file name
--key-type type Private key file type (DER/PEM/ENG)
--krb level Enable Kerberos with security level
--libcurl file Dump libcurl equivalent code of this command line
--limit-rate speed Limit transfer speed to RATE
-l, --list-only List only mode
--local-port num/range Force use of RANGE for local port numbers
-L, --location Follow redirects
--location-trusted Like --location, and send auth to other hosts
--login-options options Server login options
--mail-auth address Originator address of the original email
--mail-from address Mail from this address
--mail-rcpt address Mail from this address
-M, --manual Display the full manual
--max-filesize bytes Maximum file size to download
--max-redirs num Maximum number of redirects allowed
-m, --max-time time Maximum time allowed for the transfer
--metalink Process given URLs as metalink XML file
--negotiate Use HTTP Negotiate (SPNEGO) authentication
-n, --netrc Must read .netrc for user name and password
--netrc-file filename Specify FILE for netrc
--netrc-optional Use either .netrc or URL
-:, --next Make next URL use its separate set of options
--no-alpn Disable the ALPN TLS extension
-N, --no-buffer Disable buffering of the output stream
--no-keepalive Disable TCP keepalive on the connection
--no-npn Disable the NPN TLS extension
--no-sessionid Disable SSL session-ID reusing
--noproxy no-proxy-list List of hosts which do not use proxy
--ntlm Use HTTP NTLM authentication
--ntlm-wb Use HTTP NTLM authentication with winbind
--oauth2-bearer token OAuth 2 Bearer Token
-o, --output file Write to file instead of stdout
--pass phrase Pass phrase for the private key
--path-as-is Do not squash .. sequences in URL path
--pinnedpubkey hashes FILE/HASHES Public key to verify peer against
--post301 Do not switch to GET after following a 301
--post302 Do not switch to GET after following a 302
--post303 Do not switch to GET after following a 303
--preproxy [protocol:]host[:port] Use this proxy first
-#, --progress-bar Display transfer progress as a bar
--proto protocols Enable/disable PROTOCOLS
--proto-default protocol Use PROTOCOL for any URL missing a scheme
--proto-redir protocols Enable/disable PROTOCOLS on redirect
-x, --proxy [protocol:]host[:port] Use this proxy
--proxy-anyauth Pick any proxy authentication method
--proxy-basic Use Basic authentication on the proxy
--proxy-cacert file CA certificate to verify peer against for proxy
--proxy-capath dir CA directory to verify peer against for proxy
--proxy-cert cert[:passwd] Set client certificate for proxy
--proxy-cert-type type Client certificate type for HTTS proxy
--proxy-ciphers list SSL ciphers to use for proxy
--proxy-crlfile file Set a CRL list for proxy
--proxy-digest Use Digest authentication on the proxy
--proxy-header header/@file Pass custom header(s) to proxy
--proxy-insecure Do HTTPS proxy connections without verifying the proxy
--proxy-key key Private key for HTTPS proxy
--proxy-key-type type Private key file type for proxy
--proxy-negotiate Use HTTP Negotiate (SPNEGO) authentication on the proxy
--proxy-ntlm Use NTLM authentication on the proxy
--proxy-pass phrase Pass phrase for the private key for HTTPS proxy
--proxy-service-name name SPNEGO proxy service name
--proxy-ssl-allow-beast Allow security flaw for interop for HTTPS proxy
--proxy-tlsauthtype type TLS authentication type for HTTPS proxy
--proxy-tlspassword string TLS password for HTTPS proxy
--proxy-tlsuser name TLS username for HTTPS proxy
--proxy-tlsv1 Use TLSv1 for HTTPS proxy
-U, --proxy-user user:password Proxy user and password
--proxy1.0 host[:port] Use HTTP/1.0 proxy on given port
-p, --proxytunnel Operate through a HTTP proxy tunnel (using CONNECT)
--pubkey key SSH Public key file name
-Q, --quote Send command(s) to server before transfer
--random-file file File for reading random data from
-r, --range range Retrieve only the bytes within RANGE
--raw Do HTTP "raw"; no transfer decoding
-e, --referer URL Referrer URL
-J, --remote-header-name Use the header-provided filename
-O, --remote-name Write output to a file named as the remote file
--remote-name-all Use the remote file name for all URLs
-R, --remote-time Set the remote file's time on the local output
-X, --request command Specify request command to use
--request-target Specify the target for this request
--resolve host:port:address Resolve the host+port to this address
--retry num Retry request if transient problems occur
--retry-connrefused Retry on connection refused (use with --retry)
--retry-delay seconds Wait time between retries
--retry-max-time seconds Retry only within this period
--sasl-ir Enable initial response in SASL authentication
--service-name name SPNEGO service name
-S, --show-error Show error even when -s is used
-s, --silent Silent mode
--socks4 host[:port] SOCKS4 proxy on given host + port
--socks4a host[:port] SOCKS4a proxy on given host + port
--socks5 host[:port] SOCKS5 proxy on given host + port
--socks5-basic Enable username/password auth for SOCKS5 proxies
--socks5-gssapi Enable GSS-API auth for SOCKS5 proxies
--socks5-gssapi-nec Compatibility with NEC SOCKS5 server
--socks5-gssapi-service name SOCKS5 proxy service name for GSS-API
--socks5-hostname host[:port] SOCKS5 proxy, pass host name to proxy
-Y, --speed-limit speed Stop transfers slower than this
-y, --speed-time seconds Trigger 'speed-limit' abort after this time
--ssl Try SSL/TLS
--ssl-allow-beast Allow security flaw to improve interop
--ssl-no-revoke Disable cert revocation checks (WinSSL)
--ssl-reqd Require SSL/TLS
-2, --sslv2 Use SSLv2
-3, --sslv3 Use SSLv3
--stderr Where to redirect stderr
--suppress-connect-headers Suppress proxy CONNECT response headers
--tcp-fastopen Use TCP Fast Open
--tcp-nodelay Use the TCP_NODELAY option
-t, --telnet-option opt=val Set telnet option
--tftp-blksize value Set TFTP BLKSIZE option
--tftp-no-options Do not send any TFTP options
-z, --time-cond time Transfer based on a time condition
--tls-max VERSION Use TLSv1.0 or greater
--tlsauthtype type TLS authentication type
--tlspassword TLS password
--tlsuser name TLS user name
-1, --tlsv1 Use TLSv1.0 or greater
--tlsv1.0 Use TLSv1.0
--tlsv1.1 Use TLSv1.1
--tlsv1.2 Use TLSv1.2
--tlsv1.3 Use TLSv1.3
--tr-encoding Request compressed transfer encoding
--trace file Write a debug trace to FILE
--trace-ascii file Like --trace, but without hex output
--trace-time Add time stamps to trace/verbose output
--unix-socket path Connect through this Unix domain socket
-T, --upload-file file Transfer local FILE to destination
--url url URL to work with
-B, --use-ascii Use ASCII/text transfer
-u, --user user:password Server user and password
-A, --user-agent name Send User-Agent name to server
-v, --verbose Make the operation more talkative
-V, --version Show version number and quit
-w, --write-out format Use output FORMAT after completion
--xattr Store metadata in extended file attributes
curl is a powerful tool, please use it responsibly.
Examples
The example.com domain is used for these examples, it contains simple demonstration text and allows both HTTP and HTTPS connections.
Retrieve a web page, display the status code and all the raw content of the page:
C:\> curl https:example.com
StatusCode : 200
StatusDescription : OK
Content :
...
Retrieve a web page, display the status code and header information only:
C:\> curl -I https:example.com
HTTP /1.1 200 OK
Content-Encoding: gzip
...
Retrieve a web page, passing a specific User-Agent HTTP header (some websites use this to sniff the browser used):
C:\> curl -A "Mozilla FireFox(72.0)" https:example.com
Download the home page of example.com as a file (testing.html):
C:\> curl -o C:\demo\testing.html https:example.com/
Retrieve a file listing from an FTP server (null password):
C:\> curl ftp:anonymous@speedtest.tele2.net
caffeinate -u -t 3600
caffeinate -s command
Syntax
CALL [drive:][path]filename [parameters]
CALL :label [parameters]
CALL internal_cmd
Key:
pathname The batch program to run.
parameters Any command-line arguments.
:label Jump to a label in the current batch script.
internal_cmd Run an internal command, first expanding any variables in the argument.
The Microsoft help for the CALL command states: "Calls one batch program from another without stopping the parent batch program" to expand on this, it is true that the parent does not STOP, but it does PAUSE while the second script runs.
CALL a second batch file
The CALL command will launch a new batch file context along with any specified parameters. When the end of the second batch file is reached (or if EXIT is used), control will return to just after the initial CALL statement.
Arguments can be passed either as a simple string or using a variable:
CALL MyScript.cmd "1234"
CALL OtherScript.cmd %_MyVariable%
Example
::----------start main.cmd-----------
@Echo off
CALL function.cmd 10 first
Echo %_description% - %_number%
CALL function.cmd 15 second
Echo %_description% - %_number%
::----------end main.cmd-------------
::----------start function.cmd---------
@Echo off
:: Add 25 to %1
SET /a _number=%1 + 25
:: Store %2
SET _description=[%2]
::----------end function.cmd-----------
In many cases you will also want to use SETLOCAL and ENDLOCAL to keep variables in different batch files completely separate, this will avoid any potential problems if two scripts use the same variable name.
If you execute a second batch file without using CALL you may run into some buggy behaviour: if both batch files contain a label with the same name and you have previously used CALL to jump to that label in the first script, you will find execution of the second script starts at the same label. Even if the second label does not exist this will still raise an error "cannot find the batch label". This bug can be avoided by always using CALL.
CALL a subroutine (:label)
The CALL command will pass control to the statement after the label specified along with any specified parameters.
To exit the subroutine specify GOTO:eof this will transfer control to the end of the current subroutine.
A label is defined by a single colon followed by a name:
:myShinyLabel
If placed inside brackets, the label must be followed by at least one valid command, even just an ECHO or REM command.
The maximum length for a label is 127 characters, no spaces.
This is the basis of a batch file function.
CALL :sub_display 123
CALL :sub_display 456
ECHO All Done
GOTO :eof
:sub_display
ECHO The result is %1
EXIT /B
At the end of the subroutine an EXIT /B will return to the position where you used CALL
(GOTO :eof can also be used for this)
Call and optionally continue
In some cases you may want to call a second batch file (or subroutine) and continue only if it succeeded.
CALL SecondScript.cmd || goto :eof
This will goto:eof if SecondScript.cmd returns an errorlevel greater than zero, you can force an errorlevel by using Exit /b 1
Passing by Reference
In addition to passing numeric or string values on the command line, it is also possible to pass a variable name and then use the variable to transfer data between scripts or subroutines. Passing by reference is a slightly more advanced technique but can be essential if the string contains characters that are CMD delimiters or quotes, otherwise passing a string like Start & middle:"and & End is likely to break something.
@Echo off
Echo:
Set "var1=Red Pippin"
Set "var2=St Edmunds Pippin"
Set "var3=Egremont Russet"
Echo: before: var1=%var1% var2=%var2% var3=%var3%
call :myGetFunc var1 var2 var3
Echo: after: var1=%var1% var2=%var2% var3=%var3%
Echo:&pause&goto:eof
::----------------------------------------------
::-- Function section starts below
::----------------------------------------------
:myGetFunc - passing a variable by reference
Set "%~1=return64"
Set "%~3=return65"
EXIT /B
Buggy behaviour when using CALL
Redirection via a pipe '|' does not always work as expected.
This will work:
CALL :function >file.txt
This will fail:
CALL :function | more
More details can be found in this SO question: Why does delayed expansion fail when inside a piped block of code?
If the CALL command contains a caret character within a quoted string "test^ing" , the carets will be doubled.
Advanced usage : CALLing internal commands
CALL command [command_parameters]
CALL can also be used to run any internal command (SET, ECHO etc) with the exception of FOR and IF.
CALL will expand any variables passed on the same line. CALL REM only partly works: redirection operators, conditional execution operators and brackets will be not remarked.
This is undocumented behaviour, in fact whenever CALL is run without a : prefix, it will always search disk for a batch file/executable called command before running the internal command. The effect of this extra disc access is that CALL SET is significantly slower than CALL, its use in loops or with a large number of variables should be avoided.
Example
@Echo off
SETLOCAL
set _server=frodo
set _var=_server
CALL SET _result=%%%_var%%%
echo %_result%
The line shown in bold has the '%' symbols tripled, CALL will expand this to: SET _result=frodo
Each CALL does one substitution of the variables. (You can also do CALL CALL... for multiple substitutions)
In many cases, DelayedExpansion is a better/faster method:
@Echo Off
Setlocal EnableDelayedExpansion
Set _server=frodo
Set _var=_server
Set _result=!%_var%!
Echo %_result%
Errorlevels
If you run CALL SET this will reset ERRORLEVEL = 0 even though normally SET ... will fail to reset an ERRORLEVEL
If you CALL a subroutine, the ERRORLEVEL will be left unchanged
If you CALL a subroutine, with a label that does not exist ERRORLEVEL will be set to 1
(call ) will set the ERRORLEVEL to 0.
(call) will set the ERRORLEVEL to 1.
If you CALL an executable or resource kit utility make sure it's available on the machine where the batch will be running, test for it's existence with an IF command and throw an error if missing.
CALL is an internal command, (internally it is closely related to GOTO).
If Command Extensions are disabled, the CALL command will not accept batch labels.
Syntax
BOOTREC /FIXMBR Write an MBR to the system partition.
BOOTREC /FIXBOOT Writes a new boot sector onto the system partition.
BOOTREC /SCANOS Scans all disks for Windows installations and display entries not currently in the BCD store.
BOOTREC /REBUILDBCD Scans all disks for Windows installations and provide a choice of which entries to add to the BCD store.
/FixMbr does not overwrite the existing partition table. Use this option when you must resolve MBR corruption issues, or when you have to remove nonstandard code from the MBR.
Use /FixBoot if The boot sector was damaged or replaced.
Examples
Use Bootrec.exe to troubleshoot a "Bootmgr Is Missing" error.
If rebuilding the BCD store doesn't resolve the startup issue, you can export and delete the BCD store and then run this option again. By doing this, you make sure that the BCD store is completely rebuilt. To do this, type the following commands at the Windows RE command prompt:
bcdedit /export C:\BCD_Backup
c:
cd boot
attrib bcd -s -h -r
ren c:\boot\bcd bcd.old
bootrec /RebuildBcd
scsi_logging_level -s --ioctl=7
scsi_logging_level -s --midlevel=7
Syntax
devcon.exe [-r] [-m:\machine] command [arg...]
devcon.exe help command
Key
-r Reboot the machine after command is complete, if needed.
machine Name of target machine.
command The command to perform (see below).
arg... One or more arguments if required by command.
Commands:
classfilter Allow modification of class filters.
classes List all device setup classes.
disable Disable devices that match the specific hardware/instance ID.
driverfiles List driver files installed for devices.
drivernodes List all the driver nodes of devices.
enable Enable devices that match the specific hardware/instance ID.
find Find devices that match the specific hardware/instance ID.
findall Find devices including those that are not present.
help Display this information.
hwids List hardware ID's of devices.
install Manually install a device.
listclass List all devices for a setup class.
reboot Reboot local machine.
remove Remove devices that match the specific hardware/instance ID.
rescan Scan for new hardware.
resources List hardware resources of devices.
restart Restart devices that match the specific hardware/instance ID.
stack List expected driver stack of devices.
status List running status of devices.
update Manually update a device.
UpdateNI Manually update a device without user prompt
SetHwID Add, delete, and change the order of hardware IDs of root-enumerated devices.
DevCon is not redistributable. It is provided for use as a debugging and development tool.
Examples
List all known PCI devices on the computer pc64.
devcon -m:\pc64 find pci*
Install a new instance of the Microsoft loopback adaptor and restart if required. This creates a new root-enumerated device node with which you can install a "virtual device," such as the loopback adaptor.
devcon -r install %WINDIR%\Inf\Netloop.inf *MSLOOP
List all known setup classes. Displays both the short name and the descriptive name.
devcon classes
Lists files that are associated with each device in the ports setup class.
devcon driverfiles =ports
Disable all devices that have a hardware ID that ends in "MSLOOP" (including "*MSLOOP").
devcon disable *MSLOOP
List all compatible drivers for the device ROOT\PCI_HAL\PNP0A03. This can be used to determine why an integral device information (.inf) file was chosen, instead of a third-party .inf file.
devcon drivernodes @ROOT\PCI_HAL\PNP0A03
Enable all devices that have a hardware ID of "*MSLOOP". The single quotation mark indicates that the hardware ID must be taken literally (in other words, the asterisk ["*"] actually is an asterisk; it is not a wildcard character).
devcon enable '*MSLOOP
List device instances of all devices that are present on the local computer.
devcon find *
List all known peripheral component interconnect (PCI) devices that are on the local computer (this command assumes that a device is PCI if it has a hardware ID that is prefixed by "PCI\").
devcon find pci*
List devices that are a member of the ports setup class and that contain "PNP" in their hardware ID.
devcon find =ports *pnp*
List devices that are present that are a member of the ports setup class and that are in the "root" branch of the enum tree (the instance ID is prefixed by "root\"). Note that you should not make any programmatic assumption about how an instance ID is formatted. To determine root devices, you can look at device status bits. This feature is included in DevCon to aid in debugging.
devcon find =ports @root*
List "nonpresent" devices and devices that are present for the ports class. This includes devices that have been removed, devices that have been moved from one slot to another and, in some cases, devices that have been enumerated differently due to a BIOS change.
devcon findall =ports
List all devices that are present for each class named (in this case, USB and 1394).
devcon listclass usb 1394
Remove all USB devices. Devices that are removed are listed with their removal status.
devcon remove @usb*
Rescan for new Plug and Play devices.
devcon rescan
List the resources that are used by all devices in the ports setup class.
devcon resources =ports
Restart the loopback adaptor ROOT*MSLOOP\0000. The single quotation mark in the command indicates that the instance ID must be taken literally.
devcon restart =net @'ROOT*MSLOOP\0000
List all hardware IDs of mouse class devices on the system.
devcon hwids=mouse
Assign the hardware ID, beep, to the legacy beep device.
devcon sethwid @ROOT\LEGACY_BEEP\0000 := beep
List the status of each device present that has an instance ID that begins with "pci\".
devcon status @pci*
List the status of an Advanced Configuration and Power Interface (ACPI)-enumerated serial port.
devcon status @ACPI\PNP0501\1
List the status of all COM ports.
devcon status *PNP05*
Errorlevels returned by DevCon.exe:
0 = success.
1 - restart is required.
2 = failure.
3 = syntax error.
systemctl list-units
systemctl status foo.service
systemctl start foo.service
systemctl restart foo.service
systemctl stop foo.service
systemctl reload foo.service
systemctl enable foo.service
systemctl disable foo.service
systemctl list-dependencies foo.service
systemctl list-units --type=target
systemctl isolate foo.target
systemctl enable foo.target
blktrace /dev/sdb -a PC -o - | blkparse -i -
Syntax
CHANGEPK /ProductKey NewProductKey
This can be used to move from Home > Pro Education, from Pro > Education, from Pro > Enterprise a full list of the supported Edition upgrades and downgrades is available on docs.microsoft.com
You can also upgrade using slmgr.vbs and a KMS client setup key.
Examples
Upgrade to Windows 10 Enterprise:
C:\> Cscript.exe c:\windows\system32\slmgr.vbs /ipk NPPR9-FWDCX-D2C8J-H872K-2YT43
a simple function
func functionName() {}
function with parameters (again, types go after identifiers)
func functionName(param1 string, param2 int) {}
multiple parameters of the same type
func functionName(param1, param2 int) {}
return type declaration
func functionName() int {
return 42
}
Can return multiple values at once
func returnMulti() (int, string) {
return 42, "foobar"
}
var x, str = returnMulti()
Return multiple named results simply by return
func returnMulti2() (n int, s string) {
n = 42
s = "foobar"
n and s will be returned
return
}
var x, str = returnMulti2()
### Functions As Values And Closures
func main() {
assign a function to a name
add := func(a, b int) int {
return a + b
}
use the name to call the function
fmt.Println(add(3, 4))
}
Closures, lexically scoped: Functions can access values that were
in scope when defining the function
func scope() func() int{
outer_var := 2
foo := func() int { return outer_var}
return foo
}
func another_scope() func() int{
won't compile because outer_var and foo not defined in this scope
outer_var = 444
return foo
}
Closures: don't mutate outer vars, instead redefine them!
func outer() (func() int, int) {
outer_var := 2
inner := func() int {
outer_var += 99 attempt to mutate outer_var from outer scope
return outer_var => 101 (but outer_var is a newly redefined
variable visible only inside inner)
}
return inner, outer_var => 101, 2 (outer_var is still 2, not mutated by foo!)
}
### Variadic Functions
func main() {
fmt.Println(adder(1, 2, 3)) 6
fmt.Println(adder(9, 9)) 18
nums := []int{10, 20, 30}
fmt.Println(adder(nums...)) 60
}
By using ... before the type name of the last parameter you can indicate that it takes zero or more of those parameters.
The function is invoked like any other function except we can pass as many arguments as we want.
func adder(args ...int) int {
total := 0
for _, v := range args { Iterates over the arguments whatever the number.
total += v
}
return total
}
ocamlc hello.ml -o hello
ocamlopt hello.ml -o hello
ocaml
utop
Syntax
CMD [charset] [options]
CMD [charset] [options] [/C Command]
CMD [charset] [options] [/K Command]
Options
/C Run Command and then terminate
/K Run Command and then remain open, at the CMD prompt.
This is useful for testing, e.g. to examine variables.
Command : The command, program or batch script to be run.
This can even be several commands separated with '&'
(the whole should also be surrounded by "quotes")
/T:fg Sets the foreground/background colours
/A Output ANSI characters.
/U Output UNICODE characters (UCS-2 le).
These options will affect piping or redirecting to a file.
Most common text files are ANSI, use these switches when
you need to convert the character set.
/D Ignore registry AutoRun commands
HKLM | HKCU \Software\Microsoft\Command Processor\AutoRun
/E:ON Enable CMD Command Extensions (default)
/X Enable CMD Command Extensions (old switch for compatibility)
/E:OFF Disable CMD Command Extensions
/Y Disable CMD Command Extensions (old switch for compatibility)
/F:ON Enable auto-completion of pathnames entered at the CMD prompt
/F:OFF Disable auto-completion of pathnames entered at the CMD prompt (default)
At the command prompt Ctrl-D gives folder name completion and Ctrl-F gives File and folder name completion.
These key-strokes will display the first matching path. Thereafter, repeated pressing of the same control key will cycle through the list of matching paths. Pressing SHIFT with the control key will move through the list backwards.
/Q Turn echo off
/S Strip " quote characters from command.
If command starts with a quote, the first and last quote chars in command
will be removed, whether /s is specified or not.
/V:ON Enable delayed environment variable expansion
this allows a FOR loop to specify !variable! instead of %variable%
expanding the variable at execution time instead of at input time.
/V:OFF
Disable delayed environment expansion.
Delayed Environment expansion can also be set with SETLOCAL
If /C or /K is specified, then the remainder of the command line is processed as an immediate command in the new shell. Multiple commands separated by the command separator '&' or '&&' are accepted if surrounded by quotes.
In Windows Explorer, you can type "cmd" in the address bar to open a prompt at the current location.
For more detail about the CMD shell: QuickEdit, handing quotes, max line length etc, see the CMD Syntax page.
If you start a second nested CMD shell (or PowerShell), this will be added to the TITLE of the CMD/terminal window, when you EXIT back to the initial shell, the Title will also revert making it possible to track how many nested shells you have open.
ErrorLevel
CMD /C will return an errorlevel, for example CMD /c dir Z: where the drive Z: does not exist, will return %errorlevel% = 1 to the calling CMD shell.
Launching CMD/batch files from a UNC path
While most command line utilities do fully support UNC paths, they cannot be set as the current directory. Launching a batch file from a UNC path will implicitly run CMD.exe with that UNC path, this will often return the error: path is an invalid current directory path. UNC paths are not supported. Defaulting to Windows directory.
This can be dangerous if your batch file makes any assumptions about the current directory,
e.g. if it includes the line DEL *.ico, that will delete .ico files from the Windows directory instead of the folder where the batch file resides.
If you are confident that the batch file won't be affected by this, you can suppress the error in one of two ways: Add a CLS command as the first line of the batch script, or add the registry key DisableUNCCheck as described in Q156276
Alternatively start the batch file with pushd "%~dp0"
That will change directory to your batch file location (%0), and for UNC paths it will auto-create a temporary drive map.
Launching CMD/batch files from PowerShell
When calling CMD from PowerShell the --% operator can be used to control when $ symbols and quoted expressions will be interpreted/expanded by PowerShell:
cmd.exe --% /c dir "C:\financial $accounts\" /w
Anything to the left of --% will be expanded:
$folder = 'C:\financial $accounts\'
cmd.exe /c dir $folder --%/w
Inheritance
A new CMD.exe session can be instantiated in several ways, explicitly starting a new CMD session from an existing CMD shell, CALLing a batch file or implicit instantiation caused by piping a command or running a FOR /F command.
In all these cases, only the environment variable values are inherited by the new CMD session. Delayed expansion state, Command extension state and Echo state will all revert back to the default state based on the registry.
For more detail on inheritance and expansion see this StackOverflow thread.
Command Extensions
Much of the functionality of CMD.exe can be disabled - this will affect all the internal commands, and most dynamic/volatile environment variables (%TIME% , %DATE% , %RANDOM% , %CD% etc)
Command Extensions are enabled by default.
This can be changed by setting a value in the registry: HKCU\Software\Microsoft\Command Processor\EnableExtensions
Command Extensions can also be turned on or off by running CMD /e:on or CMD /e:off
or run SETLOCAL EnableExtensions (SetLocal will take precedence)
Forum thread: Checking if command extensions are available.
Examples
Run a program and pass a Filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a Long Filename:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in Program Path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in Program Path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
Spaces in Program Path + parameters with spaces:
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
CMD will strip the outer quotes if there is a double quote at the start and end so you can also cheat and write the above as:
CMD /k @"c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space"
Launch Demo1 and then Launch Demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
curl http:path.to.the/file
curl http:example.com/file.zip -o new_file.zip
curl -O URLOfFirstFile -O URLOfSecondFile
curl http:example.com/pic[1-24].jpg
curl -L http:example.com/file
curl -u username:password URL
curl -x proxysever.server.com:PORT http:addressiwantto.access
curl -u username:password -O ftp:example.com/pub/file.zip
curl ftp:username:password@example.com
curl -C - -o partial_file.zip http:example.com/file.zip
curl -I http:example.com
curl http:ifconfig.me/all/json
curl --limit-rate 1000B -O http:path.to.the/file
curl -F "name=user" -F "password=test" http:example.com
curl -H "Content-Type: application/json" -X POST -d '{"user":"bob","pass":"123"}' http:example.com
curl -F 'sprunge=<-' sprunge.us
SHELL=/bin/bash
- - - - -
| | | | |
| | | | +- day of week (0 - 7) (where sunday is 0 and 7)
| | | +--- month (1 - 12)
| | +----- day (1 - 31)
| +------- hour (0 - 23)
+--------- minute (0 - 59)
*/15 * * * * /home/user/command.sh
0 0 * * * /home/user/command.sh
5 8 * * 6 /home/user/command.sh
EVAL script numkeys key [key ...] arg [arg ...]
EVALSHA sha1 numkeys key [key ...] arg [arg ...]
SCRIPT DEBUG YES|SYNC|NO
SCRIPT EXISTS sha1 [sha1 ...]
SCRIPT FLUSH
SCRIPT KILL
SCRIPT LOAD script
smbclient -L
smbclient
dhcpdump -i eth0
`i32` is the type for 32-bit signed integers
fn add2(x: i32, y: i32) -> i32 {
Implicit return (no semicolon)
x + y
}
fn main() {
Numbers
Immutable bindings
let x: i32 = 1;
Integer/float suffixes
let y: i32 = 13i32;
let f: f64 = 1.3f64;
Type inference
Most of the time, the Rust compiler can infer what type a variable is, so
you don’t have to write an explicit type annotation.
Throughout this tutorial, types are explicitly annotated in many places,
but only for demonstrative purposes. Type inference can handle this for
you most of the time.
let implicit_x = 1;
let implicit_f = 1.3;
Arithmetic
let sum = x + y + 13;
Mutable variable
let mut mutable = 1;
mutable = 4;
mutable += 2;
Strings
String literals
let x: &str = "hello world!";
Printing
println!("{} {}", f, x); 1.3 hello world
A `String` – a heap-allocated string
let s: String = "hello world".to_string();
A string slice – an immutable view into another string
This is basically an immutable pair of pointers to a string – it doesn’t
actually contain the contents of a string, just a pointer to
the begin and a pointer to the end of a string buffer,
statically allocated or contained in another object (in this case, `s`)
let s_slice: &str = &s;
println!("{} {}", s, s_slice); hello world hello world
Vectors/arrays
A fixed-size array
let four_ints: [i32; 4] = [1, 2, 3, 4];
A dynamic array (vector)
let mut vector: Vec
vector.push(5);
A slice – an immutable view into a vector or array
This is much like a string slice, but for vectors
let slice: &[i32] = &vector;
Use `{:?}` to print something debug-style
println!("{:?} {:?}", vector, slice); [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
Tuples
A tuple is a fixed-size set of values of possibly different types
let x: (i32, &str, f64) = (1, "hello", 3.4);
Destructuring `let`
let (a, b, c) = x;
println!("{} {} {}", a, b, c); 1 hello 3.4
Indexing
println!("{}", x.1); hello
}
腾图小抄 SCWY.net v0.03 小抄561条 自2022-01-02访问318093次