mirror of
https://github.com/cheat/cheat.git
synced 2024-12-21 12:15:06 +01:00
Re-wrote from scratch in Golang
- Re-implemented the project in Golang, and deprecated Python entirely - Implemented several new, long-requested features - Refactored cheatsheets into a separate repository
This commit is contained in:
parent
307c4e6ad6
commit
e5114a3e76
7
.gitignore
vendored
7
.gitignore
vendored
@ -1,8 +1 @@
|
||||
*.log
|
||||
*.pyc
|
||||
.env
|
||||
.vagrant
|
||||
MANIFEST
|
||||
build
|
||||
cheat.egg-info
|
||||
dist
|
||||
|
@ -1,29 +0,0 @@
|
||||
Contributing
|
||||
============
|
||||
If you would like to contribute cheetsheets or program functionality, please
|
||||
fork this repository, make your changes, and submit a pull request against the
|
||||
`master` branch.
|
||||
|
||||
|
||||
## Python standards ##
|
||||
Python code should conform to [PEP 8][].
|
||||
|
||||
|
||||
## Cheatsheet Format ##
|
||||
Please pattern your cheatsheets after the following:
|
||||
|
||||
```sh
|
||||
# To extract an uncompressed archive:
|
||||
tar -xvf /path/to/foo.tar
|
||||
|
||||
# To create an uncompressed archive:
|
||||
tar -cvf /path/to/foo.tar /path/to/foo/
|
||||
|
||||
# To extract a .gz archive:
|
||||
tar -xzvf /path/to/foo.tgz
|
||||
```
|
||||
|
||||
If you are submitting a cheatsheet that contains side-by-side columns of text,
|
||||
please align the columns using spaces rather than tabs.
|
||||
|
||||
[PEP 8]: http://legacy.python.org/dev/peps/pep-0008/
|
2
LICENSE
2
LICENSE
@ -1,2 +0,0 @@
|
||||
This program is dual-licensed under the MIT and GPL3 licenses. See the licenses
|
||||
directory for the license text in full.
|
@ -1,6 +0,0 @@
|
||||
include CHANGELOG
|
||||
include CONTRIBUTING.md
|
||||
include LICENSE
|
||||
include README.md
|
||||
include licenses/gpl-3.txt
|
||||
include licenses/mit.txt
|
224
README.md
224
README.md
@ -1,5 +1,3 @@
|
||||
[![PyPI](https://img.shields.io/pypi/v/cheat.svg)](https://pypi.python.org/pypi/cheat/)
|
||||
|
||||
cheat
|
||||
=====
|
||||
`cheat` allows you to create and view interactive cheatsheets on the
|
||||
@ -9,6 +7,8 @@ remember.
|
||||
|
||||
![The obligatory xkcd](http://imgs.xkcd.com/comics/tar.png 'The obligatory xkcd')
|
||||
|
||||
Use `cheat` with [cheatsheets][].
|
||||
|
||||
|
||||
Example
|
||||
-------
|
||||
@ -19,7 +19,7 @@ Google, you may run:
|
||||
cheat tar
|
||||
```
|
||||
|
||||
You will be presented with a cheatsheet resembling:
|
||||
You will be presented with a cheatsheet resembling the following:
|
||||
|
||||
```sh
|
||||
# To extract an uncompressed archive:
|
||||
@ -38,142 +38,158 @@ tar -xjvf '/path/to/foo.tgz'
|
||||
tar -cjvf '/path/to/foo.tgz' '/path/to/foo/'
|
||||
```
|
||||
|
||||
To see what cheatsheets are available, run `cheat -l`.
|
||||
|
||||
Note that, while `cheat` was designed primarily for \*nix system administrators,
|
||||
it is agnostic as to what content it stores. If you would like to use `cheat`
|
||||
to store notes on your favorite cookie recipes, feel free.
|
||||
|
||||
|
||||
Installing
|
||||
----------
|
||||
It is recommended to install `cheat` with `pip`:
|
||||
|
||||
```sh
|
||||
pip install cheat --user
|
||||
```
|
||||
|
||||
(You must ensure that the `Location` identified by `pip show cheat` exists on
|
||||
your `PATH`.)
|
||||
|
||||
[Other installation methods are available][installing].
|
||||
|
||||
|
||||
Modifying Cheatsheets
|
||||
---------------------
|
||||
The value of `cheat` is that it allows you to create your own cheatsheets - the
|
||||
defaults are meant to serve only as a starting point, and can and should be
|
||||
modified.
|
||||
|
||||
Cheatsheets are stored in the `~/.cheat/` directory, and are named on a
|
||||
per-keyphrase basis. In other words, the content for the `tar` cheatsheet lives
|
||||
in the `~/.cheat/tar` file.
|
||||
|
||||
Provided that you have a `CHEAT_EDITOR`, `VISUAL`, or `EDITOR` environment
|
||||
variable set, you may edit cheatsheets with:
|
||||
|
||||
```sh
|
||||
cheat -e foo
|
||||
```
|
||||
|
||||
If the `foo` cheatsheet already exists, it will be opened for editing.
|
||||
Otherwise, it will be created automatically.
|
||||
|
||||
After you've customized your cheatsheets, I urge you to track `~/.cheat/` along
|
||||
with your [dotfiles][].
|
||||
`cheat` has no dependencies. To install it, download the executable from the
|
||||
[releases][] page and place it on your `PATH`.
|
||||
|
||||
|
||||
Configuring
|
||||
-----------
|
||||
|
||||
### Setting a CHEAT_USER_DIR ###
|
||||
Personal cheatsheets are saved in the `~/.cheat` directory by default, but you
|
||||
can specify a different default by exporting a `CHEAT_USER_DIR` environment
|
||||
variable:
|
||||
### conf.yml ###
|
||||
`cheat` is configured by a YAML file that can be generated with `cheat --init`:
|
||||
|
||||
```sh
|
||||
export CHEAT_USER_DIR='/path/to/my/cheats'
|
||||
mkdir -p ~/.config/cheat && cheat --init > ~/.config/cheat/conf.yml
|
||||
```
|
||||
|
||||
### Setting a CHEAT_PATH ###
|
||||
You can additionally instruct `cheat` to look for cheatsheets in other
|
||||
directories by exporting a `CHEAT_PATH` environment variable:
|
||||
By default, the config file is assumed to exist on an XDG-compliant
|
||||
configuration path like `~/.config/cheat/conf.yml`. If you would like to store
|
||||
it elsewhere, you may export a `CHEAT_CONFIG_PATH` environment variable that
|
||||
specifies its path:
|
||||
|
||||
```sh
|
||||
export CHEAT_PATH='/path/to/my/cheats'
|
||||
export CHEAT_CONFIG_PATH="~/.dotfiles/cheat/conf.yml"
|
||||
```
|
||||
|
||||
You may, of course, append multiple directories to your `CHEAT_PATH`:
|
||||
Cheatsheets
|
||||
-----------
|
||||
Cheatsheets are plain-text files with no file extension, and are named
|
||||
according to the command used to view them:
|
||||
|
||||
```sh
|
||||
export CHEAT_PATH="$CHEAT_PATH:/path/to/more/cheats"
|
||||
cheat tar # file is named "tar"
|
||||
cheat foo/bar # file is named "bar", in a "foo" subdirectory
|
||||
```
|
||||
|
||||
You may view which directories are on your `CHEAT_PATH` with `cheat -d`.
|
||||
Cheatsheet text may optionally be preceeded by a YAML frontmatter header that
|
||||
assigns tags and specifies syntax:
|
||||
|
||||
### Enabling Syntax Highlighting ###
|
||||
`cheat` can optionally apply syntax highlighting to your cheatsheets. To
|
||||
enable syntax highlighting, export a `CHEAT_COLORS` environment variable:
|
||||
```
|
||||
---
|
||||
syntax: javascript
|
||||
tags: [ array, map ]
|
||||
---
|
||||
// To map over an array:
|
||||
const squares = [1, 2, 3, 4].map(x => x * x);
|
||||
```
|
||||
|
||||
The `cheat` executable includes no cheatsheets, but [community-sourced
|
||||
cheatsheets are available][cheatsheets].
|
||||
|
||||
|
||||
Cheatpaths
|
||||
----------
|
||||
Cheatsheets are stored on "cheatpaths", which are directories that contain
|
||||
cheetsheets. Cheatpaths are specified in the `conf.yml` file.
|
||||
|
||||
It can be useful to configure `cheat` against multiple cheatpaths. A common
|
||||
pattern is to store cheatsheets from multiple repositories on individual
|
||||
cheatpaths:
|
||||
|
||||
```yaml
|
||||
# conf.yml:
|
||||
# ...
|
||||
cheatpaths:
|
||||
- name: community # a name for the cheatpath
|
||||
path: ~/documents/cheat/community # the path's location on the filesystem
|
||||
tags: [ community ] # these tags will be applied to all sheets on the path
|
||||
readonly: true # if true, `cheat` will not create new cheatsheets here
|
||||
|
||||
- name: personal
|
||||
path: ~/documents/cheat/personal # this is a separate directory and repository than above
|
||||
tags: [ personal ]
|
||||
readonly: false # new sheets may be written here
|
||||
# ...
|
||||
```
|
||||
|
||||
The `readonly` option instructs `cheat` not to edit (or create) any cheatsheets
|
||||
on the path. This is useful to prevent merge-conflicts from arising on upstream
|
||||
cheatsheet repositories.
|
||||
|
||||
If a user attempts to edit a cheatsheet on a read-only cheatpath, `cheat` will
|
||||
transparently copy that sheet to a writeable directory before opening it for
|
||||
editing.
|
||||
|
||||
|
||||
Usage
|
||||
-----
|
||||
To view a cheatsheet:
|
||||
|
||||
```sh
|
||||
export CHEAT_COLORS=true
|
||||
cheat tar # a "top-level" cheatsheet
|
||||
cheat foo/bar # a "nested" cheatsheet
|
||||
```
|
||||
|
||||
Note that [pygments][] must be installed on your system for this to work.
|
||||
|
||||
`cheat` ships with both light and dark colorschemes to support terminals with
|
||||
different background colors. A colorscheme may be selected via the
|
||||
`CHEAT_COLORSCHEME` envvar:
|
||||
To edit a cheatsheet:
|
||||
|
||||
```sh
|
||||
export CHEAT_COLORSCHEME=light # must be 'light' (default) or 'dark'
|
||||
cheat -e tar # opens the "tar" cheatsheet for editing, or creates it if it does not exist
|
||||
cheat -e foo/bar # nested cheatsheets are accessed like this
|
||||
```
|
||||
|
||||
#### Specifying a Syntax Highlighter ####
|
||||
You may manually specify which syntax highlighter to use for each cheatsheet by
|
||||
wrapping the sheet's contents in a [Github-Flavored Markdown code-fence][gfm].
|
||||
To view the configured cheatpaths:
|
||||
|
||||
Example:
|
||||
|
||||
<pre>
|
||||
```sql
|
||||
-- to select a user by ID
|
||||
SELECT *
|
||||
FROM Users
|
||||
WHERE id = 100
|
||||
```sh
|
||||
cheat -d
|
||||
```
|
||||
</pre>
|
||||
|
||||
If no syntax highlighter is specified, the `bash` highlighter will be used by
|
||||
default.
|
||||
To list all available cheatsheets:
|
||||
|
||||
### Enabling Search Match Highlighting ###
|
||||
`cheat` can optionally be configured to highlight search term matches in search
|
||||
results. To do so, export a `CHEAT_HIGHLIGHT` environment variable with a value
|
||||
of one of the following:
|
||||
```sh
|
||||
cheat -l
|
||||
```
|
||||
|
||||
- blue
|
||||
- cyan
|
||||
- green
|
||||
- grey
|
||||
- magenta
|
||||
- red
|
||||
- white
|
||||
- yellow
|
||||
To list all cheatsheets that are tagged with "networking":
|
||||
|
||||
Note that the `termcolor` module must be installed on your system for this to
|
||||
work.
|
||||
```sh
|
||||
cheat -l -t networking
|
||||
```
|
||||
|
||||
To list all cheatsheets on the "personal" path:
|
||||
|
||||
```sh
|
||||
cheat -l -p personal
|
||||
```
|
||||
|
||||
To search for the phrase "ssh" among cheatsheets:
|
||||
|
||||
```sh
|
||||
cheat -s ssh
|
||||
```
|
||||
|
||||
To search (by regex) for cheatsheets that contain an IP address:
|
||||
|
||||
```sh
|
||||
cheat -r -s '(?:[0-9]{1,3}\.){3}[0-9]{1,3}'
|
||||
```
|
||||
|
||||
Flags may be combined in inuitive ways. Example: to search sheets on the
|
||||
"personal" cheatpath that are tagged with "networking" and match a regex:
|
||||
|
||||
```sh
|
||||
cheat -p personal -t networking -s --regex '(?:[0-9]{1,3}\.){3}[0-9]{1,3}'
|
||||
```
|
||||
|
||||
|
||||
See Also:
|
||||
---------
|
||||
- [Enabling Command-line Autocompletion][autocompletion]
|
||||
- [Related Projects][related-projects]
|
||||
Advanced Usage
|
||||
--------------
|
||||
`cheat` may be integrated with [fzf][]. See [fzf.bash][bash] for instructions.
|
||||
(Support for other shells will be added in future releases.)
|
||||
|
||||
|
||||
[autocompletion]: https://github.com/cheat/cheat/wiki/Enabling-Command-line-Autocompletion
|
||||
[dotfiles]: http://dotfiles.github.io/
|
||||
[gfm]: https://help.github.com/articles/creating-and-highlighting-code-blocks/
|
||||
[installing]: https://github.com/cheat/cheat/wiki/Installing
|
||||
[pygments]: http://pygments.org/
|
||||
[related-projects]: https://github.com/cheat/cheat/wiki/Related-Projects
|
||||
[Releases]: https://github.com/cheat/cheat/releases
|
||||
[bash]: https://github.com/cheat/cheat/blob/master/scripts/fzf.bash
|
||||
[cheatsheets]: https://github.com/cheat/cheatsheets
|
||||
[fzf]: https://github.com/junegunn/fzf
|
||||
|
20
Vagrantfile
vendored
20
Vagrantfile
vendored
@ -1,20 +0,0 @@
|
||||
# -*- mode: ruby -*-
|
||||
# vi: set ft=ruby :
|
||||
|
||||
Vagrant.configure("2") do |config|
|
||||
config.vm.box = "ubuntu/bionic64"
|
||||
|
||||
config.vm.provider "virtualbox" do |vb|
|
||||
vb.memory = "512"
|
||||
end
|
||||
|
||||
config.vm.provision "shell", privileged: false, inline: <<-SHELL
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y python-pip
|
||||
sudo -H pip install flake8
|
||||
pip install --user docopt pygments termcolor
|
||||
cd /vagrant/ && python setup.py install --user
|
||||
echo 'export PATH=$PATH:/home/vagrant/.local/bin' >> /home/vagrant/.bashrc
|
||||
SHELL
|
||||
|
||||
end
|
13
bin/build_devel.sh
Executable file
13
bin/build_devel.sh
Executable file
@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
|
||||
# locate the lambo project root
|
||||
BINDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
APPDIR=$(readlink -f "$BINDIR/..")
|
||||
|
||||
# compile the executable
|
||||
cd "$APPDIR/cmd/cheat"
|
||||
go clean && go generate && go build
|
||||
mv "$APPDIR/cmd/cheat/cheat" "$APPDIR/dist/cheat"
|
||||
|
||||
# display a build checksum
|
||||
md5sum "$APPDIR/dist/cheat"
|
14
bin/build_release.sh
Executable file
14
bin/build_release.sh
Executable file
@ -0,0 +1,14 @@
|
||||
#!/bin/bash
|
||||
|
||||
# locate the lambo project root
|
||||
BINDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
APPDIR=$(readlink -f "$BINDIR/..")
|
||||
|
||||
# build embeds
|
||||
cd "$APPDIR/cmd/cheat"
|
||||
go clean && go generate
|
||||
|
||||
# compile AMD64 for Linux, OSX, and Windows
|
||||
env GOOS=darwin GOARCH=amd64 go build -o "$APPDIR/dist/cheat-darwin-amd64" "$APPDIR/cmd/cheat"
|
||||
env GOOS=linux GOARCH=amd64 go build -o "$APPDIR/dist/cheat-linux-amd64" "$APPDIR/cmd/cheat"
|
||||
env GOOS=windows GOARCH=amd64 go build -o "$APPDIR/dist/cheat-win-amd64.exe" "$APPDIR/cmd/cheat"
|
105
bin/cheat
105
bin/cheat
@ -1,105 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""cheat
|
||||
|
||||
Create and view cheatsheets on the command line.
|
||||
|
||||
Usage:
|
||||
cheat <cheatsheet>
|
||||
cheat -e <cheatsheet>
|
||||
cheat -s <keyword>
|
||||
cheat -l
|
||||
cheat -d
|
||||
cheat -v
|
||||
|
||||
Options:
|
||||
-d --directories List directories on $CHEAT_PATH
|
||||
-e --edit Edit cheatsheet
|
||||
-l --list List cheatsheets
|
||||
-s --search Search cheatsheets for <keyword>
|
||||
-v --version Print the version number
|
||||
|
||||
Examples:
|
||||
|
||||
To view the `tar` cheatsheet:
|
||||
cheat tar
|
||||
|
||||
To edit (or create) the `foo` cheatsheet:
|
||||
cheat -e foo
|
||||
|
||||
To list all available cheatsheets:
|
||||
cheat -l
|
||||
|
||||
To search for "ssh" among all cheatsheets:
|
||||
cheat -s ssh
|
||||
"""
|
||||
|
||||
# require the dependencies
|
||||
from __future__ import print_function
|
||||
from cheat.colorize import Colorize
|
||||
from cheat.configuration import Configuration
|
||||
from cheat.sheet import Sheet
|
||||
from cheat.sheets import Sheets
|
||||
from cheat.utils import Utils
|
||||
from docopt import docopt
|
||||
import os
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
# parse the command-line options
|
||||
options = docopt(__doc__, version='cheat 2.5.1')
|
||||
|
||||
# initialize and validate configs
|
||||
config = Configuration()
|
||||
config.validate()
|
||||
|
||||
# create the CHEAT_USER_DIR if it does not exist
|
||||
if not os.path.isdir(config.cheat_user_dir):
|
||||
try:
|
||||
os.mkdir(config.cheat_user_dir)
|
||||
|
||||
except OSError:
|
||||
Utils.die("%s %s %s" % (
|
||||
'Could not create CHEAT_USER_DIR (',
|
||||
config.cheat_user_dir,
|
||||
')')
|
||||
)
|
||||
|
||||
# assert that the CHEAT_USER_DIR is readable and writable
|
||||
if not os.access(config.cheat_user_dir, os.R_OK):
|
||||
Utils.die("%s %s %s" % (
|
||||
'The CHEAT_USER_DIR (',
|
||||
config.cheat_user_dir,
|
||||
') is not readable')
|
||||
)
|
||||
if not os.access(config.cheat_user_dir, os.W_OK):
|
||||
Utils.die("%s %s %s" % (
|
||||
'The CHEAT_USER_DIR (',
|
||||
config.cheat_user_dir,
|
||||
') is not writeable')
|
||||
)
|
||||
|
||||
# bootsrap
|
||||
sheets = Sheets(config)
|
||||
sheet = Sheet(config, sheets)
|
||||
colorize = Colorize(config)
|
||||
|
||||
# list directories
|
||||
if options['--directories']:
|
||||
print("\n".join(sheets.directories()))
|
||||
|
||||
# list cheatsheets
|
||||
elif options['--list']:
|
||||
print(sheets.list(), end="")
|
||||
|
||||
# create/edit cheatsheet
|
||||
elif options['--edit']:
|
||||
sheet.edit(options['<cheatsheet>'])
|
||||
|
||||
# search among the cheatsheets
|
||||
elif options['--search']:
|
||||
print(colorize.syntax(sheets.search(options['<keyword>'])), end="")
|
||||
|
||||
# print the cheatsheet
|
||||
else:
|
||||
print(colorize.syntax(sheet.read(options['<cheatsheet>'])), end="")
|
@ -1,8 +0,0 @@
|
||||
@echo OFF
|
||||
|
||||
if not defined CHEAT_EDITOR if not defined EDITOR if not defined VISUAL (
|
||||
set CHEAT_EDITOR=write
|
||||
)
|
||||
|
||||
REM %~dp0 is black magic for getting directory of script
|
||||
python %~dp0cheat %*
|
11
bin/deps.sh
Executable file
11
bin/deps.sh
Executable file
@ -0,0 +1,11 @@
|
||||
#!/bin/bash
|
||||
|
||||
# This script installs all Go dependencies required for
|
||||
# building `cheat` locally.
|
||||
|
||||
go get -u github.com/alecthomas/chroma
|
||||
go get -u github.com/davecgh/go-spew/spew
|
||||
go get -u github.com/docopt/docopt-go
|
||||
go get -u github.com/mgutz/ansi
|
||||
go get -u github.com/mitchellh/go-homedir
|
||||
go get -u github.com/tj/front
|
93
build/embed.go
Normal file
93
build/embed.go
Normal file
@ -0,0 +1,93 @@
|
||||
// +build ignore
|
||||
|
||||
// This script embeds `docopt.txt and `conf.yml` into the binary during at
|
||||
// build time.
|
||||
|
||||
package main
|
||||
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
// get the cwd
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// get the project root
|
||||
root, err := filepath.Abs(cwd + "../../../")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// specify template file information
|
||||
type file struct {
|
||||
In string
|
||||
Out string
|
||||
Method string
|
||||
}
|
||||
|
||||
// enumerate the template files to process
|
||||
files := []file{
|
||||
file{
|
||||
In: "cmd/cheat/docopt.txt",
|
||||
Out: "cmd/cheat/str_usage.go",
|
||||
Method: "usage"},
|
||||
file{
|
||||
In: "configs/conf.yml",
|
||||
Out: "cmd/cheat/str_config.go",
|
||||
Method: "configs"},
|
||||
}
|
||||
|
||||
// iterate over each static file
|
||||
for _, file := range files {
|
||||
|
||||
// delete the outfile
|
||||
os.Remove(path.Join(root, file.Out))
|
||||
|
||||
// read the static template
|
||||
bytes, err := ioutil.ReadFile(path.Join(root, file.In))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// render the template
|
||||
data := template(file.Method, string(bytes))
|
||||
|
||||
// write the file to the specified outpath
|
||||
spath := path.Join(root, file.Out)
|
||||
err = ioutil.WriteFile(spath, []byte(data), 0644)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// template packages the
|
||||
func template(method string, body string) string {
|
||||
|
||||
// specify the template string
|
||||
t := `package main
|
||||
|
||||
// Code generated .* DO NOT EDIT.
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
func %s() string {
|
||||
return strings.TrimSpace(%s)
|
||||
}
|
||||
`
|
||||
|
||||
return fmt.Sprintf(t, method, "`"+body+"`")
|
||||
}
|
618
cheat/appdirs.py
618
cheat/appdirs.py
@ -1,618 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright (c) 2005-2010 ActiveState Software Inc.
|
||||
# Copyright (c) 2013 Eddy Petrișor
|
||||
|
||||
"""Utilities for determining application-specific dirs.
|
||||
|
||||
See <https://github.com/ActiveState/appdirs> for details and usage.
|
||||
"""
|
||||
# Dev Notes:
|
||||
# - MSDN on where to store app data files:
|
||||
# http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120
|
||||
# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html
|
||||
# - XDG spec for Un*x: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
||||
|
||||
__version__ = "1.4.4"
|
||||
__version_info__ = tuple(int(segment) for segment in __version__.split("."))
|
||||
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
if PY3:
|
||||
unicode = str
|
||||
|
||||
if sys.platform.startswith('java'):
|
||||
import platform
|
||||
os_name = platform.java_ver()[3][0]
|
||||
if os_name.startswith('Windows'): # "Windows XP", "Windows 7", etc.
|
||||
system = 'win32'
|
||||
elif os_name.startswith('Mac'): # "Mac OS X", etc.
|
||||
system = 'darwin'
|
||||
else: # "Linux", "SunOS", "FreeBSD", etc.
|
||||
# Setting this to "linux2" is not ideal, but only Windows or Mac
|
||||
# are actually checked for and the rest of the module expects
|
||||
# *sys.platform* style strings.
|
||||
system = 'linux2'
|
||||
else:
|
||||
system = sys.platform
|
||||
|
||||
|
||||
|
||||
def user_data_dir(appname=None, appauthor=None, version=None, roaming=False):
|
||||
r"""Return full path to the user-specific data dir for this application.
|
||||
|
||||
"appname" is the name of application.
|
||||
If None, just the system directory is returned.
|
||||
"appauthor" (only used on Windows) is the name of the
|
||||
appauthor or distributing body for this application. Typically
|
||||
it is the owning company name. This falls back to appname. You may
|
||||
pass False to disable it.
|
||||
"version" is an optional version path element to append to the
|
||||
path. You might want to use this if you want multiple versions
|
||||
of your app to be able to run independently. If used, this
|
||||
would typically be "<major>.<minor>".
|
||||
Only applied when appname is present.
|
||||
"roaming" (boolean, default False) can be set True to use the Windows
|
||||
roaming appdata directory. That means that for users on a Windows
|
||||
network setup for roaming profiles, this user data will be
|
||||
sync'd on login. See
|
||||
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
|
||||
for a discussion of issues.
|
||||
|
||||
Typical user data directories are:
|
||||
Mac OS X: ~/Library/Application Support/<AppName>
|
||||
Unix: ~/.local/share/<AppName> # or in $XDG_DATA_HOME, if defined
|
||||
Win XP (not roaming): C:\Documents and Settings\<username>\Application Data\<AppAuthor>\<AppName>
|
||||
Win XP (roaming): C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>
|
||||
Win 7 (not roaming): C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>
|
||||
Win 7 (roaming): C:\Users\<username>\AppData\Roaming\<AppAuthor>\<AppName>
|
||||
|
||||
For Unix, we follow the XDG spec and support $XDG_DATA_HOME.
|
||||
That means, by default "~/.local/share/<AppName>".
|
||||
"""
|
||||
if system == "win32":
|
||||
if appauthor is None:
|
||||
appauthor = appname
|
||||
const = roaming and "CSIDL_APPDATA" or "CSIDL_LOCAL_APPDATA"
|
||||
path = os.path.normpath(_get_win_folder(const))
|
||||
if appname:
|
||||
if appauthor is not False:
|
||||
path = os.path.join(path, appauthor, appname)
|
||||
else:
|
||||
path = os.path.join(path, appname)
|
||||
elif system == 'darwin':
|
||||
path = os.path.expanduser('~/Library/Application Support/')
|
||||
if appname:
|
||||
path = os.path.join(path, appname)
|
||||
else:
|
||||
path = os.getenv('XDG_DATA_HOME', os.path.expanduser("~/.local/share"))
|
||||
if appname:
|
||||
path = os.path.join(path, appname)
|
||||
if appname and version:
|
||||
path = os.path.join(path, version)
|
||||
return path
|
||||
|
||||
|
||||
def site_data_dir(appname=None, appauthor=None, version=None, multipath=False):
|
||||
r"""Return full path to the user-shared data dir for this application.
|
||||
|
||||
"appname" is the name of application.
|
||||
If None, just the system directory is returned.
|
||||
"appauthor" (only used on Windows) is the name of the
|
||||
appauthor or distributing body for this application. Typically
|
||||
it is the owning company name. This falls back to appname. You may
|
||||
pass False to disable it.
|
||||
"version" is an optional version path element to append to the
|
||||
path. You might want to use this if you want multiple versions
|
||||
of your app to be able to run independently. If used, this
|
||||
would typically be "<major>.<minor>".
|
||||
Only applied when appname is present.
|
||||
"multipath" is an optional parameter only applicable to *nix
|
||||
which indicates that the entire list of data dirs should be
|
||||
returned. By default, the first item from XDG_DATA_DIRS is
|
||||
returned, or '/usr/local/share/<AppName>',
|
||||
if XDG_DATA_DIRS is not set
|
||||
|
||||
Typical site data directories are:
|
||||
Mac OS X: /Library/Application Support/<AppName>
|
||||
Unix: /usr/local/share/<AppName> or /usr/share/<AppName>
|
||||
Win XP: C:\Documents and Settings\All Users\Application Data\<AppAuthor>\<AppName>
|
||||
Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
|
||||
Win 7: C:\ProgramData\<AppAuthor>\<AppName> # Hidden, but writeable on Win 7.
|
||||
|
||||
For Unix, this is using the $XDG_DATA_DIRS[0] default.
|
||||
|
||||
WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
|
||||
"""
|
||||
if system == "win32":
|
||||
if appauthor is None:
|
||||
appauthor = appname
|
||||
path = os.path.normpath(_get_win_folder("CSIDL_COMMON_APPDATA"))
|
||||
if appname:
|
||||
if appauthor is not False:
|
||||
path = os.path.join(path, appauthor, appname)
|
||||
else:
|
||||
path = os.path.join(path, appname)
|
||||
elif system == 'darwin':
|
||||
path = os.path.expanduser('/Library/Application Support')
|
||||
if appname:
|
||||
path = os.path.join(path, appname)
|
||||
else:
|
||||
# XDG default for $XDG_DATA_DIRS
|
||||
# only first, if multipath is False
|
||||
path = os.getenv('XDG_DATA_DIRS',
|
||||
os.pathsep.join(['/usr/local/share', '/usr/share']))
|
||||
pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
|
||||
if appname:
|
||||
if version:
|
||||
appname = os.path.join(appname, version)
|
||||
pathlist = [os.sep.join([x, appname]) for x in pathlist]
|
||||
|
||||
if multipath:
|
||||
path = os.pathsep.join(pathlist)
|
||||
else:
|
||||
path = pathlist[0]
|
||||
return path
|
||||
|
||||
if appname and version:
|
||||
path = os.path.join(path, version)
|
||||
return path
|
||||
|
||||
|
||||
def user_config_dir(appname=None, appauthor=None, version=None, roaming=False):
|
||||
r"""Return full path to the user-specific config dir for this application.
|
||||
|
||||
"appname" is the name of application.
|
||||
If None, just the system directory is returned.
|
||||
"appauthor" (only used on Windows) is the name of the
|
||||
appauthor or distributing body for this application. Typically
|
||||
it is the owning company name. This falls back to appname. You may
|
||||
pass False to disable it.
|
||||
"version" is an optional version path element to append to the
|
||||
path. You might want to use this if you want multiple versions
|
||||
of your app to be able to run independently. If used, this
|
||||
would typically be "<major>.<minor>".
|
||||
Only applied when appname is present.
|
||||
"roaming" (boolean, default False) can be set True to use the Windows
|
||||
roaming appdata directory. That means that for users on a Windows
|
||||
network setup for roaming profiles, this user data will be
|
||||
sync'd on login. See
|
||||
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
|
||||
for a discussion of issues.
|
||||
|
||||
Typical user config directories are:
|
||||
Mac OS X: ~/Library/Preferences/<AppName>
|
||||
Unix: ~/.config/<AppName> # or in $XDG_CONFIG_HOME, if defined
|
||||
Win *: same as user_data_dir
|
||||
|
||||
For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME.
|
||||
That means, by default "~/.config/<AppName>".
|
||||
"""
|
||||
if system == "win32":
|
||||
path = user_data_dir(appname, appauthor, None, roaming)
|
||||
elif system == 'darwin':
|
||||
path = os.path.expanduser('~/Library/Preferences/')
|
||||
if appname:
|
||||
path = os.path.join(path, appname)
|
||||
else:
|
||||
path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser("~/.config"))
|
||||
if appname:
|
||||
path = os.path.join(path, appname)
|
||||
if appname and version:
|
||||
path = os.path.join(path, version)
|
||||
return path
|
||||
|
||||
|
||||
def site_config_dir(appname=None, appauthor=None, version=None, multipath=False):
|
||||
r"""Return full path to the user-shared data dir for this application.
|
||||
|
||||
"appname" is the name of application.
|
||||
If None, just the system directory is returned.
|
||||
"appauthor" (only used on Windows) is the name of the
|
||||
appauthor or distributing body for this application. Typically
|
||||
it is the owning company name. This falls back to appname. You may
|
||||
pass False to disable it.
|
||||
"version" is an optional version path element to append to the
|
||||
path. You might want to use this if you want multiple versions
|
||||
of your app to be able to run independently. If used, this
|
||||
would typically be "<major>.<minor>".
|
||||
Only applied when appname is present.
|
||||
"multipath" is an optional parameter only applicable to *nix
|
||||
which indicates that the entire list of config dirs should be
|
||||
returned. By default, the first item from XDG_CONFIG_DIRS is
|
||||
returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set
|
||||
|
||||
Typical site config directories are:
|
||||
Mac OS X: same as site_data_dir
|
||||
Unix: /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in
|
||||
$XDG_CONFIG_DIRS
|
||||
Win *: same as site_data_dir
|
||||
Vista: (Fail! "C:\ProgramData" is a hidden *system* directory on Vista.)
|
||||
|
||||
For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False
|
||||
|
||||
WARNING: Do not use this on Windows. See the Vista-Fail note above for why.
|
||||
"""
|
||||
if system == 'win32':
|
||||
path = site_data_dir(appname, appauthor)
|
||||
if appname and version:
|
||||
path = os.path.join(path, version)
|
||||
elif system == 'darwin':
|
||||
path = os.path.expanduser('/Library/Preferences')
|
||||
if appname:
|
||||
path = os.path.join(path, appname)
|
||||
elif system == 'linux':
|
||||
path = os.path.join('/etc/', appname)
|
||||
else:
|
||||
# XDG default for $XDG_CONFIG_DIRS
|
||||
# only first, if multipath is False
|
||||
path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg')
|
||||
pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]
|
||||
if appname:
|
||||
if version:
|
||||
appname = os.path.join(appname, version)
|
||||
pathlist = [os.sep.join([x, appname]) for x in pathlist]
|
||||
|
||||
if multipath:
|
||||
path = os.pathsep.join(pathlist)
|
||||
else:
|
||||
path = pathlist[0]
|
||||
return path
|
||||
|
||||
|
||||
def user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):
|
||||
r"""Return full path to the user-specific cache dir for this application.
|
||||
|
||||
"appname" is the name of application.
|
||||
If None, just the system directory is returned.
|
||||
"appauthor" (only used on Windows) is the name of the
|
||||
appauthor or distributing body for this application. Typically
|
||||
it is the owning company name. This falls back to appname. You may
|
||||
pass False to disable it.
|
||||
"version" is an optional version path element to append to the
|
||||
path. You might want to use this if you want multiple versions
|
||||
of your app to be able to run independently. If used, this
|
||||
would typically be "<major>.<minor>".
|
||||
Only applied when appname is present.
|
||||
"opinion" (boolean) can be False to disable the appending of
|
||||
"Cache" to the base app data dir for Windows. See
|
||||
discussion below.
|
||||
|
||||
Typical user cache directories are:
|
||||
Mac OS X: ~/Library/Caches/<AppName>
|
||||
Unix: ~/.cache/<AppName> (XDG default)
|
||||
Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Cache
|
||||
Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Cache
|
||||
|
||||
On Windows the only suggestion in the MSDN docs is that local settings go in
|
||||
the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming
|
||||
app data dir (the default returned by `user_data_dir` above). Apps typically
|
||||
put cache data somewhere *under* the given dir here. Some examples:
|
||||
...\Mozilla\Firefox\Profiles\<ProfileName>\Cache
|
||||
...\Acme\SuperApp\Cache\1.0
|
||||
OPINION: This function appends "Cache" to the `CSIDL_LOCAL_APPDATA` value.
|
||||
This can be disabled with the `opinion=False` option.
|
||||
"""
|
||||
if system == "win32":
|
||||
if appauthor is None:
|
||||
appauthor = appname
|
||||
path = os.path.normpath(_get_win_folder("CSIDL_LOCAL_APPDATA"))
|
||||
if appname:
|
||||
if appauthor is not False:
|
||||
path = os.path.join(path, appauthor, appname)
|
||||
else:
|
||||
path = os.path.join(path, appname)
|
||||
if opinion:
|
||||
path = os.path.join(path, "Cache")
|
||||
elif system == 'darwin':
|
||||
path = os.path.expanduser('~/Library/Caches')
|
||||
if appname:
|
||||
path = os.path.join(path, appname)
|
||||
else:
|
||||
path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache'))
|
||||
if appname:
|
||||
path = os.path.join(path, appname)
|
||||
if appname and version:
|
||||
path = os.path.join(path, version)
|
||||
return path
|
||||
|
||||
|
||||
def user_state_dir(appname=None, appauthor=None, version=None, roaming=False):
|
||||
r"""Return full path to the user-specific state dir for this application.
|
||||
|
||||
"appname" is the name of application.
|
||||
If None, just the system directory is returned.
|
||||
"appauthor" (only used on Windows) is the name of the
|
||||
appauthor or distributing body for this application. Typically
|
||||
it is the owning company name. This falls back to appname. You may
|
||||
pass False to disable it.
|
||||
"version" is an optional version path element to append to the
|
||||
path. You might want to use this if you want multiple versions
|
||||
of your app to be able to run independently. If used, this
|
||||
would typically be "<major>.<minor>".
|
||||
Only applied when appname is present.
|
||||
"roaming" (boolean, default False) can be set True to use the Windows
|
||||
roaming appdata directory. That means that for users on a Windows
|
||||
network setup for roaming profiles, this user data will be
|
||||
sync'd on login. See
|
||||
<http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>
|
||||
for a discussion of issues.
|
||||
|
||||
Typical user state directories are:
|
||||
Mac OS X: same as user_data_dir
|
||||
Unix: ~/.local/state/<AppName> # or in $XDG_STATE_HOME, if defined
|
||||
Win *: same as user_data_dir
|
||||
|
||||
For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state>
|
||||
to extend the XDG spec and support $XDG_STATE_HOME.
|
||||
|
||||
That means, by default "~/.local/state/<AppName>".
|
||||
"""
|
||||
if system in ["win32", "darwin"]:
|
||||
path = user_data_dir(appname, appauthor, None, roaming)
|
||||
else:
|
||||
path = os.getenv('XDG_STATE_HOME', os.path.expanduser("~/.local/state"))
|
||||
if appname:
|
||||
path = os.path.join(path, appname)
|
||||
if appname and version:
|
||||
path = os.path.join(path, version)
|
||||
return path
|
||||
|
||||
|
||||
def user_log_dir(appname=None, appauthor=None, version=None, opinion=True):
|
||||
r"""Return full path to the user-specific log dir for this application.
|
||||
|
||||
"appname" is the name of application.
|
||||
If None, just the system directory is returned.
|
||||
"appauthor" (only used on Windows) is the name of the
|
||||
appauthor or distributing body for this application. Typically
|
||||
it is the owning company name. This falls back to appname. You may
|
||||
pass False to disable it.
|
||||
"version" is an optional version path element to append to the
|
||||
path. You might want to use this if you want multiple versions
|
||||
of your app to be able to run independently. If used, this
|
||||
would typically be "<major>.<minor>".
|
||||
Only applied when appname is present.
|
||||
"opinion" (boolean) can be False to disable the appending of
|
||||
"Logs" to the base app data dir for Windows, and "log" to the
|
||||
base cache dir for Unix. See discussion below.
|
||||
|
||||
Typical user log directories are:
|
||||
Mac OS X: ~/Library/Logs/<AppName>
|
||||
Unix: ~/.cache/<AppName>/log # or under $XDG_CACHE_HOME if defined
|
||||
Win XP: C:\Documents and Settings\<username>\Local Settings\Application Data\<AppAuthor>\<AppName>\Logs
|
||||
Vista: C:\Users\<username>\AppData\Local\<AppAuthor>\<AppName>\Logs
|
||||
|
||||
On Windows the only suggestion in the MSDN docs is that local settings
|
||||
go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in
|
||||
examples of what some windows apps use for a logs dir.)
|
||||
|
||||
OPINION: This function appends "Logs" to the `CSIDL_LOCAL_APPDATA`
|
||||
value for Windows and appends "log" to the user cache dir for Unix.
|
||||
This can be disabled with the `opinion=False` option.
|
||||
"""
|
||||
if system == "darwin":
|
||||
path = os.path.join(
|
||||
os.path.expanduser('~/Library/Logs'),
|
||||
appname)
|
||||
elif system == "win32":
|
||||
path = user_data_dir(appname, appauthor, version)
|
||||
version = False
|
||||
if opinion:
|
||||
path = os.path.join(path, "Logs")
|
||||
else:
|
||||
path = user_cache_dir(appname, appauthor, version)
|
||||
version = False
|
||||
if opinion:
|
||||
path = os.path.join(path, "log")
|
||||
if appname and version:
|
||||
path = os.path.join(path, version)
|
||||
return path
|
||||
|
||||
|
||||
class AppDirs(object):
|
||||
"""Convenience wrapper for getting application dirs."""
|
||||
def __init__(self, appname=None, appauthor=None, version=None,
|
||||
roaming=False, multipath=False):
|
||||
self.appname = appname
|
||||
self.appauthor = appauthor
|
||||
self.version = version
|
||||
self.roaming = roaming
|
||||
self.multipath = multipath
|
||||
|
||||
@property
|
||||
def user_data_dir(self):
|
||||
return user_data_dir(self.appname, self.appauthor,
|
||||
version=self.version, roaming=self.roaming)
|
||||
|
||||
@property
|
||||
def site_data_dir(self):
|
||||
return site_data_dir(self.appname, self.appauthor,
|
||||
version=self.version, multipath=self.multipath)
|
||||
|
||||
@property
|
||||
def user_config_dir(self):
|
||||
return user_config_dir(self.appname, self.appauthor,
|
||||
version=self.version, roaming=self.roaming)
|
||||
|
||||
@property
|
||||
def site_config_dir(self):
|
||||
return site_config_dir(self.appname, self.appauthor,
|
||||
version=self.version, multipath=self.multipath)
|
||||
|
||||
@property
|
||||
def user_cache_dir(self):
|
||||
return user_cache_dir(self.appname, self.appauthor,
|
||||
version=self.version)
|
||||
|
||||
@property
|
||||
def user_state_dir(self):
|
||||
return user_state_dir(self.appname, self.appauthor,
|
||||
version=self.version)
|
||||
|
||||
@property
|
||||
def user_log_dir(self):
|
||||
return user_log_dir(self.appname, self.appauthor,
|
||||
version=self.version)
|
||||
|
||||
|
||||
#---- internal support stuff
|
||||
|
||||
def _get_win_folder_from_registry(csidl_name):
|
||||
"""This is a fallback technique at best. I'm not sure if using the
|
||||
registry for this guarantees us the correct answer for all CSIDL_*
|
||||
names.
|
||||
"""
|
||||
if PY3:
|
||||
import winreg as _winreg
|
||||
else:
|
||||
import _winreg
|
||||
|
||||
shell_folder_name = {
|
||||
"CSIDL_APPDATA": "AppData",
|
||||
"CSIDL_COMMON_APPDATA": "Common AppData",
|
||||
"CSIDL_LOCAL_APPDATA": "Local AppData",
|
||||
}[csidl_name]
|
||||
|
||||
key = _winreg.OpenKey(
|
||||
_winreg.HKEY_CURRENT_USER,
|
||||
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
|
||||
)
|
||||
dir, type = _winreg.QueryValueEx(key, shell_folder_name)
|
||||
return dir
|
||||
|
||||
|
||||
def _get_win_folder_with_pywin32(csidl_name):
|
||||
from win32com.shell import shellcon, shell
|
||||
dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0)
|
||||
# Try to make this a unicode path because SHGetFolderPath does
|
||||
# not return unicode strings when there is unicode data in the
|
||||
# path.
|
||||
try:
|
||||
dir = unicode(dir)
|
||||
|
||||
# Downgrade to short path name if have highbit chars. See
|
||||
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
|
||||
has_high_char = False
|
||||
for c in dir:
|
||||
if ord(c) > 255:
|
||||
has_high_char = True
|
||||
break
|
||||
if has_high_char:
|
||||
try:
|
||||
import win32api
|
||||
dir = win32api.GetShortPathName(dir)
|
||||
except ImportError:
|
||||
pass
|
||||
except UnicodeError:
|
||||
pass
|
||||
return dir
|
||||
|
||||
|
||||
def _get_win_folder_with_ctypes(csidl_name):
|
||||
import ctypes
|
||||
|
||||
csidl_const = {
|
||||
"CSIDL_APPDATA": 26,
|
||||
"CSIDL_COMMON_APPDATA": 35,
|
||||
"CSIDL_LOCAL_APPDATA": 28,
|
||||
}[csidl_name]
|
||||
|
||||
buf = ctypes.create_unicode_buffer(1024)
|
||||
ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
|
||||
|
||||
# Downgrade to short path name if have highbit chars. See
|
||||
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
|
||||
has_high_char = False
|
||||
for c in buf:
|
||||
if ord(c) > 255:
|
||||
has_high_char = True
|
||||
break
|
||||
if has_high_char:
|
||||
buf2 = ctypes.create_unicode_buffer(1024)
|
||||
if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
|
||||
buf = buf2
|
||||
|
||||
return buf.value
|
||||
|
||||
def _get_win_folder_with_jna(csidl_name):
|
||||
import array
|
||||
from com.sun import jna
|
||||
from com.sun.jna.platform import win32
|
||||
|
||||
buf_size = win32.WinDef.MAX_PATH * 2
|
||||
buf = array.zeros('c', buf_size)
|
||||
shell = win32.Shell32.INSTANCE
|
||||
shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)
|
||||
dir = jna.Native.toString(buf.tostring()).rstrip("\0")
|
||||
|
||||
# Downgrade to short path name if have highbit chars. See
|
||||
# <http://bugs.activestate.com/show_bug.cgi?id=85099>.
|
||||
has_high_char = False
|
||||
for c in dir:
|
||||
if ord(c) > 255:
|
||||
has_high_char = True
|
||||
break
|
||||
if has_high_char:
|
||||
buf = array.zeros('c', buf_size)
|
||||
kernel = win32.Kernel32.INSTANCE
|
||||
if kernel.GetShortPathName(dir, buf, buf_size):
|
||||
dir = jna.Native.toString(buf.tostring()).rstrip("\0")
|
||||
|
||||
return dir
|
||||
|
||||
if system == "win32":
|
||||
try:
|
||||
import win32com.shell
|
||||
_get_win_folder = _get_win_folder_with_pywin32
|
||||
except ImportError:
|
||||
try:
|
||||
from ctypes import windll
|
||||
_get_win_folder = _get_win_folder_with_ctypes
|
||||
except ImportError:
|
||||
try:
|
||||
import com.sun.jna
|
||||
_get_win_folder = _get_win_folder_with_jna
|
||||
except ImportError:
|
||||
_get_win_folder = _get_win_folder_from_registry
|
||||
|
||||
|
||||
#---- self test code
|
||||
|
||||
if __name__ == "__main__":
|
||||
appname = "MyApp"
|
||||
appauthor = "MyCompany"
|
||||
|
||||
props = ("user_data_dir",
|
||||
"user_config_dir",
|
||||
"user_cache_dir",
|
||||
"user_state_dir",
|
||||
"user_log_dir",
|
||||
"site_data_dir",
|
||||
"site_config_dir")
|
||||
|
||||
print("-- app dirs %s --" % __version__)
|
||||
|
||||
print("-- app dirs (with optional 'version')")
|
||||
dirs = AppDirs(appname, appauthor, version="1.0")
|
||||
for prop in props:
|
||||
print("%s: %s" % (prop, getattr(dirs, prop)))
|
||||
|
||||
print("\n-- app dirs (without optional 'version')")
|
||||
dirs = AppDirs(appname, appauthor)
|
||||
for prop in props:
|
||||
print("%s: %s" % (prop, getattr(dirs, prop)))
|
||||
|
||||
print("\n-- app dirs (without optional 'appauthor')")
|
||||
dirs = AppDirs(appname)
|
||||
for prop in props:
|
||||
print("%s: %s" % (prop, getattr(dirs, prop)))
|
||||
|
||||
print("\n-- app dirs (with disabled 'appauthor')")
|
||||
dirs = AppDirs(appname, appauthor=False)
|
||||
for prop in props:
|
||||
print("%s: %s" % (prop, getattr(dirs, prop)))
|
@ -1,9 +0,0 @@
|
||||
function _cheat_autocomplete {
|
||||
sheets=$(cheat -l | cut -d' ' -f1)
|
||||
COMPREPLY=()
|
||||
if [ $COMP_CWORD = 1 ]; then
|
||||
COMPREPLY=(`compgen -W "$sheets" -- $2`)
|
||||
fi
|
||||
}
|
||||
|
||||
complete -F _cheat_autocomplete cheat
|
@ -1,12 +0,0 @@
|
||||
#completion for cheat
|
||||
complete -c cheat -s h -l help -f -x --description "Display help and exit"
|
||||
complete -c cheat -l edit -f -x --description "Edit <cheatsheet>"
|
||||
complete -c cheat -s e -f -x --description "Edit <cheatsheet>"
|
||||
complete -c cheat -s l -l list -f -x --description "List all available cheatsheets"
|
||||
complete -c cheat -s d -l cheat-directories -f -x --description "List all current cheat dirs"
|
||||
complete -c cheat --authoritative -f
|
||||
for cheatsheet in (cheat -l | cut -d' ' -f1)
|
||||
complete -c cheat -a "$cheatsheet"
|
||||
complete -c cheat -o e -a "$cheatsheet"
|
||||
complete -c cheat -o '-edit' -a "$cheatsheet"
|
||||
end
|
@ -1,5 +0,0 @@
|
||||
#compdef cheat
|
||||
|
||||
declare -a cheats
|
||||
cheats=$(cheat -l | cut -d' ' -f1)
|
||||
_arguments "1:cheats:(${cheats})" && return 0
|
@ -1,29 +0,0 @@
|
||||
7z
|
||||
A file archiver with highest compression ratio
|
||||
|
||||
Args:
|
||||
a add
|
||||
d delete
|
||||
e extract
|
||||
l list
|
||||
t test
|
||||
u update
|
||||
x extract with full paths
|
||||
|
||||
Example:
|
||||
7z a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on archive.7z dir1
|
||||
|
||||
-t7z 7z archive
|
||||
-m0=lzma lzma method
|
||||
-mx=9 level of compression = 9 (ultra)
|
||||
-mfb=64 number of fast bytes for lzma = 64
|
||||
-md=32m dictionary size = 32 Mb
|
||||
-ms=on solid archive = on
|
||||
|
||||
7z exit codes:
|
||||
0 normal (no errors or warnings)
|
||||
1 warning (non-fatal errors)
|
||||
2 fatal error
|
||||
7 bad cli arguments
|
||||
8 not enough memory for operation
|
||||
255 process was interrupted
|
@ -1,5 +0,0 @@
|
||||
# send 100 requests with a concurency of 50 requests to an URL
|
||||
ab -n 100 -c 50 http://www.example.com/
|
||||
|
||||
# send requests during 30 seconds with a concurency of 50 requests to an URL
|
||||
ab -t 30 -c 50 URL http://www.example.com/
|
@ -1,5 +0,0 @@
|
||||
# Show a list of your current shell aliases
|
||||
alias
|
||||
|
||||
# Map `ll` to `ls -l` (Can be used per session or put inside a shell config file)
|
||||
alias ll='ls -l'
|
@ -1,72 +0,0 @@
|
||||
# Reset
|
||||
Color_Off='\e[0m' # Text Reset
|
||||
|
||||
# Regular Colors
|
||||
Black='\e[0;30m' # Black
|
||||
Red='\e[0;31m' # Red
|
||||
Green='\e[0;32m' # Green
|
||||
Yellow='\e[0;33m' # Yellow
|
||||
Blue='\e[0;34m' # Blue
|
||||
Purple='\e[0;35m' # Purple
|
||||
Cyan='\e[0;36m' # Cyan
|
||||
White='\e[0;37m' # White
|
||||
|
||||
# Bold
|
||||
BBlack='\e[1;30m' # Black
|
||||
BRed='\e[1;31m' # Red
|
||||
BGreen='\e[1;32m' # Green
|
||||
BYellow='\e[1;33m' # Yellow
|
||||
BBlue='\e[1;34m' # Blue
|
||||
BPurple='\e[1;35m' # Purple
|
||||
BCyan='\e[1;36m' # Cyan
|
||||
BWhite='\e[1;37m' # White
|
||||
|
||||
# Underline
|
||||
UBlack='\e[4;30m' # Black
|
||||
URed='\e[4;31m' # Red
|
||||
UGreen='\e[4;32m' # Green
|
||||
UYellow='\e[4;33m' # Yellow
|
||||
UBlue='\e[4;34m' # Blue
|
||||
UPurple='\e[4;35m' # Purple
|
||||
UCyan='\e[4;36m' # Cyan
|
||||
UWhite='\e[4;37m' # White
|
||||
|
||||
# Background
|
||||
On_Black='\e[40m' # Black
|
||||
On_Red='\e[41m' # Red
|
||||
On_Green='\e[42m' # Green
|
||||
On_Yellow='\e[43m' # Yellow
|
||||
On_Blue='\e[44m' # Blue
|
||||
On_Purple='\e[45m' # Purple
|
||||
On_Cyan='\e[46m' # Cyan
|
||||
On_White='\e[47m' # White
|
||||
|
||||
# High Intensity
|
||||
IBlack='\e[0;90m' # Black
|
||||
IRed='\e[0;91m' # Red
|
||||
IGreen='\e[0;92m' # Green
|
||||
IYellow='\e[0;93m' # Yellow
|
||||
IBlue='\e[0;94m' # Blue
|
||||
IPurple='\e[0;95m' # Purple
|
||||
ICyan='\e[0;96m' # Cyan
|
||||
IWhite='\e[0;97m' # White
|
||||
|
||||
# Bold High Intensity
|
||||
BIBlack='\e[1;90m' # Black
|
||||
BIRed='\e[1;91m' # Red
|
||||
BIGreen='\e[1;92m' # Green
|
||||
BIYellow='\e[1;93m' # Yellow
|
||||
BIBlue='\e[1;94m' # Blue
|
||||
BIPurple='\e[1;95m' # Purple
|
||||
BICyan='\e[1;96m' # Cyan
|
||||
BIWhite='\e[1;97m' # White
|
||||
|
||||
# High Intensity backgrounds
|
||||
On_IBlack='\e[0;100m' # Black
|
||||
On_IRed='\e[0;101m' # Red
|
||||
On_IGreen='\e[0;102m' # Green
|
||||
On_IYellow='\e[0;103m' # Yellow
|
||||
On_IBlue='\e[0;104m' # Blue
|
||||
On_IPurple='\e[0;105m' # Purple
|
||||
On_ICyan='\e[0;106m' # Cyan
|
||||
On_IWhite='\e[0;107m' # White
|
@ -1,14 +0,0 @@
|
||||
# Install a package
|
||||
apk add $package
|
||||
|
||||
# Remove a package
|
||||
apk del $package
|
||||
|
||||
# Update repos
|
||||
apk update
|
||||
|
||||
# Upgrade all packages
|
||||
apk upgrade
|
||||
|
||||
# Find a package
|
||||
apk search $package
|
@ -1,18 +0,0 @@
|
||||
# Desc: Apparmor will protect the system by confining programs to a limited set of resources.
|
||||
|
||||
# To activate a profile:
|
||||
sudo aa-enforce usr.bin.firefox
|
||||
# OR
|
||||
export _PROFILE_='usr.bin.firefox' sudo $(rm /etc/apparmor.d/disable/$_PROFILE_ ; cat /etc/apparmor.d/$_PROFILE_ | apparmor_parser -a )
|
||||
|
||||
# TO disable a profile:
|
||||
sudo aa-disable usr.bin.firefox
|
||||
# OR
|
||||
export _PROFILE_='usr.bin.firefox' sudo $(ln -s /etc/apparmor.d/$_PROFILE_ /etc/apparmor.d/disable/ && apparmor_parser -R /etc/apparmor.d/$_PROFILE_)
|
||||
|
||||
# To list profiles loaded:
|
||||
sudo aa-status
|
||||
# OR
|
||||
sudo apparmor_status
|
||||
|
||||
# List of profiles aviables: /etc/apparmor.d/
|
@ -1,23 +0,0 @@
|
||||
# To search a package:
|
||||
apt search package
|
||||
|
||||
# To show package informations:
|
||||
apt show package
|
||||
|
||||
# To fetch package list:
|
||||
apt update
|
||||
|
||||
# To download and install updates without installing new package:
|
||||
apt upgrade
|
||||
|
||||
# To download and install the updates AND install new necessary packages:
|
||||
apt dist-upgrade
|
||||
|
||||
# Full command:
|
||||
apt update && apt dist-upgrade
|
||||
|
||||
# To install a new package(s):
|
||||
apt install package(s)
|
||||
|
||||
# To uninstall package(s)
|
||||
apt remove package(s)
|
@ -1,12 +0,0 @@
|
||||
# To search for apt packages:
|
||||
apt-cache search "whatever"
|
||||
|
||||
# To display package records for the named package(s):
|
||||
apt-cache show pkg(s)
|
||||
|
||||
# To display reverse dependencies of a package
|
||||
apt-cache rdepends package_name
|
||||
|
||||
# To display package versions, reverse dependencies and forward dependencies
|
||||
# of a package
|
||||
apt-cache showpkg package_name
|
@ -1,28 +0,0 @@
|
||||
# Desc: Allows to update the operating system
|
||||
|
||||
# To fetch package list
|
||||
apt-get update
|
||||
|
||||
# To download and install updates without installing new package.
|
||||
apt-get upgrade
|
||||
|
||||
# To download and install the updates AND install new necessary packages
|
||||
apt-get dist-upgrade
|
||||
|
||||
# Full command:
|
||||
apt-get update && apt-get dist-upgrade
|
||||
|
||||
# To install a new package(s)
|
||||
apt-get install package(s)
|
||||
|
||||
# Download a package without installing it. (The package will be downloaded in your current working dir)
|
||||
apt-get download modsecurity-crs
|
||||
|
||||
# Change Cache dir and archive dir (where .deb are stored).
|
||||
apt-get -o Dir::Cache="/path/to/destination/dir/" -o Dir::Cache::archives="./" install ...
|
||||
|
||||
# Show apt-get installed packages.
|
||||
grep 'install ' /var/log/dpkg.log
|
||||
|
||||
# Silently keep old configuration during batch updates
|
||||
apt-get update -o DPkg::Options::='--force-confold' ...
|
@ -1,15 +0,0 @@
|
||||
# To search for packages:
|
||||
aptitude search "whatever"
|
||||
|
||||
# To display package records for the named package(s):
|
||||
aptitude show pkg(s)
|
||||
|
||||
# To install a package:
|
||||
aptitude install package
|
||||
|
||||
# To remove a package:
|
||||
aptitude remove package
|
||||
|
||||
# To remove unnecessary package:
|
||||
aptitude autoclean
|
||||
|
@ -1,12 +0,0 @@
|
||||
# Just download a file
|
||||
# The url can be a http(s), ftp, .torrent file or even a magnet link
|
||||
aria2c <url>
|
||||
|
||||
# To prevent downloading the .torrent file
|
||||
aria2c --follow-torrent=mem <url>
|
||||
|
||||
# Download 1 file at a time (-j)
|
||||
# continuing (-c) any partially downloaded ones
|
||||
# to the directory specified (-d)
|
||||
# reading urls from the file (-i)
|
||||
aria2c -j 1 -c -d ~/Downloads -i /path/to/file
|
@ -1,22 +0,0 @@
|
||||
# To show some text in ASCII Art:
|
||||
|
||||
figlet Cheat
|
||||
# ____ _ _
|
||||
# / ___| |__ ___ __ _| |_
|
||||
#| | | '_ \ / _ \/ _` | __|
|
||||
#| |___| | | | __/ (_| | |_
|
||||
# \____|_| |_|\___|\__,_|\__|
|
||||
#
|
||||
|
||||
|
||||
# To have some text with color and other options:
|
||||
# Show with a border
|
||||
toilet -F border Cheat
|
||||
# Basic show (filled)
|
||||
toilet Cheat
|
||||
# mmm # m
|
||||
# m" " # mm mmm mmm mm#mm
|
||||
# # #" # #" # " # #
|
||||
# # # # #"""" m"""# #
|
||||
# "mmm" # # "#mm" "mm"# "mm
|
||||
#
|
@ -1,17 +0,0 @@
|
||||
# To connect to a running Asterisk session:
|
||||
asterisk -rvvv
|
||||
|
||||
# To issue a command to Asterisk from the shell:
|
||||
asterisk -rx "<command>"
|
||||
|
||||
# To originate an echo call from a SIP trunk on an Asterisk server, to a specified number:
|
||||
asterisk -rx "channel originate SIP/<trunk>/<number> application echo"
|
||||
|
||||
# To print out the details of SIP accounts:
|
||||
asterisk -rx "sip show peers"
|
||||
|
||||
# To print out the passwords of SIP accounts:
|
||||
asterisk -rx "sip show users"
|
||||
|
||||
# To print out the current active channels:
|
||||
asterisk -rx "core show channels"
|
@ -1,17 +0,0 @@
|
||||
# To schedule a one time task
|
||||
at {time}
|
||||
{command 0}
|
||||
{command 1}
|
||||
Ctrl-d
|
||||
|
||||
# {time} can be either
|
||||
now | midnight | noon | teatime (4pm)
|
||||
HH:MM
|
||||
now + N {minutes | hours | days | weeks}
|
||||
MM/DD/YY
|
||||
|
||||
# To list pending jobs
|
||||
atq
|
||||
|
||||
# To remove a job (use id from atq)
|
||||
atrm {id}
|
@ -1,11 +0,0 @@
|
||||
# sum integers from a file or stdin, one integer per line:
|
||||
printf '1\n2\n3\n' | awk '{ sum += $1} END {print sum}'
|
||||
|
||||
# using specific character as separator to sum integers from a file or stdin
|
||||
printf '1:2:3' | awk -F ":" '{print $1+$2+$3}'
|
||||
|
||||
# print a multiplication table
|
||||
seq 9 | sed 'H;g' | awk -v RS='' '{for(i=1;i<=NF;i++)printf("%dx%d=%d%s", i, NR, i*NR, i==NR?"\n":"\t")}'
|
||||
|
||||
# Specify output separator character
|
||||
printf '1 2 3' | awk 'BEGIN {OFS=":"}; {print $1,$2,$3}'
|
@ -1,27 +0,0 @@
|
||||
# To implement a for loop:
|
||||
for file in *;
|
||||
do
|
||||
echo $file found;
|
||||
done
|
||||
|
||||
# To implement a case command:
|
||||
case "$1"
|
||||
in
|
||||
0) echo "zero found";;
|
||||
1) echo "one found";;
|
||||
2) echo "two found";;
|
||||
3*) echo "something beginning with 3 found";;
|
||||
esac
|
||||
|
||||
# Turn on debugging:
|
||||
set -x
|
||||
|
||||
# Turn off debugging:
|
||||
set +x
|
||||
|
||||
# Retrieve N-th piped command exit status
|
||||
printf 'foo' | fgrep 'foo' | sed 's/foo/bar/'
|
||||
echo ${PIPESTATUS[0]} # replace 0 with N
|
||||
|
||||
# Lock file:
|
||||
( set -o noclobber; echo > my.lock ) || echo 'Failed to create lock file'
|
@ -1,26 +0,0 @@
|
||||
# Install a package locally
|
||||
bower install <package-name>
|
||||
|
||||
# Install a package locally directly from github
|
||||
bower install <user>/<repo>
|
||||
|
||||
# Install a specific package locally
|
||||
bower install <package-name>#<version>
|
||||
|
||||
# Install a package locally and save installed package into bower.json
|
||||
bower install <package-name> --save
|
||||
|
||||
# Retrieve info of a particular package
|
||||
bower info <package-name>
|
||||
|
||||
# List local packages
|
||||
bower list
|
||||
|
||||
# Search for a package by name
|
||||
bower search <package-name>
|
||||
|
||||
# Update a package to their newest version
|
||||
bower update <package-name>
|
||||
|
||||
# Remove a local package
|
||||
bower uninstall <package-name>
|
@ -1,11 +0,0 @@
|
||||
# compress foo -> foo.bz2
|
||||
bzip2 -z foo
|
||||
|
||||
# decompress foo.bz2 -> foo
|
||||
bzip2 -d foo.bz2
|
||||
|
||||
# compress foo to stdout
|
||||
bzip2 -zc foo > foo.bz2
|
||||
|
||||
# decompress foo.bz2 to stdout
|
||||
bzip2 -dc foo.bz2
|
@ -1,8 +0,0 @@
|
||||
# Display the contents of a file
|
||||
cat /path/to/foo
|
||||
|
||||
# Display contents with line numbers
|
||||
cat -n /path/to/foo
|
||||
|
||||
# Display contents with line numbers (blank lines excluded)
|
||||
cat -b /path/to/foo
|
@ -1,11 +0,0 @@
|
||||
#Go to the given directory
|
||||
cd path/to/directory
|
||||
|
||||
#Go to home directory of current user
|
||||
cd
|
||||
|
||||
#Go up to the parent of the current directory
|
||||
cd ..
|
||||
|
||||
#Go to the previously chosen directory
|
||||
cd -
|
@ -1,14 +0,0 @@
|
||||
# To see example usage of a program:
|
||||
cheat <command>
|
||||
|
||||
# To edit a cheatsheet
|
||||
cheat -e <command>
|
||||
|
||||
# To list available cheatsheets
|
||||
cheat -l
|
||||
|
||||
# To search available cheatsheets
|
||||
cheat -s <command>
|
||||
|
||||
# To get the current `cheat' version
|
||||
cheat -v
|
@ -1,36 +0,0 @@
|
||||
# Add execute for all (myscript.sh)
|
||||
chmod a+x myscript.sh
|
||||
|
||||
# Set user to read/write/execute, group/global to read only (myscript.sh), symbolic mode
|
||||
chmod u=rwx, go=r myscript.sh
|
||||
|
||||
# Remove write from user/group/global (myscript.sh), symbolic mode
|
||||
chmod a-w myscript.sh
|
||||
|
||||
# Remove read/write/execute from user/group/global (myscript.sh), symbolic mode
|
||||
chmod = myscript.sh
|
||||
|
||||
# Set user to read/write and group/global read (myscript.sh), octal notation
|
||||
chmod 644 myscript.sh
|
||||
|
||||
# Set user to read/write/execute and group/global read/execute (myscript.sh), octal notation
|
||||
chmod 755 myscript.sh
|
||||
|
||||
# Set user/group/global to read/write (myscript.sh), octal notation
|
||||
chmod 666 myscript.sh
|
||||
|
||||
# Roles
|
||||
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)
|
||||
|
||||
# Numeric representations
|
||||
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 (---)
|
@ -1,11 +0,0 @@
|
||||
# Change file owner
|
||||
chown user file
|
||||
|
||||
# Change file owner and group
|
||||
chown user:group file
|
||||
|
||||
# Change owner recursively
|
||||
chown -R user directory
|
||||
|
||||
# Change ownership to match another file
|
||||
chown --reference=/path/to/ref_file file
|
@ -1,19 +0,0 @@
|
||||
# To resize an image to a fixed width and proportional height:
|
||||
convert original-image.jpg -resize 100x converted-image.jpg
|
||||
|
||||
# To resize an image to a fixed height and proportional width:
|
||||
convert original-image.jpg -resize x100 converted-image.jpg
|
||||
|
||||
# To resize an image to a fixed width and height:
|
||||
convert original-image.jpg -resize 100x100 converted-image.jpg
|
||||
|
||||
# To resize an image and simultaneously change its file type:
|
||||
convert original-image.jpg -resize 100x converted-image.png
|
||||
|
||||
# To resize all of the images within a directory:
|
||||
# To implement a for loop:
|
||||
for file in `ls original/image/path/`;
|
||||
do new_path=${file%.*};
|
||||
new_file=`basename $new_path`;
|
||||
convert $file -resize 150 converted/image/path/$new_file.png;
|
||||
done
|
@ -1,11 +0,0 @@
|
||||
# Create a copy of a file
|
||||
cp ~/Desktop/foo.txt ~/Downloads/foo.txt
|
||||
|
||||
# Create a copy of a directory
|
||||
cp -r ~/Desktop/cruise_pics/ ~/Pictures/
|
||||
|
||||
# Create a copy but ask to overwrite if the destination file already exists
|
||||
cp -i ~/Desktop/foo.txt ~/Documents/foo.txt
|
||||
|
||||
# Create a backup file with date
|
||||
cp foo.txt{,."$(date +%Y%m%d-%H%M%S)"}
|
@ -1,132 +0,0 @@
|
||||
# Read in.pdf, select pages 1, 2, 3 and 6, and write those pages to
|
||||
# out.pdf
|
||||
cpdf in.pdf 1-3,6 -o out.pdf
|
||||
|
||||
# Select the even pages (2, 4, 6...) from in.pdf and write those pages
|
||||
# to out.pdf
|
||||
cpdf in.pdf even -o out.pdf
|
||||
|
||||
# Using AND to perform several operations in order, here merging two
|
||||
# files together and adding a copyright stamp to every page.
|
||||
cpdf -merge in.pdf in2.pdf AND -add-text "Copyright 2014" -o out.pdf
|
||||
|
||||
# Read control.txt and use its contents as the command line arguments
|
||||
# for cpdf.
|
||||
cpdf -control control.txt
|
||||
|
||||
# Merge in.pdf and in2.pdf into one document, writing to out.pdf.
|
||||
cpdf -merge in.pdf in2.pdf -o out.pdf
|
||||
|
||||
# Split in.pdf into ten-page chunks, writing them to Chunk001.pdf,
|
||||
# Chunk002.pdf etc
|
||||
cpdf -split in.pdf -o Chunk%%%.pdf -chunk 10
|
||||
|
||||
# Split in.pdf on bookmark boundaries, writing each to a file whose
|
||||
# name is the bookmark label
|
||||
cpdf -split-bookmarks 0 in.pdf -o @N.pdf
|
||||
|
||||
# Scale both the dimensions and contents of in.pdf by a factor of two
|
||||
# in x and y directions.
|
||||
cpdf -scale-page "2 2" in.pdf -o out.pdf
|
||||
|
||||
# Scale the pages in in.pdf to fit the US Letter page size, writing to
|
||||
# out.pdf
|
||||
cpdf -scale-to-fit usletterportrait in.pdf -o out.pdf
|
||||
|
||||
# Shift the contents of the page by 26 pts in the x direction, and 18
|
||||
# millimetres in the y direction, writing to out.pdf
|
||||
cpdf -shift "26pt 18mm" in.pdf -o out.pdf
|
||||
|
||||
# Rotate the contents of the pages in in.pdf by ninety degrees and
|
||||
# write to out.pdf.
|
||||
cpdf -rotate-contents 90 in.pdf -o out.pdf
|
||||
|
||||
# Crop the pages in in.pdf to a 600 pts by 400 pts rectangle.
|
||||
cpdf -crop "0 0 600pt 400pt" in.pdf -o out.pdf
|
||||
|
||||
# Encrypt using 128bit PDF encryption using the owner password 'fred'
|
||||
# and the user password 'joe'
|
||||
cpdf -encrypt 128bit fred joe in.pdf -o out.pdf
|
||||
|
||||
# Decrypt using the owner password, writing to out.pdf.
|
||||
cpdf -decrypt in.pdf owner=fred -o out.pdf
|
||||
|
||||
# Compress the data streams in in.pdf, writing the result to out.pdf.
|
||||
cpdf -compress in.pdf -o out.pdf
|
||||
|
||||
# Decompress the data streams in in.pdf, writing to out.pdf.
|
||||
cpdf -decompress in.pdf -o out.pdf
|
||||
|
||||
# List the bookmarks in in.pdf. This would produce:
|
||||
cpdf -list-bookmarks in.pdf
|
||||
|
||||
# Outputs:
|
||||
|
||||
# Add bookmarks in the same form from a prepared file bookmarks.txt to
|
||||
# in.pdf, writing to out.pdf.
|
||||
cpdf -add-bookmarks bookmarks.txt in.pdf -o out.pdf
|
||||
|
||||
# Use the Split style to build a presentation from the PDF in.pdf,
|
||||
# each slide staying 10 seconds on screen unless manually advanced.
|
||||
# The first page, being a title does not move on automatically, and
|
||||
# has no transition effect.
|
||||
cpdf -presentation in.pdf 2-end -trans Split -duration 10 -o out.pdf
|
||||
|
||||
# Stamp the file watermark.pdf on to each page of in.pdf, writing the
|
||||
# result to out.pdf.
|
||||
cpdf -stamp-on watermark.pdf in.pdf -o out.pdf
|
||||
|
||||
# Add a page number and date to all the pages in in.pdf using the
|
||||
# Courier font, writing to out.pdf
|
||||
cpdf -topleft 10 -font Courier -add-text "Page %Page\nDate %d-%m-%Y" in.pdf -o out.pdf
|
||||
|
||||
# Two up impose the file in.pdf, writing to out.pdf
|
||||
cpdf -twoup-stack in.pdf -o out.pdf
|
||||
|
||||
# Add extra blank pages after pages one, three and four of a document.
|
||||
cpdf -pad-after 1,3,4 in.pdf -o out.pdf
|
||||
|
||||
# List the annotations in a file in.pdf to standard output.
|
||||
cpdf -list-annotations in.pdf
|
||||
|
||||
# Might Produce:
|
||||
|
||||
# -- # Annotation text content 1 # -- # -- # Annotation text content 2
|
||||
# --
|
||||
|
||||
# Copy the annotations from from.pdf to in.pdf, writing to out.pdf.
|
||||
cpdf -copy-annotations from.pdf in.pdf -o out.pdf
|
||||
|
||||
# Set the document title of in.pdf. writing to out.pdf.
|
||||
cpdf -set-title "The New Title" in.pdf -o out.pdf
|
||||
|
||||
# Set the document in.pdf to open with the Acrobat Viewer's toolbar
|
||||
# hidden, writing to out.pdf.
|
||||
cpdf -hide-toolbar true in.pdf -o out.pdf
|
||||
|
||||
# Set the metadata in a PDF in.pdf to the contents of the file
|
||||
# metadata.xml, and write the output to out.pdf.
|
||||
cpdf -set-metadata metadata.xml in.pdf -o out.pdf
|
||||
|
||||
# Set the document in.pdf to open in Acrobat Viewer showing two
|
||||
# columns of pages, starting on the right, putting the result in
|
||||
# out.pdf.
|
||||
cpdf -set-page-layout TwoColumnRight in.pdf -o out.pdf
|
||||
|
||||
# Set the document in.pdf to open in Acrobat Viewer in full screen
|
||||
# mode, putting the result in out.pdf.
|
||||
cpdf -set-page-mode FullScreen in.pdf -o out.pdf
|
||||
|
||||
# Attach the file sheet.xls to in.pdf, writing to out.pdf.
|
||||
cpdf -attach-file sheet.xls in.pdf -o out.pdf
|
||||
|
||||
# Remove any attachments from in.pdf, writing to out.pdf.
|
||||
cpdf -remove-files in.pdf -o out.pdf
|
||||
|
||||
# Blacken all the text in in.pdf, writing to out.pdf.
|
||||
cpdf -blacktext in.pdf -o out.pdf
|
||||
|
||||
# Make sure all lines in in.pdf are at least 2 pts wide, writing to
|
||||
# out.pdf.
|
||||
cpdf -thinlines 2pt in.pdf -o out.pdf
|
||||
|
@ -1,22 +0,0 @@
|
||||
# set a shell
|
||||
SHELL=/bin/bash
|
||||
|
||||
# crontab format
|
||||
* * * * * command_to_execute
|
||||
- - - - -
|
||||
| | | | |
|
||||
| | | | +- day of week (0 - 7) (where sunday is 0 and 7)
|
||||
| | | +--- month (1 - 12)
|
||||
| | +----- day (1 - 31)
|
||||
| +------- hour (0 - 23)
|
||||
+--------- minute (0 - 59)
|
||||
|
||||
# example entries
|
||||
# every 15 min
|
||||
*/15 * * * * /home/user/command.sh
|
||||
|
||||
# every midnight
|
||||
0 0 * * * /home/user/command.sh
|
||||
|
||||
# every Saturday at 8:05 AM
|
||||
5 8 * * 6 /home/user/command.sh
|
@ -1,8 +0,0 @@
|
||||
# open encrypted partition /dev/sdb1 (reachable at /dev/mapper/backup)
|
||||
cryptsetup open --type luks /dev/sdb1 backup
|
||||
|
||||
# open encrypted partition /dev/sdb1 using a keyfile (reachable at /dev/mapper/hdd)
|
||||
cryptsetup open --type luks --key-file hdd.key /dev/sdb1 hdd
|
||||
|
||||
# close luks container at /dev/mapper/hdd
|
||||
cryptsetup close hdd
|
@ -1,5 +0,0 @@
|
||||
# Split a file based on pattern
|
||||
csplit input.file '/PATTERN/'
|
||||
|
||||
# Use prefix/suffix to improve resulting file names
|
||||
csplit -f 'prefix-' -b '%d.extension' input.file '/PATTERN/' '{*}'
|
@ -1,22 +0,0 @@
|
||||
# Manage printers through CUPS:
|
||||
http://localhost:631 (in web browser)
|
||||
|
||||
# Print file from command line
|
||||
lp myfile.txt
|
||||
|
||||
# Display print queue
|
||||
lpq
|
||||
|
||||
# Remove print job from queue
|
||||
lprm 545
|
||||
or
|
||||
lprm -
|
||||
|
||||
# Print log location
|
||||
/var/log/cups
|
||||
|
||||
# Reject new jobs
|
||||
cupsreject printername
|
||||
|
||||
# Accept new jobs
|
||||
cupsaccept printername
|
@ -1,41 +0,0 @@
|
||||
# Download a single file
|
||||
curl http://path.to.the/file
|
||||
|
||||
# Download a file and specify a new filename
|
||||
curl http://example.com/file.zip -o new_file.zip
|
||||
|
||||
# Download multiple files
|
||||
curl -O URLOfFirstFile -O URLOfSecondFile
|
||||
|
||||
# Download all sequentially numbered files (1-24)
|
||||
curl http://example.com/pic[1-24].jpg
|
||||
|
||||
# Download a file and pass HTTP Authentication
|
||||
curl -u username:password URL
|
||||
|
||||
# Download a file with a Proxy
|
||||
curl -x proxysever.server.com:PORT http://addressiwantto.access
|
||||
|
||||
# Download a file from FTP
|
||||
curl -u username:password -O ftp://example.com/pub/file.zip
|
||||
|
||||
# Get an FTP directory listing
|
||||
curl ftp://username:password@example.com
|
||||
|
||||
# Resume a previously failed download
|
||||
curl -C - -o partial_file.zip http://example.com/file.zip
|
||||
|
||||
# Fetch only the HTTP headers from a response
|
||||
curl -I http://example.com
|
||||
|
||||
# Fetch your external IP and network info as JSON
|
||||
curl http://ifconfig.me/all.json
|
||||
|
||||
# Limit the rate of a download
|
||||
curl --limit-rate 1000B -O http://path.to.the/file
|
||||
|
||||
# Get your global IP
|
||||
curl httpbin.org/ip
|
||||
|
||||
# Get only the HTTP status code
|
||||
curl -o /dev/null -w '%{http_code}\n' -s -I URL
|
@ -1,2 +0,0 @@
|
||||
# To cut out the third field of text or stdoutput that is delimited by a #:
|
||||
cut -d# -f3
|
@ -1,8 +0,0 @@
|
||||
# Print date in format suitable for affixing to file names
|
||||
date +"%Y%m%d_%H%M%S"
|
||||
|
||||
# Convert Unix timestamp to Date(Linux)
|
||||
date -d @1440359821
|
||||
|
||||
# Convert Unix timestamp to Date(Mac)
|
||||
date -r 1440359821
|
@ -1,22 +0,0 @@
|
||||
# Read from {/dev/urandom} 2*512 Bytes and put it into {/tmp/test.txt}
|
||||
# Note: At the first iteration, we read 512 Bytes.
|
||||
# Note: At the second iteration, we read 512 Bytes.
|
||||
dd if=/dev/urandom of=/tmp/test.txt count=2 bs=512
|
||||
|
||||
# Watch the progress of 'dd'
|
||||
dd if=/dev/zero of=/dev/null bs=4KB &; export dd_pid=`pgrep '^dd'`; while [[ -d /proc/$dd_pid ]]; do kill -USR1 $dd_pid && sleep 1 && clear; done
|
||||
|
||||
# Watch the progress of 'dd' with `pv` and `dialog` (apt-get install pv dialog)
|
||||
(pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror) 2>&1 | dialog --gauge "Running dd command (cloning), please wait..." 10 70 0
|
||||
|
||||
# Watch the progress of 'dd' with `pv` and `zenity` (apt-get install pv zenity)
|
||||
(pv -n /dev/zero | dd of=/dev/null bs=128M conv=notrunc,noerror) 2>&1 | zenity --title 'Running dd command (cloning), please wait...' --progress
|
||||
|
||||
# Watch the progress of 'dd' with the built-in `progress` functionality (introduced in coreutils v8.24)
|
||||
dd if=/dev/zero of=/dev/null bs=128M status=progress
|
||||
|
||||
# DD with "graphical" return
|
||||
dcfldd if=/dev/zero of=/dev/null bs=500K
|
||||
|
||||
# This will output the sound from your microphone port to the ssh target computer's speaker port. The sound quality is very bad, so you will hear a lot of hissing.
|
||||
dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp
|
@ -1,7 +0,0 @@
|
||||
# Extract contents of a .deb file
|
||||
$ ar vx foo.deb # -> data.tar.gz
|
||||
$ tar xf data.tar.gz
|
||||
|
||||
# Install .deb file to a debian like system, e.g. ubuntu
|
||||
$ sudo dpkg -i foo.deb
|
||||
$ sudo apt-get install -f
|
@ -1,2 +0,0 @@
|
||||
# Printout disk free space in a human readable format
|
||||
df -h
|
@ -1,10 +0,0 @@
|
||||
# To release the current IP address:
|
||||
sudo dhclient -r
|
||||
|
||||
# To obtain a new IP address:
|
||||
sudo dhclient
|
||||
|
||||
# Running the above in sequence is a common way of refreshing an IP.
|
||||
|
||||
# To obtain a new IP address for a specific interface:
|
||||
sudo dhclient eth0
|
@ -1,26 +0,0 @@
|
||||
# To view the differences between two files:
|
||||
diff -u version1 version2
|
||||
|
||||
# To view the differences between two directories:
|
||||
diff -ur folder1/ folder2/
|
||||
|
||||
# To ignore the white spaces:
|
||||
diff -ub version1 version2
|
||||
|
||||
# To ignore the blank lines:
|
||||
diff -uB version1 version2
|
||||
|
||||
# To ignore the differences between uppercase and lowercase:
|
||||
diff -ui version1 version2
|
||||
|
||||
# To report whether the files differ:
|
||||
diff -q version1 version2
|
||||
|
||||
# To report whether the files are identical:
|
||||
diff -s version1 version2
|
||||
|
||||
# To diff the output of two commands or scripts:
|
||||
diff <(command1) <(command2)
|
||||
|
||||
# Generate a patch file from two files
|
||||
diff -Naur version1 version2 > version.patch
|
@ -1,29 +0,0 @@
|
||||
# INSTALL
|
||||
# ==============================================================================
|
||||
# Edit /etc/default/distcc and set theses vars
|
||||
# STARTDISTCC="true"
|
||||
# ALLOWEDNETS="127.0.0.1 192.168.1.0/24"# Your computer and local computers
|
||||
# #LISTENER="127.0.0.1"# Comment it
|
||||
# ZEROCONF="true"# Auto configuration
|
||||
|
||||
# REMEMBER 1:
|
||||
# Start/Restart your distccd servers before using one of these commands.
|
||||
# service distccd start
|
||||
|
||||
# REMEMBER 2:
|
||||
# Do not forget to install on each machine DISTCC.
|
||||
# No need to install libs ! Only main host need libs !
|
||||
|
||||
# USAGE
|
||||
# ==============================================================================
|
||||
|
||||
# Run make with 4 thread (a cross network) in auto configuration.
|
||||
# Note: for gcc, Replace CXX by CC and g++ by gcc
|
||||
ZEROCONF='+zeroconf' make -j4 CXX='distcc g++'
|
||||
|
||||
# Run make with 4 thread (a cross network) in static configuration (2 ip)
|
||||
# Note: for gcc, Replace CXX by CC and g++ by gcc
|
||||
DISTCC_HOSTS='127.0.0.1 192.168.1.69' make -j4 CXX='distcc g++'
|
||||
|
||||
# Show hosts aviables
|
||||
ZEROCONF='+zeroconf' distcc --show-hosts
|
@ -1,16 +0,0 @@
|
||||
# To install the latest version of a package:
|
||||
dnf install <package name>
|
||||
|
||||
# To search package details for the given string
|
||||
dnf search <string>
|
||||
|
||||
# To find which package provides a binary
|
||||
dnf provides <path to binary>
|
||||
|
||||
# The following are available after installing "dnf-plugins-core"
|
||||
|
||||
# Download a package
|
||||
dnf download <package name>
|
||||
|
||||
# install the build dependencies for a SRPM or from a .spec file
|
||||
dnf builddep <srpm/.spec file>
|
@ -1,32 +0,0 @@
|
||||
# Start docker daemon
|
||||
docker -d
|
||||
|
||||
# start a container with an interactive shell
|
||||
docker run -ti <image_name> /bin/bash
|
||||
|
||||
# "shell" into a running container (docker-1.3+)
|
||||
docker exec -ti <container_name> bash
|
||||
|
||||
# inspect a running container
|
||||
docker inspect <container_name> (or <container_id>)
|
||||
|
||||
# Get the process ID for a container
|
||||
# Source: https://github.com/jpetazzo/nsenter
|
||||
docker inspect --format {{.State.Pid}} <container_name_or_ID>
|
||||
|
||||
# List the current mounted volumes for a container (and pretty print)
|
||||
# Source:
|
||||
# http://nathanleclaire.com/blog/2014/07/12/10-docker-tips-and-tricks-that-will-make-you-sing-a-whale-song-of-joy/
|
||||
docker inspect --format='{{json .Volumes}}' <container_id> | python -mjson.tool
|
||||
|
||||
# Copy files/folders between a container and your host
|
||||
docker cp foo.txt mycontainer:/foo.txt
|
||||
|
||||
# list currently running containers
|
||||
docker ps
|
||||
|
||||
# list all containers
|
||||
docker ps -a
|
||||
|
||||
# list all images
|
||||
docker images
|
@ -1,11 +0,0 @@
|
||||
# Install the package or upgrade it
|
||||
dpkg -i test.deb
|
||||
|
||||
# Remove a package including configuration files
|
||||
dpkg -P test.deb
|
||||
|
||||
# List all installed packages with versions and details
|
||||
dpkg -l
|
||||
|
||||
# Find out if a Debian package is installed or not
|
||||
dpkg -s test.deb | grep Status
|
@ -1,5 +0,0 @@
|
||||
# To sort directories/files by size
|
||||
du -sk *| sort -rn
|
||||
|
||||
# To show cumulative humanreadable size
|
||||
du -sh
|
@ -1,64 +0,0 @@
|
||||
# Running emacs
|
||||
|
||||
GUI mode $ emacs
|
||||
Terminal mode $ emacs -nw
|
||||
|
||||
# Basic usage
|
||||
|
||||
Indent Select text then press TAB
|
||||
Cut C-w
|
||||
Copy M-w
|
||||
Paste ("yank") C-y
|
||||
Begin selection C-SPACE
|
||||
Search/Find C-s
|
||||
Replace M-% (M-SHIFT-5)
|
||||
Save C-x C-s
|
||||
Save as C-x C-w
|
||||
Load/Open C-x C-f
|
||||
Undo C-x u
|
||||
Highlight all text C-x h
|
||||
Directory listing C-x d
|
||||
Cancel a command C-g
|
||||
Font size bigger C-x C-+
|
||||
Font size smaller C-x C--
|
||||
|
||||
# Buffers
|
||||
|
||||
Split screen vertically C-x 2
|
||||
Split screen vertically with 5 row height C-u 5 C-x 2
|
||||
Split screen horizontally C-x 3
|
||||
Split screen horizontally with 24 column width C-u 24 C-x 3
|
||||
Revert to single screen C-x 1
|
||||
Hide the current screen C-x 0
|
||||
Move to the next screen C-x o
|
||||
Kill the current buffer C-x k
|
||||
Select a buffer C-x b
|
||||
Run command in the scratch buffer C-x C-e
|
||||
|
||||
# Navigation ( backward / forward )
|
||||
|
||||
Character-wise C-b , C-f
|
||||
Word-wise M-b , M-f
|
||||
Line-wise C-p , C-n
|
||||
Sentence-wise M-a , M-e
|
||||
Paragraph-wise M-{ , M-}
|
||||
Function-wise C-M-a , C-M-e
|
||||
Line beginning / end C-a , C-e
|
||||
|
||||
# Other stuff
|
||||
|
||||
Open a shell M-x eshell
|
||||
Goto a line number M-x goto-line
|
||||
Word wrap M-x toggle-word-wrap
|
||||
Spell checking M-x flyspell-mode
|
||||
Line numbers M-x linum-mode
|
||||
Toggle line wrap M-x visual-line-mode
|
||||
Compile some code M-x compile
|
||||
List packages M-x package-list-packages
|
||||
|
||||
# Line numbers
|
||||
|
||||
To add line numbers and enable moving to a line with C-l:
|
||||
|
||||
(global-set-key "\C-l" 'goto-line)
|
||||
(add-hook 'find-file-hook (lambda () (linum-mode 1)))
|
@ -1,5 +0,0 @@
|
||||
# Calling export with no arguments will show current shell attributes
|
||||
export
|
||||
|
||||
# Create new environment variable
|
||||
export VARNAME="value"
|
@ -1,23 +0,0 @@
|
||||
# Print file metadata etc.
|
||||
ffmpeg -i path/to/file.ext
|
||||
|
||||
# Convert all m4a files to mp3
|
||||
for f in *.m4a; do ffmpeg -i "$f" -acodec libmp3lame -vn -b:a 320k "${f%.m4a}.mp3"; done
|
||||
|
||||
# Convert video from .foo to .bar
|
||||
# -g : GOP, for searchability
|
||||
ffmpeg -i input.foo -vcodec bar -acodec baz -b:v 21000k -b:a 320k -g 150 -threads 4 output.bar
|
||||
|
||||
# Convert image sequence to video
|
||||
ffmpeg -r 18 -pattern_type glob -i '*.png' -b:v 21000k -s hd1080 -vcodec vp9 -an -pix_fmt yuv420p -deinterlace output.ext
|
||||
|
||||
# Combine video and audio into one file
|
||||
ffmpeg -i video.ext -i audio.ext -c:v copy -c:a copy output.ext
|
||||
|
||||
# Listen to 10 seconds of audio from a video file
|
||||
#
|
||||
# -ss : start time
|
||||
# -t : seconds to cut
|
||||
# -autoexit : closes ffplay as soon as the audio finishes
|
||||
ffmpeg -ss 00:34:24.85 -t 10 -i path/to/file.mp4 -f mp3 pipe:play | ffplay -i pipe:play -autoexit
|
||||
|
@ -1,47 +0,0 @@
|
||||
# To find files by case-insensitive extension (ex: .jpg, .JPG, .jpG):
|
||||
find . -iname "*.jpg"
|
||||
|
||||
# To find directories:
|
||||
find . -type d
|
||||
|
||||
# To find files:
|
||||
find . -type f
|
||||
|
||||
# To find files by octal permission:
|
||||
find . -type f -perm 777
|
||||
|
||||
# To find files with setuid bit set:
|
||||
find . -xdev \( -perm -4000 \) -type f -print0 | xargs -0 ls -l
|
||||
|
||||
# To find files with extension '.txt' and remove them:
|
||||
find ./path/ -name '*.txt' -exec rm '{}' \;
|
||||
|
||||
# To find files with extension '.txt' and look for a string into them:
|
||||
find ./path/ -name '*.txt' | xargs grep 'string'
|
||||
|
||||
# To find files with size bigger than 5 Mebibyte and sort them by size:
|
||||
find . -size +5M -type f -print0 | xargs -0 ls -Ssh | sort -z
|
||||
|
||||
# To find files bigger than 2 Megabyte and list them:
|
||||
find . -type f -size +200000000c -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'
|
||||
|
||||
# To find files modified more than 7 days ago and list file information
|
||||
find . -type f -mtime +7d -ls
|
||||
|
||||
# To find symlinks owned by a user and list file information
|
||||
find . -type l --user=username -ls
|
||||
|
||||
# To search for and delete empty directories
|
||||
find . -type d -empty -exec rmdir {} \;
|
||||
|
||||
# To search for directories named build at a max depth of 2 directories
|
||||
find . -maxdepth 2 -name build -type d
|
||||
|
||||
# To search all files who are not in .git directory
|
||||
find . ! -iwholename '*.git*' -type f
|
||||
|
||||
# To find all files that have the same node (hard link) as MY_FILE_HERE
|
||||
find . -type f -samefile MY_FILE_HERE 2>/dev/null
|
||||
|
||||
# To find all files in the current directory and modify their permissions
|
||||
find . -type f -exec chmod 644 {} \;
|
@ -1,35 +0,0 @@
|
||||
# basic loop
|
||||
for i in 1 2 3 4 5 6 7 8 9 10
|
||||
do
|
||||
echo $i
|
||||
done
|
||||
|
||||
# loop ls command results
|
||||
for var in `ls -alF`
|
||||
do
|
||||
echo $var
|
||||
done
|
||||
|
||||
# loop over all the JPG files in the current directory
|
||||
for jpg_file in *.jpg
|
||||
do
|
||||
echo $jpg_file
|
||||
done
|
||||
|
||||
# loop specified number of times
|
||||
for i in `seq 1 10`
|
||||
do
|
||||
echo $i
|
||||
done
|
||||
|
||||
# loop specified number of times: the C/C++ style
|
||||
for ((i=1;i<=10;++i))
|
||||
do
|
||||
echo $i
|
||||
done
|
||||
|
||||
# loop specified number of times: the brace expansion
|
||||
for i in {1..10}
|
||||
do
|
||||
echo $i
|
||||
done
|
@ -1,21 +0,0 @@
|
||||
# Compile a file
|
||||
gcc file.c
|
||||
|
||||
# Compile a file with a custom output
|
||||
gcc -o file file.c
|
||||
|
||||
# Debug symbols
|
||||
gcc -g
|
||||
|
||||
# Debug with all symbols.
|
||||
gcc -ggdb3
|
||||
|
||||
# Build for 64 bits
|
||||
gcc -m64
|
||||
|
||||
# Include the directory {/usr/include/myPersonnal/lib/} to the list of path for #include <....>
|
||||
# With this option, no warning / error will be reported for the files in {/usr/include/myPersonnal/lib/}
|
||||
gcc -isystem /usr/include/myPersonnal/lib/
|
||||
|
||||
# Build a GUI for windows (Mingw) (Will disable the term/console)
|
||||
gcc -mwindows
|
@ -1,26 +0,0 @@
|
||||
# start the debugger
|
||||
gdb your-executable
|
||||
|
||||
# set a breakpoint
|
||||
b some-method, break some-method
|
||||
|
||||
# run the program
|
||||
r, run
|
||||
|
||||
# when a breakpoint was reached:
|
||||
|
||||
# run the current line, stepping over any invocations
|
||||
n, next
|
||||
# run the current line, stepping into any invocations
|
||||
s, step
|
||||
# print a stacktrace
|
||||
bt, backtrace
|
||||
# evaluate an expression and print the result
|
||||
p length=strlen(string)
|
||||
# list surrounding source code
|
||||
l, list
|
||||
# continue execution
|
||||
c, continue
|
||||
|
||||
# exit gdb (after program terminated)
|
||||
q, quit
|
@ -1,151 +0,0 @@
|
||||
# To set your identity:
|
||||
git config --global user.name "John Doe"
|
||||
git config --global user.email johndoe@example.com
|
||||
|
||||
# To set your editor:
|
||||
git config --global core.editor emacs
|
||||
|
||||
# To enable color:
|
||||
git config --global color.ui true
|
||||
|
||||
# To stage all changes for commit:
|
||||
git add --all
|
||||
|
||||
# To stash changes locally, this will keep the changes in a separate changelist
|
||||
# called stash and the working directory is cleaned. You can apply changes
|
||||
# from the stash anytime
|
||||
git stash
|
||||
|
||||
# To stash changes with a message
|
||||
git stash save "message"
|
||||
|
||||
# To list all the stashed changes
|
||||
git stash list
|
||||
|
||||
# To apply the most recent change and remove the stash from the stash list
|
||||
git stash pop
|
||||
|
||||
# To apply any stash from the list of stashes. This does not remove the stash
|
||||
# from the stash list
|
||||
git stash apply stash@{6}
|
||||
|
||||
# To commit staged changes
|
||||
git commit -m "Your commit message"
|
||||
|
||||
# To edit previous commit message
|
||||
git commit --amend
|
||||
|
||||
# Git commit in the past
|
||||
git commit --date="`date --date='2 day ago'`"
|
||||
git commit --date="Jun 13 18:30:25 IST 2015"
|
||||
# more recent versions of Git also support --date="2 days ago" directly
|
||||
|
||||
# To change the date of an existing commit
|
||||
git filter-branch --env-filter \
|
||||
'if [ $GIT_COMMIT = 119f9ecf58069b265ab22f1f97d2b648faf932e0 ]
|
||||
then
|
||||
export GIT_AUTHOR_DATE="Fri Jan 2 21:38:53 2009 -0800"
|
||||
export GIT_COMMITTER_DATE="Sat May 19 01:01:01 2007 -0700"
|
||||
fi'
|
||||
|
||||
# To removed staged and working directory changes
|
||||
git reset --hard
|
||||
|
||||
# To go 2 commits back
|
||||
git reset --hard HEAD~2
|
||||
|
||||
# To remove untracked files
|
||||
git clean -f -d
|
||||
|
||||
# To remove untracked and ignored files
|
||||
git clean -f -d -x
|
||||
|
||||
# To push to the tracked master branch:
|
||||
git push origin master
|
||||
|
||||
# To push to a specified repository:
|
||||
git push git@github.com:username/project.git
|
||||
|
||||
# To delete the branch "branch_name"
|
||||
git branch -D branch_name
|
||||
|
||||
# To make an exisiting branch track a remote branch
|
||||
git branch -u upstream/foo
|
||||
|
||||
# To see who commited which line in a file
|
||||
git blame filename
|
||||
|
||||
# To sync a fork with the master repo:
|
||||
git remote add upstream git@github.com:name/repo.git # Set a new repo
|
||||
git remote -v # Confirm new remote repo
|
||||
git fetch upstream # Get branches
|
||||
git branch -va # List local - remote branches
|
||||
git checkout master # Checkout local master branch
|
||||
git checkout -b new_branch # Create and checkout a new branch
|
||||
git merge upstream/master # Merge remote into local repo
|
||||
git show 83fb499 # Show what a commit did.
|
||||
git show 83fb499:path/fo/file.ext # Shows the file as it appeared at 83fb499.
|
||||
git diff branch_1 branch_2 # Check difference between branches
|
||||
git log # Show all the commits
|
||||
git status # Show the changes from last commit
|
||||
|
||||
# Commit history of a set of files
|
||||
git log --pretty=email --patch-with-stat --reverse --full-index -- Admin\*.py > Sripts.patch
|
||||
|
||||
# Import commits from another repo
|
||||
git --git-dir=../some_other_repo/.git format-patch -k -1 --stdout <commit SHA> | git am -3 -k
|
||||
|
||||
# View commits that will be pushed
|
||||
git log @{u}..
|
||||
|
||||
# View changes that are new on a feature branch
|
||||
git log -p feature --not master
|
||||
git diff master...feature
|
||||
|
||||
# Interactive rebase for the last 7 commits
|
||||
git rebase -i @~7
|
||||
|
||||
# Diff files WITHOUT considering them a part of git
|
||||
# This can be used to diff files that are not in a git repo!
|
||||
git diff --no-index path/to/file/A path/to/file/B
|
||||
|
||||
# To pull changes while overwriting any local commits
|
||||
git fetch --all
|
||||
git reset --hard origin/master
|
||||
|
||||
# Update all your submodules
|
||||
git submodule update --init --recursive
|
||||
|
||||
# Perform a shallow clone to only get latest commits
|
||||
# (helps save data when cloning large repos)
|
||||
git clone --depth 1 <remote-url>
|
||||
|
||||
# To unshallow a clone
|
||||
git pull --unshallow
|
||||
|
||||
# Create a bare branch (one that has no commits on it)
|
||||
git checkout --orphan branch_name
|
||||
|
||||
# Checkout a new branch from a different starting point
|
||||
git checkout -b master upstream/master
|
||||
|
||||
# Remove all stale branches (ones that have been deleted on remote)
|
||||
# So if you have a lot of useless branches, delete them on Github and then run this
|
||||
git remote prune origin
|
||||
|
||||
# The following can be used to prune all remotes at once
|
||||
git remote prune $(git remote | tr '\n' ' ')
|
||||
|
||||
# Revisions can also be identified with :/text
|
||||
# So, this will show the first commit that has "cool" in their message body
|
||||
git show :/cool
|
||||
|
||||
# Undo parts of last commit in a specific file
|
||||
git checkout -p HEAD^ -- /path/to/file
|
||||
|
||||
# Revert a commit and keep the history of the reverted change as a separate revert commit
|
||||
git revert <commit SHA>
|
||||
|
||||
# Pich a commit from a branch to current branch. This is different than merge as
|
||||
# this just applies a single commit from a branch to current branch
|
||||
git cherry-pick <commit SHA1>
|
@ -1,173 +0,0 @@
|
||||
# Create a key
|
||||
|
||||
gpg --gen-key
|
||||
|
||||
|
||||
# Show keys
|
||||
|
||||
To list a summary of all keys
|
||||
|
||||
gpg --list-keys
|
||||
|
||||
To show your public key
|
||||
|
||||
gpg --armor --export
|
||||
|
||||
To show the fingerprint for a key
|
||||
|
||||
gpg --fingerprint KEY_ID
|
||||
|
||||
# Search for keys
|
||||
|
||||
gpg --search-keys 'user@emailaddress.com'
|
||||
|
||||
|
||||
# To Encrypt a File
|
||||
|
||||
gpg --encrypt --recipient 'user@emailaddress.com' example.txt
|
||||
|
||||
|
||||
# To Decrypt a File
|
||||
|
||||
gpg --output example.txt --decrypt example.txt.gpg
|
||||
|
||||
|
||||
# Export keys
|
||||
|
||||
gpg --output ~/public_key.txt --armor --export KEY_ID
|
||||
gpg --output ~/private_key.txt --armor --export-secret-key KEY_ID
|
||||
|
||||
Where KEY_ID is the 8 character GPG key ID.
|
||||
|
||||
Store these files to a safe location, such as a USB drive, then
|
||||
remove the private key file.
|
||||
|
||||
shred -zu ~/private_key.txt
|
||||
|
||||
# Import keys
|
||||
|
||||
Retrieve the key files which you previously exported.
|
||||
|
||||
gpg --import ~/public_key.txt
|
||||
gpg --allow-secret-key-import --import ~/private_key.txt
|
||||
|
||||
Then delete the private key file.
|
||||
|
||||
shred -zu ~/private_key.txt
|
||||
|
||||
# Revoke a key
|
||||
|
||||
Create a revocation certificate.
|
||||
|
||||
gpg --output ~/revoke.asc --gen-revoke KEY_ID
|
||||
|
||||
Where KEY_ID is the 8 character GPG key ID.
|
||||
|
||||
After creating the certificate import it.
|
||||
|
||||
gpg --import ~/revoke.asc
|
||||
|
||||
Then ensure that key servers know about the revokation.
|
||||
|
||||
gpg --send-keys KEY_ID
|
||||
|
||||
# Signing and Verifying files
|
||||
|
||||
If you're uploading files to launchpad you may also want to include
|
||||
a GPG signature file.
|
||||
|
||||
gpg -ba filename
|
||||
|
||||
or if you need to specify a particular key:
|
||||
|
||||
gpg --default-key <key ID> -ba filename
|
||||
|
||||
This then produces a file with a .asc extension which can be uploaded.
|
||||
If you need to set the default key more permanently then edit the
|
||||
file ~/.gnupg/gpg.conf and set the default-key parameter.
|
||||
|
||||
To verify a downloaded file using its signature file.
|
||||
|
||||
gpg --verify filename.asc
|
||||
|
||||
# Signing Public Keys
|
||||
|
||||
Import the public key or retrieve it from a server.
|
||||
|
||||
gpg --keyserver <keyserver> --recv-keys <Key_ID>
|
||||
|
||||
Check its fingerprint against any previously stated value.
|
||||
|
||||
gpg --fingerprint <Key_ID>
|
||||
|
||||
Sign the key.
|
||||
|
||||
gpg --sign-key <Key_ID>
|
||||
|
||||
Upload the signed key to a server.
|
||||
|
||||
gpg --keyserver <keyserver> --send-key <Key_ID>
|
||||
|
||||
# Change the email address associated with a GPG key
|
||||
|
||||
gpg --edit-key <key ID>
|
||||
adduid
|
||||
|
||||
Enter the new name and email address. You can then list the addresses with:
|
||||
|
||||
list
|
||||
|
||||
If you want to delete a previous email address first select it:
|
||||
|
||||
uid <list number>
|
||||
|
||||
Then delete it with:
|
||||
|
||||
deluid
|
||||
|
||||
To finish type:
|
||||
|
||||
save
|
||||
|
||||
Publish the key to a server:
|
||||
|
||||
gpg --send-keys <key ID>
|
||||
|
||||
# Creating Subkeys
|
||||
|
||||
Subkeys can be useful if you don't wish to have your main GPG key
|
||||
installed on multiple machines. In this way you can keep your
|
||||
master key safe and have subkeys with expiry periods or which may be
|
||||
separately revoked installed on various machines. This avoids
|
||||
generating entirely separate keys and so breaking any web of trust
|
||||
which has been established.
|
||||
|
||||
gpg --edit-key <key ID>
|
||||
|
||||
At the prompt type:
|
||||
|
||||
addkey
|
||||
|
||||
Choose RSA (sign only), 4096 bits and select an expiry period.
|
||||
Entropy will be gathered.
|
||||
|
||||
At the prompt type:
|
||||
|
||||
save
|
||||
|
||||
You can also repeat the procedure, but selecting RSA (encrypt only).
|
||||
To remove the master key, leaving only the subkey/s in place:
|
||||
|
||||
gpg --export-secret-subkeys <subkey ID> > subkeys
|
||||
gpg --export <key ID> > pubkeys
|
||||
gpg --delete-secret-key <key ID>
|
||||
|
||||
Import the keys back.
|
||||
|
||||
gpg --import pubkeys subkeys
|
||||
|
||||
Verify the import.
|
||||
|
||||
gpg -K
|
||||
|
||||
Should show sec# instead of just sec.
|
@ -1,29 +0,0 @@
|
||||
# Search a file for a pattern
|
||||
grep pattern file
|
||||
|
||||
# Case insensitive search (with line numbers)
|
||||
grep -in pattern file
|
||||
|
||||
# Recursively grep for string <pattern> in folder:
|
||||
grep -R pattern folder
|
||||
|
||||
# Read search patterns from a file (one per line)
|
||||
grep -f pattern_file file
|
||||
|
||||
# Find lines NOT containing pattern
|
||||
grep -v pattern file
|
||||
|
||||
# You can grep with regular expressions
|
||||
grep "^00" file #Match lines starting with 00
|
||||
grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" file #Find IP add
|
||||
|
||||
# Find all files which match {pattern} in {directory}
|
||||
# This will show: "file:line my research"
|
||||
grep -rnw 'directory' -e "pattern"
|
||||
|
||||
# Exclude grep from your grepped output of ps.
|
||||
# Add [] to the first letter. Ex: sshd -> [s]shd
|
||||
ps aux | grep '[h]ttpd'
|
||||
|
||||
# Colour in red {bash} and keep all other lines
|
||||
ps aux | grep -E --color 'bash|$'
|
@ -1,3 +0,0 @@
|
||||
# To reduce the size of a pdf file:
|
||||
gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile=output.pdf input.pdf
|
||||
|
@ -1,12 +0,0 @@
|
||||
# To estimate the number and the size of all mails on youremail@gmail.com
|
||||
gyb --email youremail@gmail.com --action estimate
|
||||
|
||||
# To backup from youremail@gmail.com to your local-folder
|
||||
gyb --email youremail@gmail.com --action backup --local-folder "~/MyLocalFolder/"
|
||||
|
||||
# To backup from youremail@gmail.com only important or starred emails to the
|
||||
# default local folder GYB-GMail-Backup-youremail@gmail.com
|
||||
gyb --email youremail@gmail.com --search "is:important OR is:starred"
|
||||
|
||||
# To restore from your local-folder to youremail@gmail.com
|
||||
gyb --email youremail@gmail.com --action restore --local-folder "~/MyLocalFolder/"
|
@ -1,17 +0,0 @@
|
||||
# To create a *.gz compressed file
|
||||
gzip test.txt
|
||||
|
||||
# To create a *.gz compressed file to a specific location using -c option (standard out)
|
||||
gzip -c test.txt > test_custom.txt.gz
|
||||
|
||||
# To uncompress a *.gz file
|
||||
gzip -d test.txt.gz
|
||||
|
||||
# Display compression ratio of the compressed file using gzip -l
|
||||
gzip -l *.gz
|
||||
|
||||
# Recursively compress all the files under a specified directory
|
||||
gzip -r documents_directory
|
||||
|
||||
# To create a *.gz compressed file and keep the original
|
||||
gzip < test.txt > test.txt.gz
|
@ -1,32 +0,0 @@
|
||||
# Display all hardware details
|
||||
sudo lshw
|
||||
|
||||
# List currently loaded kernel modules
|
||||
lsmod
|
||||
|
||||
# List all modules available to the system
|
||||
find /lib/modules/$(uname -r) -type f -iname "*.ko"
|
||||
|
||||
# Load a module into kernel
|
||||
modprobe modulename
|
||||
|
||||
# Remove a module from kernel
|
||||
modprobe -r modulename
|
||||
|
||||
# List devices connected via pci bus
|
||||
lspci
|
||||
|
||||
# Debug output for pci devices (hex)
|
||||
lspci -vvxxx
|
||||
|
||||
# Display cpu hardware stats
|
||||
cat /proc/cpuinfo
|
||||
|
||||
# Display memory hardware stats
|
||||
cat /proc/meminfo
|
||||
|
||||
# Output the kernel ring buffer
|
||||
dmesg
|
||||
|
||||
# Ouput kernel messages
|
||||
dmesg --kernel
|
@ -1,8 +0,0 @@
|
||||
# To show the first 10 lines of file
|
||||
head file
|
||||
|
||||
# To show the first N lines of file
|
||||
head -n N file
|
||||
|
||||
# To show the first N bytes of file
|
||||
head -c N file
|
@ -1,20 +0,0 @@
|
||||
# Clone a directory
|
||||
hg clone
|
||||
|
||||
# Add files to hg tracker
|
||||
hg add filename
|
||||
|
||||
# Add all files in a folder to hg tracker
|
||||
hg add folder/
|
||||
|
||||
# Create a commit with all tracked changes and a message
|
||||
hg commit -m "message"
|
||||
|
||||
# Push commits to source repository
|
||||
hg push
|
||||
|
||||
# Pull changes from source repository
|
||||
hg pull
|
||||
|
||||
# Rebase local commits to disambiguate with remote repository
|
||||
hg pull --rebase
|
@ -1,3 +0,0 @@
|
||||
# To see most used top 10 commands:
|
||||
history | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n10
|
||||
|
@ -1,195 +0,0 @@
|
||||
# Custom HTTP method HTTP headers and JSON data:
|
||||
http PUT example.org X-API-Token:123 name=John
|
||||
|
||||
# Submitting forms:
|
||||
http -f POST example.org hello=World
|
||||
|
||||
# See the request that is being sent using one of the output options:
|
||||
http -v example.org
|
||||
|
||||
# Use Github API to post a comment on an issue with authentication:
|
||||
http -a USERNAME POST https://api.github.com/repos/jkbrzt/httpie/issues/83/comments body='HTTPie is awesome!'
|
||||
|
||||
# Upload a file using redirected input:
|
||||
http example.org < file.json
|
||||
|
||||
# Download a file and save it via redirected output:
|
||||
http example.org/file > file
|
||||
|
||||
# Download a file wget style:
|
||||
http --download example.org/file
|
||||
|
||||
# Use named sessions_ to make certain aspects or the communication
|
||||
# persistent between requests to the same host:
|
||||
# http --session=logged-in -a username:password httpbin.org/get API-Key:123
|
||||
http --session=logged-in httpbin.org/headers
|
||||
|
||||
# Set a custom Host header to work around missing DNS records:
|
||||
http localhost:8000 Host:example.com
|
||||
|
||||
# Simple JSON example:
|
||||
http PUT example.org name=John email=john@example.org
|
||||
|
||||
# Non-string fields use the := separator, which allows you to embed raw
|
||||
# JSON into the resulting object. Text and raw JSON files can also be
|
||||
# embedded into fields using =@ and :=@:
|
||||
http PUT api.example.com/person/1 name=John age:=29 married:=false hobbies:='["http", "pies"]' description=@about-john.txt bookmarks:=@bookmarks.json
|
||||
|
||||
# Send JSON data stored in a file:
|
||||
http POST api.example.com/person/1 < person.json
|
||||
|
||||
# Regular Forms
|
||||
http --form POST api.example.org/person/1 name='John Smith' email=john@example.org cv=@~/Documents/cv.txt
|
||||
|
||||
# File Upload Forms
|
||||
# If one or more file fields is present, the serialization and content
|
||||
# type is multipart/form-data:
|
||||
http -f POST example.com/jobs name='John Smith' cv@~/Documents/cv.pdf
|
||||
|
||||
# To set custom headers you can use the Header:Value notation:
|
||||
http example.org User-Agent:Bacon/1.0 'Cookie:valued-visitor=yes;foo=bar' X-Foo:Bar Referer:http://httpie.org/
|
||||
|
||||
# Basic auth:
|
||||
http -a username:password example.org
|
||||
|
||||
# Digest auth:
|
||||
http --auth-type=digest -a username:password example.org
|
||||
|
||||
# With password prompt:
|
||||
http -a username example.org
|
||||
|
||||
# Authorization information from your ~/.netrc file is honored as well:
|
||||
cat ~/.netrc
|
||||
machine httpbin.org
|
||||
login httpie
|
||||
# password test
|
||||
http httpbin.org/basic-auth/httpie/test
|
||||
|
||||
# You can specify proxies to be used through the --proxy argument for each
|
||||
# protocol (which is included in the value in case of redirects across
|
||||
# protocols):
|
||||
http --proxy=http:http://10.10.1.10:3128 --proxy=https:https://10.10.1.10:1080 example.org
|
||||
|
||||
# With Basic authentication:
|
||||
http --proxy=http:http://user:pass@10.10.1.10:3128 example.org
|
||||
|
||||
# To skip the HOST'S SSL CERTIFICATE VERIFICATION, you can pass
|
||||
# --verify=no (default is yes):
|
||||
http --verify=no https://example.org
|
||||
|
||||
# You can also use --verify=<CA_BUNDLE_PATH> to set a CUSTOM CA BUNDLE path:
|
||||
http --verify=/ssl/custom_ca_bundle https://example.org
|
||||
|
||||
# To use a CLIENT SIDE CERTIFICATE for the SSL communication, you can pass
|
||||
# the path of the cert file with --cert:
|
||||
http --cert=client.pem https://example.org
|
||||
|
||||
# If the PRIVATE KEY is not contained in the cert file you may pass the
|
||||
# path of the key file with --cert-key:
|
||||
http --cert=client.crt --cert-key=client.key https://example.org
|
||||
|
||||
# You can control what should be printed via several options:
|
||||
# --headers, -h Only the response headers are printed.
|
||||
# --body, -b Only the response body is printed.
|
||||
# --verbose, -v Print the whole HTTP exchange (request and response).
|
||||
# --print, -p Selects parts of the HTTP exchange.
|
||||
http --verbose PUT httpbin.org/put hello=world
|
||||
|
||||
# Print request and response headers:
|
||||
# Character Stands for
|
||||
# ----------- -------------------
|
||||
# H Request headers.
|
||||
# B Request body.
|
||||
# h Response headers.
|
||||
# b Response body.
|
||||
http --print=Hh PUT httpbin.org/put hello=world
|
||||
|
||||
# Let's say that there is an API that returns the whole resource when it
|
||||
# is updated, but you are only interested in the response headers to see
|
||||
# the status code after an update:
|
||||
http --headers PATCH example.org/Really-Huge-Resource name='New Name'
|
||||
|
||||
# Redirect from a file:
|
||||
http PUT example.com/person/1 X-API-Token:123 < person.json
|
||||
|
||||
# Or the output of another program:
|
||||
grep '401 Unauthorized' /var/log/httpd/error_log | http POST example.org/intruders
|
||||
|
||||
# You can use echo for simple data:
|
||||
echo '{"name": "John"}' | http PATCH example.com/person/1 X-API-Token:123
|
||||
|
||||
# You can even pipe web services together using HTTPie:
|
||||
http GET https://api.github.com/repos/jkbrzt/httpie | http POST httpbin.org/post
|
||||
|
||||
# You can use cat to enter multiline data on the terminal:
|
||||
cat | http POST example.com
|
||||
<paste>
|
||||
# ^D
|
||||
cat | http POST example.com/todos Content-Type:text/plain
|
||||
- buy milk
|
||||
- call parents
|
||||
^D
|
||||
|
||||
# On OS X, you can send the contents of the clipboard with pbpaste:
|
||||
pbpaste | http PUT example.com
|
||||
|
||||
# Passing data through stdin cannot be combined with data fields specified
|
||||
# on the command line:
|
||||
echo 'data' | http POST example.org more=data # This is invalid
|
||||
|
||||
|
||||
# AN ALTERNATIVE TO REDIRECTED stdin is specifying a filename (as
|
||||
# @/path/to/file) whose content is used as if it came from stdin.
|
||||
|
||||
# It has the advantage that THE Content-Type HEADER IS AUTOMATICALLY SET
|
||||
# to the appropriate value based on the filename extension. For example,
|
||||
# the following request sends the verbatim contents of that XML file with
|
||||
# Content-Type: application/xml:
|
||||
http PUT httpbin.org/put @/data/file.xml
|
||||
|
||||
# Download a file:
|
||||
http example.org/Movie.mov > Movie.mov
|
||||
|
||||
# Download an image of Octocat, resize it using ImageMagick, upload it
|
||||
# elsewhere:
|
||||
http octodex.github.com/images/original.jpg | convert - -resize 25% - | http example.org/Octocats
|
||||
|
||||
# Force colorizing and formatting, and show both the request and the
|
||||
# response in less pager:
|
||||
http --pretty=all --verbose example.org | less -R
|
||||
|
||||
# When enabled using the --download, -d flag, response headers are printed
|
||||
# to the terminal (stderr), and a progress bar is shown while the response
|
||||
# body is being saved to a file.
|
||||
http --download https://github.com/jkbrzt/httpie/tarball/master
|
||||
|
||||
# You can also redirect the response body to another program while the
|
||||
# response headers and progress are still shown in the terminal:
|
||||
http -d https://github.com/jkbrzt/httpie/tarball/master | tar zxf -
|
||||
|
||||
# If --output, -o is specified, you can resume a partial download using
|
||||
# the --continue, -c option. This only works with servers that support
|
||||
# Range requests and 206 Partial Content responses. If the server doesn't
|
||||
# support that, the whole file will simply be downloaded:
|
||||
http -dco file.zip example.org/file
|
||||
|
||||
# Prettified streamed response:
|
||||
http --stream -f -a YOUR-TWITTER-NAME https://stream.twitter.com/1/statuses/filter.json track='Justin Bieber'
|
||||
|
||||
# Send each new tweet (JSON object) mentioning "Apple" to another
|
||||
# server as soon as it arrives from the Twitter streaming API:
|
||||
http --stream -f -a YOUR-TWITTER-NAME https://stream.twitter.com/1/statuses/filter.json track=Apple | while read tweet; do echo "$tweet" | http POST example.org/tweets ; done
|
||||
|
||||
# Create a new session named user1 for example.org:
|
||||
http --session=user1 -a user1:password example.org X-Foo:Bar
|
||||
|
||||
# Now you can refer to the session by its name, and the previously used
|
||||
# authorization and HTTP headers will automatically be set:
|
||||
http --session=user1 example.org
|
||||
|
||||
# To create or reuse a different session, simple specify a different name:
|
||||
http --session=user2 -a user2:password example.org X-Bar:Foo
|
||||
|
||||
# Instead of a name, you can also directly specify a path to a session
|
||||
# file. This allows for sessions to be re-used across multiple hosts:
|
||||
http --session=/tmp/session.json example.orghttp --session=/tmp/session.json admin.example.orghttp --session=~/.httpie/sessions/another.example.org/test.json example.orghttp --session-read-only=/tmp/session.json example.org
|
@ -1,74 +0,0 @@
|
||||
As a contributor to open-source
|
||||
-------------------------------
|
||||
|
||||
# clone your own project
|
||||
$ git clone dotfiles
|
||||
→ git clone git://github.com/YOUR_USER/dotfiles.git
|
||||
|
||||
# clone another project
|
||||
$ git clone github/hub
|
||||
→ git clone git://github.com/github/hub.git
|
||||
|
||||
# see the current project's issues
|
||||
$ git browse -- issues
|
||||
→ open https://github.com/github/hub/issues
|
||||
|
||||
# open another project's wiki
|
||||
$ git browse mojombo/jekyll wiki
|
||||
→ open https://github.com/mojombo/jekyll/wiki
|
||||
|
||||
## Example workflow for contributing to a project:
|
||||
$ git clone github/hub
|
||||
$ cd hub
|
||||
# create a topic branch
|
||||
$ git checkout -b feature
|
||||
→ ( making changes ... )
|
||||
$ git commit -m "done with feature"
|
||||
# It's time to fork the repo!
|
||||
$ git fork
|
||||
→ (forking repo on GitHub...)
|
||||
→ git remote add YOUR_USER git://github.com/YOUR_USER/hub.git
|
||||
# push the changes to your new remote
|
||||
$ git push YOUR_USER feature
|
||||
# open a pull request for the topic branch you've just pushed
|
||||
$ git pull-request
|
||||
→ (opens a text editor for your pull request message)
|
||||
|
||||
|
||||
As an open-source maintainer
|
||||
----------------------------
|
||||
|
||||
# fetch from multiple trusted forks, even if they don't yet exist as remotes
|
||||
$ git fetch mislav,cehoffman
|
||||
→ git remote add mislav git://github.com/mislav/hub.git
|
||||
→ git remote add cehoffman git://github.com/cehoffman/hub.git
|
||||
→ git fetch --multiple mislav cehoffman
|
||||
|
||||
# check out a pull request for review
|
||||
$ git checkout https://github.com/github/hub/pull/134
|
||||
→ (creates a new branch with the contents of the pull request)
|
||||
|
||||
# directly apply all commits from a pull request to the current branch
|
||||
$ git am -3 https://github.com/github/hub/pull/134
|
||||
|
||||
# cherry-pick a GitHub URL
|
||||
$ git cherry-pick https://github.com/xoebus/hub/commit/177eeb8
|
||||
→ git remote add xoebus git://github.com/xoebus/hub.git
|
||||
→ git fetch xoebus
|
||||
→ git cherry-pick 177eeb8
|
||||
|
||||
# `am` can be better than cherry-pick since it doesn't create a remote
|
||||
$ git am https://github.com/xoebus/hub/commit/177eeb8
|
||||
|
||||
# open the GitHub compare view between two releases
|
||||
$ git compare v0.9..v1.0
|
||||
|
||||
# put compare URL for a topic branch to clipboard
|
||||
$ git compare -u feature | pbcopy
|
||||
|
||||
# create a repo for a new project
|
||||
$ git init
|
||||
$ git add . && git commit -m "It begins."
|
||||
$ git create -d "My new thing"
|
||||
→ (creates a new project on GitHub with the name of current directory)
|
||||
$ git push origin master
|
@ -1,3 +0,0 @@
|
||||
# To convert file (iconv.src) from iso-8859-1 to utf-8 and save to
|
||||
# /tmp/iconv.out
|
||||
iconv -f iso-8859-1 -t utf-8 iconv.src -o /tmp/iconv.out
|
@ -1,14 +0,0 @@
|
||||
# Display network settings of the first ethernet adapter
|
||||
ifconfig wlan0
|
||||
|
||||
# Display all interfaces, even if down
|
||||
ifconfig -a
|
||||
|
||||
# Take down / up the wireless adapter
|
||||
ifconfig wlan0 {up|down}
|
||||
|
||||
# Set a static IP and netmask
|
||||
ifconfig eth0 192.168.1.100 netmask 255.255.255.0
|
||||
|
||||
# You may also need to add a gateway IP
|
||||
route add -net 192.168.1.0 netmask 255.255.255.0 gw 192.168.1.1
|
@ -1,2 +0,0 @@
|
||||
# format C/C++ source according to the style of Kernighan and Ritchie (K&R), no tabs, 3 spaces per indent, wrap lines at 120 characters.
|
||||
indent -i3 -kr -nut -l120
|
@ -1,32 +0,0 @@
|
||||
# Display all interfaces with addresses
|
||||
ip addr
|
||||
|
||||
# Take down / up the wireless adapter
|
||||
ip link set dev wlan0 {up|down}
|
||||
|
||||
# Set a static IP and netmask
|
||||
ip addr add 192.168.1.100/32 dev eth0
|
||||
|
||||
# Remove a IP from an interface
|
||||
ip addr del 192.168.1.100/32 dev eth0
|
||||
|
||||
# Remove all IPs from an interface
|
||||
ip address flush dev eth0
|
||||
|
||||
# Display all routes
|
||||
ip route
|
||||
|
||||
# Display all routes for IPv6
|
||||
ip -6 route
|
||||
|
||||
# Add default route via gateway IP
|
||||
ip route add default via 192.168.1.1
|
||||
|
||||
# Add route via interface
|
||||
ip route add 192.168.0.0/24 dev eth0
|
||||
|
||||
# Change your mac address
|
||||
ip link set dev eth0 address aa:bb:cc:dd:ee:ff
|
||||
|
||||
# View neighbors (using ARP and NDP)
|
||||
ip neighbor show
|
@ -1,40 +0,0 @@
|
||||
# Show hit for rules with auto refresh
|
||||
watch --interval 0 'iptables -nvL | grep -v "0 0"'
|
||||
|
||||
# Show hit for rule with auto refresh and highlight any changes since the last refresh
|
||||
watch -d -n 2 iptables -nvL
|
||||
|
||||
# Block the port 902 and we hide this port from nmap.
|
||||
iptables -A INPUT -i eth0 -p tcp --dport 902 -j REJECT --reject-with icmp-port-unreachable
|
||||
|
||||
# Note, --reject-with accept:
|
||||
# icmp-net-unreachable
|
||||
# icmp-host-unreachable
|
||||
# icmp-port-unreachable <- Hide a port to nmap
|
||||
# icmp-proto-unreachable
|
||||
# icmp-net-prohibited
|
||||
# icmp-host-prohibited or
|
||||
# icmp-admin-prohibited
|
||||
# tcp-reset
|
||||
|
||||
# Add a comment to a rule:
|
||||
iptables ... -m comment --comment "This rule is here for this reason"
|
||||
|
||||
|
||||
# To remove or insert a rule:
|
||||
# 1) Show all rules
|
||||
iptables -L INPUT --line-numbers
|
||||
# OR iptables -nL --line-numbers
|
||||
|
||||
# Chain INPUT (policy ACCEPT)
|
||||
# num target prot opt source destination
|
||||
# 1 ACCEPT udp -- anywhere anywhere udp dpt:domain
|
||||
# 2 ACCEPT tcp -- anywhere anywhere tcp dpt:domain
|
||||
# 3 ACCEPT udp -- anywhere anywhere udp dpt:bootps
|
||||
# 4 ACCEPT tcp -- anywhere anywhere tcp dpt:bootps
|
||||
|
||||
# 2.a) REMOVE (-D) a rule. (here an INPUT rule)
|
||||
iptables -D INPUT 2
|
||||
|
||||
# 2.b) OR INSERT a rule.
|
||||
iptables -I INPUT {LINE_NUMBER} -i eth1 -p tcp --dport 21 -s 123.123.123.123 -j ACCEPT -m comment --comment "This rule is here for this reason"
|
@ -1,33 +0,0 @@
|
||||
# To connect to an IRC server
|
||||
/connect <server domain name>
|
||||
|
||||
# To join a channel
|
||||
/join #<channel name>
|
||||
|
||||
# To set a nickname
|
||||
/nick <my nickname>
|
||||
|
||||
# To send a private message to a user
|
||||
/msg <nickname>
|
||||
|
||||
# To close the current channel window
|
||||
/wc
|
||||
|
||||
# To switch between channel windows
|
||||
ALT+<number>, eg. ALT+1, ALT+2
|
||||
|
||||
# To list the nicknames within the active channel
|
||||
/names
|
||||
|
||||
# To change the channel topic
|
||||
/topic <description>
|
||||
|
||||
# To limit channel background noise (joins, parts, quits, etc.)
|
||||
/ignore #foo,#bar JOINS PARTS QUITS NICKS # Quieten only channels `#foo`, `#bar`
|
||||
/ignore * JOINS PARTS QUITS NICKS # Quieten all channels
|
||||
|
||||
# To save the current Irssi session config into the configuration file
|
||||
/save
|
||||
|
||||
# To quit Irssi
|
||||
/exit
|
@ -1,8 +0,0 @@
|
||||
# Display wireless settings of the first wireless adapter
|
||||
iwconfig wlan0
|
||||
|
||||
# Take down / up the wireless adapter
|
||||
iwconfig wlan0 txpower {on|auto|off}
|
||||
|
||||
# Change the mode of the wireless adapter
|
||||
iwconfig wlan0 mode {managed|ad-hoc|monitor}
|
@ -1,32 +0,0 @@
|
||||
# Actively follow log (like tail -f)
|
||||
journalctl -f
|
||||
|
||||
# Display all errors since last boot
|
||||
journalctl -b -p err
|
||||
|
||||
# Filter by time period
|
||||
journalctl --since=2012-10-15 --until="2011-10-16 23:59:59"
|
||||
|
||||
# Show list of systemd units logged in journal
|
||||
journalctl -F _SYSTEMD_UNIT
|
||||
|
||||
# Filter by specific unit
|
||||
journalctl -u dbus
|
||||
|
||||
# Filter by executable name
|
||||
journalctl /usr/bin/dbus-daemon
|
||||
|
||||
# Filter by PID
|
||||
journalctl _PID=123
|
||||
|
||||
# Filter by Command, e.g., sshd
|
||||
journalctl _COMM=sshd
|
||||
|
||||
# Filter by Command and time period
|
||||
journalctl _COMM=crond --since '10:00' --until '11:00'
|
||||
|
||||
# List all available boots
|
||||
journalctl --list-boots
|
||||
|
||||
# Filter by specific User ID e.g., user id 1000
|
||||
journalctl _UID=1000
|
@ -1,13 +0,0 @@
|
||||
# Pretty print the json
|
||||
jq "." < filename.json
|
||||
|
||||
# Access the value at key "foo"
|
||||
jq '.foo'
|
||||
|
||||
# Access first list item
|
||||
jq '.[0]'
|
||||
|
||||
# Slice & Dice
|
||||
jq '.[2:4]'
|
||||
jq '.[:3]'
|
||||
jq '.[-2:]'
|
@ -1,25 +0,0 @@
|
||||
# Add entry to default jrnl (from your configured text editor)
|
||||
jrnl
|
||||
|
||||
# Add entry to default jrnl
|
||||
jrnl Write entry here.
|
||||
|
||||
# List of tags
|
||||
jrnl --tags
|
||||
|
||||
# Entries per tag
|
||||
jrnl @tag
|
||||
|
||||
# Export jrnl as json
|
||||
jrnl --export json
|
||||
|
||||
# Entries in a timeframe
|
||||
jrnl -from 2009 -until may
|
||||
|
||||
# Add Sublime text to .jrnl_config
|
||||
|
||||
# Windows
|
||||
"editor": "F:\\Powerpack\\Sublime\\sublime_text.exe -w"
|
||||
|
||||
# Linux
|
||||
"editor": "/usr/bin/sublime -w"
|
@ -1,5 +0,0 @@
|
||||
# Kill a process gracefully
|
||||
kill -15 <process id>
|
||||
|
||||
# Kill a process forcefully
|
||||
kill -9 <process id>
|
@ -1,9 +0,0 @@
|
||||
# To disable the terminal refresh when exiting
|
||||
less -X
|
||||
|
||||
# To save the contents to a file
|
||||
# Method 1 - Only works when the input is a pipe
|
||||
s <filename>
|
||||
|
||||
# Method 2 - This should work whether input is a pipe or an ordinary file.
|
||||
Type g or < (g or less-than) | $ (pipe then dollar) then cat > <filename> and Enter.
|
@ -1,23 +0,0 @@
|
||||
# Display available libraries
|
||||
ldconfig -p
|
||||
|
||||
# Update library resources
|
||||
ldconfig
|
||||
|
||||
# Display libraries and file location
|
||||
ldd
|
||||
|
||||
# Libraries available to apps in real-time
|
||||
"Dynamic Libraries" (.so.)
|
||||
|
||||
# Libraries only available to apps when installed (imported)
|
||||
"Static Libraries" (.a.)
|
||||
|
||||
# Standard (usual) library file location
|
||||
/lib
|
||||
|
||||
# Sofware-accessible source for library info
|
||||
/etc/ld.so.cache # (binary)
|
||||
|
||||
# Human-readable source for library info
|
||||
/etc/ld.so.conf # (points to /etc/ld.so.conf.d)
|
@ -1,5 +0,0 @@
|
||||
# To create a symlink:
|
||||
ln -s path/to/the/target/directory name-of-symlink
|
||||
|
||||
# Symlink, while overwriting existing destination files
|
||||
ln -sf /some/dir/exec /usr/bin/exec
|
@ -1,17 +0,0 @@
|
||||
# Displays everything in the target directory
|
||||
ls path/to/the/target/directory
|
||||
|
||||
# Displays everything including hidden files
|
||||
ls -a
|
||||
|
||||
# Displays all files, along with the size (with unit suffixes) and timestamp
|
||||
ls -lh
|
||||
|
||||
# Display files, sorted by size
|
||||
ls -S
|
||||
|
||||
# Display directories only
|
||||
ls -d */
|
||||
|
||||
# Display directories only, include hidden
|
||||
ls -d .*/ */
|
@ -1,21 +0,0 @@
|
||||
# Show all available block devices along with their partitioning schemes
|
||||
lsblk
|
||||
|
||||
# To show SCSI devices:
|
||||
lsblk --scsi
|
||||
|
||||
# To show a specific device
|
||||
lsblk /dev/sda
|
||||
|
||||
# To verify TRIM support:
|
||||
# Check the values of DISC-GRAN (discard granularity) and DISC-MAX (discard max bytes) columns.
|
||||
# Non-zero values indicate TRIM support
|
||||
lsblk --discard
|
||||
|
||||
# To featch info about filesystems:
|
||||
lsblk --fs
|
||||
|
||||
# For JSON, LIST or TREE output formats use the following flags:
|
||||
lsblk --json
|
||||
lsblk --list
|
||||
lsblk --tree # default view
|
@ -1,37 +0,0 @@
|
||||
# List all IPv4 network files
|
||||
sudo lsof -i4
|
||||
|
||||
# List all IPv6 network files
|
||||
sudo lsof -i6
|
||||
|
||||
# List all open sockets
|
||||
lsof -i
|
||||
|
||||
# List all listening ports
|
||||
lsof -Pnl +M -i4
|
||||
|
||||
# Find which program is using the port 80
|
||||
lsof -i TCP:80
|
||||
|
||||
# List all connections to a specific host
|
||||
lsof -i@192.168.1.5
|
||||
|
||||
# List all processes accessing a particular file/directory
|
||||
lsof </path/to/file>
|
||||
|
||||
# List all files open for a particular user
|
||||
lsof -u <username>
|
||||
|
||||
# List all files/network connections a command is using
|
||||
lsof -c <command-name>
|
||||
|
||||
# List all files a process has open
|
||||
lsof -p <pid>
|
||||
|
||||
# List all files open mounted at /mount/point.
|
||||
# Particularly useful for finding which process(es) are using a
|
||||
# mounted USB stick or CD/DVD.
|
||||
lsof +f -- </mount/point>
|
||||
|
||||
# See this primer: http://www.danielmiessler.com/study/lsof/
|
||||
# for a number of other useful lsof tips
|
@ -1,7 +0,0 @@
|
||||
#Exclusive Activation of a Volume Group in a Cluster
|
||||
#Link --> https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/High_Availability_Add-On_Administration/s1-exclusiveactive-HAAA.html
|
||||
1> vgs --noheadings -o vg_name
|
||||
2> volume_list = [ "rhel_root", "rhel_home" ]
|
||||
3> dracut -H -f /boot/initramfs-$(uname -r).img $(uname -r)
|
||||
4> Reboot the node
|
||||
5> uname -r to verify the correct initrd image
|
@ -1,5 +0,0 @@
|
||||
# Convert a man page to pdf
|
||||
man -t bash | ps2pdf - bash.pdf
|
||||
|
||||
# View the ascii chart
|
||||
man 7 ascii
|
@ -1,44 +0,0 @@
|
||||
# headers
|
||||
h1 header
|
||||
=========
|
||||
h2 header
|
||||
---------
|
||||
|
||||
# blockquotes
|
||||
> first level and paragraph
|
||||
>> second level and first paragraph
|
||||
>
|
||||
> first level and second paragraph
|
||||
|
||||
# lists
|
||||
## unordered - use *, +, or -
|
||||
* Red
|
||||
* Green
|
||||
* Blue
|
||||
|
||||
## ordered
|
||||
1. First
|
||||
2. Second
|
||||
3. Third
|
||||
|
||||
# code - use 4 spaces/1 tab
|
||||
regular text
|
||||
code code code
|
||||
or:
|
||||
Use the `printf()` function
|
||||
|
||||
# hr's - three or more of the following
|
||||
***
|
||||
---
|
||||
___
|
||||
|
||||
# links
|
||||
This is [an example](http://example.com "Title") inline link.
|
||||
|
||||
# image
|
||||
![Alt Text](/path/to/file.png)
|
||||
|
||||
# formatting
|
||||
*em* _em_
|
||||
**strong** __strong__
|
||||
~~strikethrough~~
|
@ -1,58 +0,0 @@
|
||||
# For the sake of briefness, we use Bash "group compound" stanza:
|
||||
# /dev/sd{a,b,...}1 => /dev/sda1 /dev/sdb1 ...
|
||||
# Along the following variables:
|
||||
# ${M} array identifier (/dev/md${M})
|
||||
# ${D} device identifier (/dev/sd${D})
|
||||
# ${P} partition identifier (/dev/sd${D}${P})
|
||||
|
||||
# Create (initialize) a new array
|
||||
mdadm --create /dev/md${M} --level=raid5 --raid-devices=4 /dev/sd{a,b,c,d,e}${P} --spare-devices=/dev/sdf1
|
||||
|
||||
# Manually assemble (activate) an existing array
|
||||
mdadm --assemble /dev/md${M} /dev/sd{a,b,c,d,e}${P}
|
||||
|
||||
# Automatically assemble (activate) all existing arrays
|
||||
mdadm --assemble --scan
|
||||
|
||||
# Stop an assembled (active) array
|
||||
mdadm --stop /dev/md${M}
|
||||
|
||||
# See array configuration
|
||||
mdadm --query /dev/md${M}
|
||||
|
||||
# See array component configuration (dump superblock content)
|
||||
mdadm --query --examine /dev/sd${D}${P}
|
||||
|
||||
# See detailed array confiration/status
|
||||
mdadm --detail /dev/md${M}
|
||||
|
||||
# Save existing arrays configuration
|
||||
# (MAY be required by initrd for successfull boot)
|
||||
mdadm --detail --scan > /etc/mdadm/mdadm.conf
|
||||
|
||||
# Erase array component superblock
|
||||
# (MUST do before reusing a partition for other purposes)
|
||||
mdadm --zero-superblock /dev/sd${D}${P}
|
||||
|
||||
# Manually mark a component as failed
|
||||
# (SHOULD when a device shows wear-and-tear signs, e.g. through SMART)
|
||||
mdadm --manage /dev/md${M} --fail /dev/sd${D}${P}
|
||||
|
||||
# Remove a failed component
|
||||
# (SHOULD before preemptively replacing a device, after failing it)
|
||||
mdadm --manage /dev/md${M} --remove /dev/sd${D}${P}
|
||||
|
||||
# Prepare (format) a new device to replace a failed one
|
||||
sfdisk -d /dev/sd${D,sane} | sfdisk /dev/sd${D,new}
|
||||
|
||||
# Add new component to an existing array
|
||||
# (this will trigger the rebuild)
|
||||
mdadm --manage /dev/md${M} --add /dev/sd${D,new}${P}
|
||||
|
||||
# See assembled (active) arrays status
|
||||
cat /proc/mdstat
|
||||
|
||||
# Rename a device
|
||||
# (SHOULD after hostname change; eg. name="$(hostname -s)")
|
||||
mdadm --assemble /dev/md${M} /dev/sd{a,b,c,d,e}${P} --name="${name}:${M}" --update=name
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user