├── .nojekyll ├── .gitattributes ├── html ├── fonts │ ├── glyphicons-halflings-regular.eot │ ├── glyphicons-halflings-regular.ttf │ ├── glyphicons-halflings-regular.woff │ └── glyphicons-halflings-regular.woff2 ├── styles │ ├── github-gist.css │ ├── default.css │ ├── github.css │ └── grayscale.css ├── css │ └── cheatsheet.css ├── marked.min.js └── bootstrap.min.js ├── sheets ├── config.js ├── love2d.md ├── typescript.md ├── git.md ├── eg.md ├── cmake.md ├── swift.md ├── glsl.md ├── bash.md ├── textmate.md └── moonscript.md ├── .editorconfig ├── readme.md ├── index.html └── LICENSE /.nojekyll: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | 2 | * text=auto 3 | *.md text 4 | *.html text 5 | -------------------------------------------------------------------------------- /html/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/billyquith/cheatsheet/HEAD/html/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /html/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/billyquith/cheatsheet/HEAD/html/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /html/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/billyquith/cheatsheet/HEAD/html/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /html/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/billyquith/cheatsheet/HEAD/html/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /sheets/config.js: -------------------------------------------------------------------------------- 1 | // List of the sheets available 2 | var sheets = ['bash','cmake', 'git', 'glsl', 'moonscript','swift', 'textmate', 'typescript']; 3 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | root = true 3 | 4 | [*.{js,py}] 5 | charset = utf-8 6 | 7 | [sheets/*.md] 8 | indent_style = space 9 | indent_size = 2 10 | 11 | [*.html] 12 | indent_style = space 13 | indent_size = 2 14 | 15 | 16 | -------------------------------------------------------------------------------- /sheets/love2d.md: -------------------------------------------------------------------------------- 1 | 2 | Love2d 3 | ====== 4 | 5 | Start Up 6 | -------- 7 | 8 | **These notes are for Love2d 0.9.** 9 | 10 | Love provides default callback placeholders: 11 | 12 | ```lua 13 | debug = true -- turn on debug info 14 | 15 | function love.load() -- called before first update 16 | end 17 | 18 | function love.update(dt) -- frame update, with time delta, before draw 19 | end 20 | 21 | function love.draw() -- frame draw 22 | end 23 | ``` 24 | 25 | Graphics 26 | -------- 27 | 28 | `VERTS` is: 29 | - a list of vertex pairs, `x1, y1, x2, y2, ...`, e.g. `100, 100, 200, 100, 150, 200` 30 | - a table reference, where table is a list of vertex pairs, eg. `{100, 100, 200, 100, 150, 200}` 31 | 32 | #### Polygon 33 | 34 | ```lua 35 | love.graphics.polygon( "line", VERTS ) -- outlined polygon 36 | love.graphics.polygon( "fill", VERTS ) -- filled convex polygon 37 | ``` 38 | 39 | #### Polyline 40 | 41 | ```lua 42 | love.graphics.line( VERTS ) 43 | 44 | love.graphics.setLineWidth( WIDTH ) 45 | love.graphics.setLineStyle( STYLE ) -- [ "rough" | "smooth" ] 46 | ``` 47 | 48 | 49 | -------------------------------------------------------------------------------- /html/styles/github-gist.css: -------------------------------------------------------------------------------- 1 | /** 2 | * GitHub Gist Theme 3 | * Author : Louis Barranqueiro - https://github.com/LouisBarranqueiro 4 | */ 5 | 6 | .hljs { 7 | display: block; 8 | background: white; 9 | padding: 0.5em; 10 | color: #333333; 11 | overflow-x: auto; 12 | } 13 | 14 | .hljs-comment, 15 | .hljs-meta { 16 | color: #969896; 17 | } 18 | 19 | .hljs-string, 20 | .hljs-variable, 21 | .hljs-template-variable, 22 | .hljs-strong, 23 | .hljs-emphasis, 24 | .hljs-quote { 25 | color: #df5000; 26 | } 27 | 28 | .hljs-keyword, 29 | .hljs-selector-tag, 30 | .hljs-type { 31 | color: #a71d5d; 32 | } 33 | 34 | .hljs-literal, 35 | .hljs-symbol, 36 | .hljs-bullet, 37 | .hljs-attribute { 38 | color: #0086b3; 39 | } 40 | 41 | .hljs-section, 42 | .hljs-name { 43 | color: #63a35c; 44 | } 45 | 46 | .hljs-tag { 47 | color: #333333; 48 | } 49 | 50 | .hljs-title, 51 | .hljs-attr, 52 | .hljs-selector-id, 53 | .hljs-selector-class, 54 | .hljs-selector-attr, 55 | .hljs-selector-pseudo { 56 | color: #795da3; 57 | } 58 | 59 | .hljs-addition { 60 | color: #55a532; 61 | background-color: #eaffea; 62 | } 63 | 64 | .hljs-deletion { 65 | color: #bd2c00; 66 | background-color: #ffecec; 67 | } 68 | 69 | .hljs-link { 70 | text-decoration: underline; 71 | } 72 | -------------------------------------------------------------------------------- /html/styles/default.css: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Original highlight.js style (c) Ivan Sagalaev 4 | 5 | */ 6 | 7 | .hljs { 8 | display: block; 9 | overflow-x: auto; 10 | padding: 0.5em; 11 | background: #F0F0F0; 12 | } 13 | 14 | .hljs, 15 | .hljs-subst { 16 | color: #444; 17 | } 18 | 19 | .hljs-keyword, 20 | .hljs-attribute, 21 | .hljs-selector-tag, 22 | .hljs-meta-keyword, 23 | .hljs-doctag, 24 | .hljs-name { 25 | font-weight: bold; 26 | } 27 | 28 | .hljs-built_in, 29 | .hljs-bullet, 30 | .hljs-code, 31 | .hljs-addition { 32 | color: #2C6F2C; 33 | } 34 | 35 | .hljs-literal { 36 | color: #4D974D; 37 | } 38 | 39 | .hljs-regexp, 40 | .hljs-symbol, 41 | .hljs-variable, 42 | .hljs-template-variable, 43 | .hljs-link, 44 | .hljs-selector-attr, 45 | .hljs-selector-pseudo { 46 | color: #BC6060; 47 | } 48 | 49 | .hljs-type, 50 | .hljs-string, 51 | .hljs-number, 52 | .hljs-selector-id, 53 | .hljs-selector-class, 54 | .hljs-quote, 55 | .hljs-template-tag, 56 | .hljs-deletion { 57 | color: #880000; 58 | } 59 | 60 | .hljs-title, 61 | .hljs-section { 62 | color: #880000; 63 | font-weight: bold; 64 | } 65 | 66 | .hljs-comment { 67 | color: #888888; 68 | } 69 | 70 | .hljs-meta { 71 | color: #2B6EA1; 72 | } 73 | 74 | .hljs-meta-string { 75 | color: #6CA8D6; 76 | } 77 | 78 | .hljs-emphasis { 79 | font-style: italic; 80 | } 81 | 82 | .hljs-strong { 83 | font-weight: bold; 84 | } 85 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | 2 | Cheatsheet 3 | ========== 4 | 5 | ### Summary 6 | 7 | This is a simple tool for displaying summarised information as cheatsheets. The sheets are 8 | formatted using [Markdown][1], like you are reading now. Once parsed they are are then transformed 9 | into browsable webpages. 10 | 11 | ### Usage 12 | 13 | To use just git clone this repository somewhere and open the `html/index.html` file. 14 | To open a specific sheet use URL: 15 | 16 | file:///PATH_TO_CHEATSHEET/index.html?sheet=SHEETNAME 17 | 18 | To add new sheets, create a new file `sheets/SHEETNAME.md`. 19 | 20 | ### Formatting 21 | 22 | Formatting is [standard Markdown][mdcheat]: 23 | 24 | - H2 headers become section names. 25 | - Tables are allowed. 26 | - Value-comment lists are a markup extension. 27 | - Pop-up examples. 28 | 29 | See the "eg" [example sheet][eg] and its source for more examples. 30 | 31 | ### Useful links 32 | 33 | - [Project homepage](https://github.com/billyquith/cheatsheet) 34 | - [Markdown](http://daringfireball.net/projects/markdown/) 35 | - [Markdown cheatsheet][mdcheat] 36 | 37 | ### Licence 38 | 39 | The project is a standalone tool and so is licensed under GPL. 40 | 41 | [GPLv3][GPL] - GNU GENERAL PUBLIC LICENSE]. Version 3, 29 June 2007. 42 | 43 | 44 | [1]: https://en.wikipedia.org/wiki/Markdown 45 | [2]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#tables 46 | [eg]: https://billyquith.github.io/cheatsheet/?sheet=eg 47 | [mdcheat]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet 48 | [GPL]: https://www.gnu.org/licenses/gpl-3.0.en.html 49 | -------------------------------------------------------------------------------- /html/styles/github.css: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | github.com style (c) Vasily Polovnyov 4 | 5 | */ 6 | 7 | .hljs { 8 | display: block; 9 | overflow-x: auto; 10 | padding: 0.5em; 11 | color: #333; 12 | background: #f8f8f8; 13 | } 14 | 15 | .hljs-comment, 16 | .hljs-quote { 17 | color: #998; 18 | font-style: italic; 19 | } 20 | 21 | .hljs-keyword, 22 | .hljs-selector-tag, 23 | .hljs-subst { 24 | color: #333; 25 | font-weight: bold; 26 | } 27 | 28 | .hljs-number, 29 | .hljs-literal, 30 | .hljs-variable, 31 | .hljs-template-variable, 32 | .hljs-tag .hljs-attr { 33 | color: #008080; 34 | } 35 | 36 | .hljs-string, 37 | .hljs-doctag { 38 | color: #d14; 39 | } 40 | 41 | .hljs-title, 42 | .hljs-section, 43 | .hljs-selector-id { 44 | color: #900; 45 | font-weight: bold; 46 | } 47 | 48 | .hljs-subst { 49 | font-weight: normal; 50 | } 51 | 52 | .hljs-type, 53 | .hljs-class .hljs-title { 54 | color: #458; 55 | font-weight: bold; 56 | } 57 | 58 | .hljs-tag, 59 | .hljs-name, 60 | .hljs-attribute { 61 | color: #000080; 62 | font-weight: normal; 63 | } 64 | 65 | .hljs-regexp, 66 | .hljs-link { 67 | color: #009926; 68 | } 69 | 70 | .hljs-symbol, 71 | .hljs-bullet { 72 | color: #990073; 73 | } 74 | 75 | .hljs-built_in, 76 | .hljs-builtin-name { 77 | color: #0086b3; 78 | } 79 | 80 | .hljs-meta { 81 | color: #999; 82 | font-weight: bold; 83 | } 84 | 85 | .hljs-deletion { 86 | background: #fdd; 87 | } 88 | 89 | .hljs-addition { 90 | background: #dfd; 91 | } 92 | 93 | .hljs-emphasis { 94 | font-style: italic; 95 | } 96 | 97 | .hljs-strong { 98 | font-weight: bold; 99 | } 100 | -------------------------------------------------------------------------------- /html/styles/grayscale.css: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | grayscale style (c) MY Sun 4 | 5 | */ 6 | 7 | .hljs { 8 | display: block; 9 | overflow-x: auto; 10 | padding: 0.5em; 11 | color: #333; 12 | background: #fff; 13 | } 14 | 15 | .hljs-comment, 16 | .hljs-quote { 17 | color: #777; 18 | font-style: italic; 19 | } 20 | 21 | .hljs-keyword, 22 | .hljs-selector-tag, 23 | .hljs-subst { 24 | color: #333; 25 | font-weight: bold; 26 | } 27 | 28 | .hljs-number, 29 | .hljs-literal { 30 | color: #777; 31 | } 32 | 33 | .hljs-string, 34 | .hljs-doctag, 35 | .hljs-formula { 36 | color: #333; 37 | background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAJ0lEQVQIW2O8e/fufwYGBgZBQUEQxcCIIfDu3Tuwivfv30NUoAsAALHpFMMLqZlPAAAAAElFTkSuQmCC) repeat; 38 | } 39 | 40 | .hljs-title, 41 | .hljs-section, 42 | .hljs-selector-id { 43 | color: #000; 44 | font-weight: bold; 45 | } 46 | 47 | .hljs-subst { 48 | font-weight: normal; 49 | } 50 | 51 | .hljs-class .hljs-title, 52 | .hljs-type, 53 | .hljs-name { 54 | color: #333; 55 | font-weight: bold; 56 | } 57 | 58 | .hljs-tag { 59 | color: #333; 60 | } 61 | 62 | .hljs-regexp { 63 | color: #333; 64 | background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAICAYAAADA+m62AAAAPUlEQVQYV2NkQAN37979r6yszIgujiIAU4RNMVwhuiQ6H6wQl3XI4oy4FMHcCJPHcDS6J2A2EqUQpJhohQDexSef15DBCwAAAABJRU5ErkJggg==) repeat; 65 | } 66 | 67 | .hljs-symbol, 68 | .hljs-bullet, 69 | .hljs-link { 70 | color: #000; 71 | background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAKElEQVQIW2NkQAO7d+/+z4gsBhJwdXVlhAvCBECKwIIwAbhKZBUwBQA6hBpm5efZsgAAAABJRU5ErkJggg==) repeat; 72 | } 73 | 74 | .hljs-built_in, 75 | .hljs-builtin-name { 76 | color: #000; 77 | text-decoration: underline; 78 | } 79 | 80 | .hljs-meta { 81 | color: #999; 82 | font-weight: bold; 83 | } 84 | 85 | .hljs-deletion { 86 | color: #fff; 87 | background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAADCAYAAABS3WWCAAAAE0lEQVQIW2MMDQ39zzhz5kwIAQAyxweWgUHd1AAAAABJRU5ErkJggg==) repeat; 88 | } 89 | 90 | .hljs-addition { 91 | color: #000; 92 | background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAALUlEQVQYV2N89+7dfwYk8P79ewZBQUFkIQZGOiu6e/cuiptQHAPl0NtNxAQBAM97Oejj3Dg7AAAAAElFTkSuQmCC) repeat; 93 | } 94 | 95 | .hljs-emphasis { 96 | font-style: italic; 97 | } 98 | 99 | .hljs-strong { 100 | font-weight: bold; 101 | } 102 | -------------------------------------------------------------------------------- /sheets/typescript.md: -------------------------------------------------------------------------------- 1 | Typescript 2 | ========== 3 | 4 | - [MS Docs](https://www.typescriptlang.org/docs/home.html) 5 | - [More detailed cheatsheet](https://rmolinamir.github.io/typescript-cheatsheet/) 6 | 7 | 8 | Types 9 | ----- 10 | 11 | #### Basic 12 | 13 | ``` 14 | let isDone: boolean = false; 15 | let n: number = 77; 16 | let name: string = 'Fred'; 17 | ``` 18 | 19 | #### Array 20 | 21 | ``` 22 | let list: number[] = [1, 2, 3]; 23 | let list: Array = [1, 2, 3]; // generics 24 | ``` 25 | 26 | #### Tuple 27 | 28 | ``` 29 | let pair: [string, number]= ["value", 28]; 30 | ``` 31 | 32 | #### Enum 33 | 34 | ``` 35 | enum Color {Red, Green, Blue}; 36 | enum Flags { A=1, B=2, C=4 }; 37 | let c: Color = Color.Green; 38 | ``` 39 | 40 | #### Any 41 | 42 | Variant type. 43 | 44 | ``` 45 | let x: any = 6; 46 | let list: any[] = [1, true, "free"]; 47 | ``` 48 | 49 | #### Object 50 | 51 | ``` 52 | declare function create(o: object | null): void; 53 | 54 | create({ prop: 0 }); 55 | create(null); 56 | ``` 57 | 58 | #### Void 59 | 60 | ``` 61 | function foo(): void { 62 | // nothing 63 | } 64 | ``` 65 | 66 | #### Never 67 | 68 | ``` 69 | function error(message: string): never { 70 | throw new Error(message); 71 | } 72 | 73 | function fail() { 74 | return error("Something failed"); // Inferred return type is never 75 | } 76 | ``` 77 | 78 | ### Type Assertions 79 | 80 | Like casting. 81 | 82 | ``` 83 | let someValue: any = "this is a string"; 84 | 85 | let strLength: number = (someValue).length; 86 | let strLength2: number = (someValue as string).length; // same, used for JSX 87 | ``` 88 | 89 | Variables 90 | --------- 91 | 92 | ### Array & Tuple Destructuring 93 | 94 | Assignment: 95 | ``` 96 | let input = [1, 2]; 97 | let [first, second] = input; 98 | [first, second] = [second, first]; // swap 99 | let first = input[0]; 100 | ``` 101 | 102 | Function parameters: 103 | ``` 104 | function f([first, second]: [number, number]) { 105 | console.log(first); 106 | console.log(second); 107 | } 108 | ``` 109 | 110 | Partial: 111 | ``` 112 | let [first, ...rest] = [1, 2, 3, 4]; // remember tail 113 | let [first] = [1, 2, 3, 4]; // forget tail 114 | let [, second, , fourth] = [1, 2, 3, 4]; 115 | ``` 116 | 117 | ### Object Destructuring 118 | 119 | ``` 120 | let o = { 121 | a: "foo", 122 | b: 12, 123 | c: "bar" 124 | }; 125 | let { a, b } = o; 126 | ``` 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /sheets/git.md: -------------------------------------------------------------------------------- 1 | Git 2 | === 3 | 4 | Create & Config 5 | --------------- 6 | 7 | ### Create 8 | 9 | Create new repo: 10 | 11 | ```bash 12 | git init 13 | touch .gitignore 14 | git add * 15 | ``` 16 | 17 | Clone repo from various sources: 18 | 19 | - `git clone SOURCE_REPO NEW_REPO` :: Copy local repo. 20 | - `git clone git://...` :: Copy remote git source. 21 | - `git clone https://...` :: Copy remote git repo over HTTPS. 22 | 23 | ### Config 24 | 25 | Set values: 26 | 27 | - `git config --global user.name NAME` :: Set user name in config. 28 | - `git config --global user.email EMAIL` :: Set user email address in config. 29 | - `git config --global core.editor EDITOR` :: Set text editor. "EDITOR " to open. 30 | 31 | `--local`, `--global`, `--system` used to set local repo, user environment, system environment. 32 | 33 | Show/edit values: 34 | 35 | - `git config -l` :: List config. Option: `--local`. 36 | - `git config --global --edit` :: Edit config in text editor. 37 | 38 | 39 | TODO: `.gitignore` etc. 40 | 41 | 42 | Changing 43 | -------- 44 | 45 | ### Differences 46 | 47 | Show unstaged differences: 48 | 49 | - `git status` :: Show which files changed. 50 | - `git diff` :: Show unstaged file differences. 51 | 52 | Stage changes for commit: 53 | 54 | - `git add FILES...` :: Stage specific files. 55 | - `git add *` :: Stage all files added & changed recursively. 56 | - `git mv OLD NEW` :: Stage move or rename. 57 | - `git rm FILES...` :: Stage file deletes. 58 | - `git rm --cached files` :: Stop tracking, but keep files. 59 | 60 | 61 | ### Commiting 62 | 63 | After staging changes we can commit them. 64 | 65 | - `git commit` :: Commit staged changes and use edit for message. 66 | - `git commit -m 'MESSAGE'` :: Commit with message. 67 | - `git commit --amend` :: Apply staged changed to last commit and edit change message. 68 | 69 | Then we can `git push` to a remote. 70 | 71 | 72 | ### History 73 | 74 | Commit history log: 75 | 76 | - `git log` :: List repo history. 77 | - `git log -n ENTRIES` :: Limit list to last ENTRIES. 78 | - `git log FILE` :: Show only changes that affect FILE. 79 | - `git log --graph --decorate` :: Show graphical graph of commits. 80 | 81 | Repo changes: 82 | 83 | - `git reflog` :: Show changes made to local repo's HEAD. 84 | - `git blame FILE` :: Show who edited each FILE line last. 85 | 86 | 87 | ### Revert 88 | 89 | Per file: 90 | 91 | - `git checkout FILE` :: Revert file to branch HEAD. 92 | 93 | Per branch: 94 | 95 | - `git reset --hard` :: Revert *all local changes. 96 | 97 | 98 | Remotes 99 | ------- 100 | 101 | ### Updating 102 | 103 | Updating local repo without changing working files: 104 | 105 | - `git fetch` :: Fetch, but do not merge, changes from upstream. 106 | - `git fetch REMOTE` :: Fetch from specific remote. 107 | 108 | Update local repo, changing working file: 109 | 110 | - `git pull` :: Fetch and merge changes from upstream. 111 | - `git pull REMOTE` :: Use specific remote. 112 | 113 | Patching local files: 114 | 115 | - `git apply PATCH.diff` :: Apply patch file. 116 | 117 | 118 | ### Publishing 119 | 120 | - `git push` :: Push committed changes upstream. 121 | - `git push REMOTE` :: Push to specific remote. 122 | 123 | 124 | ### Remotes 125 | 126 | - `git remote add URL` :: Add new remote. 127 | 128 | -------------------------------------------------------------------------------- /html/css/cheatsheet.css: -------------------------------------------------------------------------------- 1 | 2 | /* bootstrap ... */ 3 | 4 | /* Move down content because we have a fixed navbar that is 50px tall */ 5 | body { 6 | padding-top: 50px; 7 | } 8 | 9 | /* Global add-ons */ 10 | 11 | .sub-header { 12 | padding-bottom: 10px; 13 | border-bottom: 1px solid #eee; 14 | } 15 | 16 | /* Top navigation 17 | * Hide default border to remove 1px line. 18 | */ 19 | .navbar-fixed-top { 20 | border: 0; 21 | } 22 | 23 | /* Sidebar */ 24 | 25 | /* Hide for mobile, show later */ 26 | .sidebar { 27 | display: none; 28 | } 29 | 30 | @media (min-width: 768px) { 31 | .sidebar { 32 | position: fixed; 33 | top: 51px; 34 | bottom: 0; 35 | left: 0; 36 | z-index: 1000; 37 | display: block; 38 | padding: 20px; 39 | overflow-x: hidden; 40 | overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */ 41 | background-color: #f5f5f5; 42 | border-right: 1px solid #eee; 43 | } 44 | } 45 | 46 | /* Sidebar navigation */ 47 | .nav-sidebar { 48 | margin-right: -21px; /* 20px padding + 1px border */ 49 | margin-bottom: 20px; 50 | margin-left: -20px; 51 | } 52 | .nav-sidebar > li > a { 53 | padding-right: 20px; 54 | padding-left: 20px; 55 | } 56 | .nav-sidebar > .active > a, 57 | .nav-sidebar > .active > a:hover, 58 | .nav-sidebar > .active > a:focus { 59 | color: #fff; 60 | background-color: #428bca; 61 | } 62 | 63 | 64 | /* 65 | * Main content 66 | */ 67 | 68 | .main { 69 | padding: 20px; 70 | } 71 | 72 | @media (min-width: 768px) { 73 | .main { 74 | padding-right: 40px; 75 | padding-left: 40px; 76 | } 77 | .main_show_all { 78 | margin: 0; 79 | width: 100%; 80 | padding: 1em 2em 4em 2em; 81 | } 82 | } 83 | .main .page-header { 84 | margin-top: 0; 85 | } 86 | 87 | 88 | /* 89 | * Placeholder dashboard ideas 90 | */ 91 | 92 | .placeholders { 93 | margin-bottom: 30px; 94 | text-align: center; 95 | } 96 | .placeholders h4 { 97 | margin-bottom: 0; 98 | } 99 | .placeholder { 100 | margin-bottom: 20px; 101 | } 102 | .placeholder img { 103 | display: inline-block; 104 | border-radius: 50%; 105 | } 106 | 107 | /*----------- cheatsheet -----------*/ 108 | 109 | h2 { 110 | border-width: 2px; 111 | border-color: #5a96ca; 112 | border-style: solid; 113 | border-radius: 5px; 114 | padding: 0.5em; 115 | background-color: #f0f0f0; 116 | margin: 1em 0 1em 0; 117 | } 118 | 119 | pre { font-size:0.9em; } 120 | 121 | .table { 122 | margin: 1.5em 0 1.5em 1em; 123 | width: 95%; 124 | } 125 | 126 | #csshowing h3 { margin-top: 2em; } 127 | #csshowing h4 { margin-top: 2em; } 128 | #csshowing h5 { margin-top: 1em; } 129 | 130 | #csshowing > div > :first-child { margin-top: 0px; } /* no space at top */ 131 | 132 | .vals-list { 133 | padding: 5px; 134 | margin: 1em 0 1em 0.5em; 135 | background-color: #fdfdfd; 136 | border-style: solid; 137 | border-width: 1px; 138 | border-color: #d0d0d0; 139 | border-radius: 5px; 140 | } 141 | 142 | .vals-list .row { 143 | margin: 0; 144 | padding: 3px 0 3px 0; 145 | } 146 | 147 | .vals-list .row:not(:first-child) { 148 | border-color: lightgray; 149 | border-width: 1px 0 0 0; 150 | border-style: dashed; 151 | } 152 | 153 | /*.vals-list .row:nth-child(even) { 154 | background-color: #f4f4f6; 155 | } 156 | .vals-list .row:nth-child(odd) { 157 | background-color: #fdfdfd; 158 | }*/ 159 | 160 | .vals-value { 161 | padding-left: 1em; 162 | /* font-weight: bold;*/ 163 | /* white-space: nowrap; */ 164 | /* text-align: center */ 165 | } 166 | 167 | .vals-comment { 168 | padding-left: 1em; 169 | color: #787878; 170 | } 171 | 172 | @media (min-width: 768px) { /* 2 cols for wider screen */ 173 | .vals-value { 174 | float: left; 175 | width: 40%; 176 | } 177 | .vals-comment { 178 | float: left; 179 | width: 50%; 180 | } 181 | } 182 | 183 | .popover { 184 | max-width: 100%; /* depends on container! required or code wraps */ 185 | } 186 | 187 | .note-unknown { 188 | background-color: #aa0000; 189 | color: white; 190 | padding: 5px; 191 | } 192 | 193 | .csnote { 194 | border-width: 1px; 195 | border-color: lightblue; 196 | border-style:dashed; 197 | border-radius: 5px; 198 | padding: 1em; 199 | } 200 | 201 | /* inline code. Needs specialisations to not break
 */
202 | p > code, li > code, div > code {
203 |   margin: 2px 4px 2px 4px;
204 |   font-size: 90%;
205 |   color: #a4323c;
206 |   background-color: #f4f4f4;
207 |   border-radius: 3px;
208 |   font-weight: normal;
209 | }
210 | 
211 | 


--------------------------------------------------------------------------------
/sheets/eg.md:
--------------------------------------------------------------------------------
  1 | 
  2 | Example
  3 | =======
  4 | 
  5 | Formatting
  6 | ----------
  7 | 
  8 | #### Formatting examples
  9 | 
 10 | - Some useful information *in italics* and **in bold**.
 11 | - `int itCode();` in here.
 12 | - Ctrl + A is for 'orses.
 13 | - Notes:   Inline note
 14 | 
 15 | 
 16 | #### Sub heading
 17 | 
 18 | Note this must be >h2.
 19 | 
 20 | - another list
 21 | - with items
 22 |   * and sublist
 23 |   * with more items
 24 | - and back to the other list
 25 | - which ends here
 26 | 
 27 | 
 28 | This is a small table example:
 29 | 
 30 | Country | Size | Food
 31 | ------- | ---- | ----
 32 | UK | small | chips
 33 | US | big | burgers
 34 | France | medium | cheese
 35 | 
 36 | 
 37 | This is an extension, lists with splits, for values-comments:
 38 | 
 39 | - `RGB(255,0,0)`  :: red
 40 | - `RGB(0,255)`    :: green
 41 | - `RGB(0,0,255)`  :: blue
 42 | 
 43 | More text:
 44 | 
 45 | - `${parameter:-word}` :: If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
 46 | - `${parameter:=word}` :: If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
 47 | - `${parameter:?word}` :: If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
 48 | - `${parameter:+word}` :: If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.
 49 | 
 50 | 
 51 | ### heading 3
 52 | #### heading 4
 53 | ##### heading 5
 54 | ###### heading 6
 55 | 
 56 | 
 57 | Table
 58 | -----
 59 | 
 60 | Big table example:
 61 | 
 62 | Key | Value
 63 | --- | -----
 64 | Apple | Pears
 65 | Tomarto | Tomayto
 66 | `code` | nice
 67 | 
 68 | 
 69 | Shortcut                       | Comment
 70 | ------------------------------ | -----------------------------------------
 71 | CTRL + A | move to beginning of line
 72 | CTRL + B | moves backward one character
 73 | CTRL + C | halts the current command
 74 | CTRL + D | deletes one character backward or logs out of current session, similar to exit
 75 | CTRL + E | moves to end of line
 76 | CTRL + F | moves forward one character
 77 | CTRL + G | aborts the current editing command and ring the terminal bell
 78 | CTRL + J | same as RETURN
 79 | CTRL + K | deletes (kill) forward to end of line
 80 | CTRL + L | clears screen and redisplay the line
 81 | 
 82 | 
 83 | Code
 84 | ----
 85 | 
 86 | #### Some BASH
 87 | 
 88 | This is a BASH example.
 89 | 
 90 | ```bash
 91 | #!/bin/bash
 92 | 
 93 | ###### BEGIN CONFIG
 94 | ACCEPTED_HOSTS="/root/.hag_accepted.conf"
 95 | BE_VERBOSE=false
 96 | ###### END CONFIG
 97 | 
 98 | if [ "$UID" -ne 0 ]
 99 | then
100 |  echo "Superuser rights is required"
101 |  echo 'Printing the # sign'
102 |  exit 2
103 | fi
104 | 
105 | if test $# -eq 0
106 | then
107 | elif test [ $1 == 'start' ]
108 | else
109 | fi
110 | 
111 | genApacheConf(){
112 |  if [[ "$2" = "www" ]]
113 |  then
114 |   full_domain=$1
115 |  else
116 |   full_domain=$2.$1
117 |  fi
118 |  host_root="${APACHE_HOME_DIR}$1/$2/$(title)"
119 |  echo -e "# Host $1/$2 :"
120 | }
121 | ```
122 | 
123 | #### Some Python
124 | 
125 | ```python
126 | @requires_authorization
127 | def somefunc(param1='', param2=0):
128 |     r'''A docstring'''
129 |     if param1 > param2: # interesting
130 |         print 'Gre\'ater'
131 |     return (param2 - param1 + 1 + 0b10l) or None
132 | 
133 | class SomeClass:
134 |     pass
135 | 
136 | >>> message = '''interpreter
137 | ... prompt'''
138 | ```
139 | 
140 | #### Some Lua
141 | 
142 | ```lua
143 | --[[
144 | Simple signal/slot implementation
145 | ]]
146 | local signal_mt = {
147 |     __index = {
148 |         register = table.insert
149 |     }
150 | }
151 | function signal_mt.__index:emit(... --[[ Comment in params ]])
152 |     for _, slot in ipairs(self) do
153 |         slot(self, ...)
154 |     end
155 | end
156 | local function create_signal()
157 |     return setmetatable({}, signal_mt)
158 | end
159 | 
160 | -- Signal test
161 | local signal = create_signal()
162 | signal:register(function(signal, ...)
163 |     print(...)
164 | end)
165 | signal:emit('Answer to Life, the Universe, and Everything:', 42)
166 | 
167 | --[==[ [=[ [[
168 | Nested ]]
169 | multi-line ]=]
170 | comment ]==]
171 | [==[ Nested
172 | [=[ multi-line
173 | [[ string
174 | ]] ]=] ]==]
175 | ```
176 | 
177 | Notes
178 | -----
179 | 
180 | 
181 | 
182 | #### A test
183 | 
184 | Test "with quotes" **bold**
185 | 
186 | #### Code test
187 | 
188 | ```lua
189 | if something then
190 |   -- do something
191 |   local function create_signal()
192 |       return setmetatable({}, signal_mt)
193 |   end
194 | end
195 | ```
196 | 
197 | #### colours
198 | 
199 | red
200 | 
201 | 
202 | Useful links
203 | ------------
204 | - [Cheatsheet Github page](https://github.com/billyquith/cheatsheet)
205 | - [Markdown syntax](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#tables)
206 | 


--------------------------------------------------------------------------------
/sheets/cmake.md:
--------------------------------------------------------------------------------
  1 | cmake
  2 | =====
  3 | 
  4 | Commands
  5 | --------
  6 | 
  7 | 
  8 | ### add_definitions
  9 | 
 10 | ```
 11 | add_definitions(-DFOO -DBAR ...)
 12 | ```
 13 | 
 14 | Adds definitions to the compiler command line for targets in the current directory and below.
 15 | 
 16 | ### find_package
 17 | 
 18 | ```raw
 19 | find_package( [version] [EXACT] [QUIET] [MODULE]
 20 |              [REQUIRED] [[COMPONENTS] [components...]]
 21 |              [OPTIONAL_COMPONENTS components...]
 22 |              [NO_POLICY_SCOPE])`
 23 | ```
 24 | [docs](https://cmake.org/cmake/help/latest/command/find_package.html)
 25 | 
 26 | Finds and loads settings from an external project (in "module mode"). `_FOUND` set indicates found. `QUIET`
 27 | disables messages if package not found. `MODULE` option disables the second signature. `REQUIRED`
 28 | option stops processing with an error message if package not be found.
 29 | 
 30 | A package-specific list of required components may be listed after the `COMPONENTS` option.
 31 | Additional optional components may be listed after `OPTIONAL_COMPONENTS`.
 32 | 
 33 | `[version]` argument requests a version with which the package found should be compatible (format
 34 | is `major[.minor[.patch[.tweak]]]`). The `EXACT` option requests that the version be matched exactly.
 35 | If no `[version]` and/or component list is given to a recursive invocation inside a find-module, the
 36 | corresponding arguments are forwarded automatically from the outer call (including the `EXACT` flag
 37 | for `[version]`). Version support is currently provided only on a package-by-package basis (details
 38 | below).
 39 | 
 40 | User code should generally look for packages using the above simple signature. See doc link for
 41 | more complicated version. 
 42 | 
 43 | The command has two modes by which it searches for packages: “Module” mode and “Config” mode.
 44 | *Module mode* is available when the command is invoked with the above reduced signature. CMake
 45 | searches for a file called `Find.cmake` in the `CMAKE_MODULE_PATH` followed by the CMake
 46 | installation. If the file is found, it is read and processed by CMake. It is responsible for
 47 | finding the package, checking the version, and producing any needed messages. Many find-modules
 48 | provide limited or no support for versioning; check the module documentation. If no module is found
 49 | and the MODULE option is not given the command proceeds to Config mode.
 50 | 
 51 | e.g.
 52 | ```cmake
 53 | find_package(SDL 2.0 REQUIRED)
 54 | if(SDL_FOUND)
 55 |   include_directories(${SDL_INCLUDE_DIRS})
 56 |   link_libraries(${SDL_LIBRARIES})
 57 | endif()
 58 | ```
 59 | 
 60 | ### message
 61 | 
 62 | ```
 63 | message([] "message to display" ...)
 64 | ```
 65 |   
 66 | ``:
 67 | 
 68 | - (none)         :: Important information
 69 | - STATUS         :: Incidental information
 70 | - WARNING        :: CMake Warning, continue processing
 71 | - AUTHOR_WARNING :: CMake Warning (dev), continue processing
 72 | - SEND_ERROR     :: CMake Error, continue processing, but skip generation
 73 | - FATAL_ERROR    :: CMake Error, stop processing and generation
 74 | - DEPRECATION    :: CMake Deprecation Error or Warning if variable `CMAKE_ERROR_DEPRECATED` 
 75 |   or `CMAKE_WARN_DEPRECATED` is enabled, respectively, else no message.
 76 | 
 77 | ### set
 78 | 
 79 | ```
 80 | set( ... [PARENT_SCOPE])
 81 | ```
 82 |   
 83 | 
 84 | Set given `` in the current function or directory scope. If `PARENT_SCOPE` given variable
 85 | set in scope above. Each new directory or function creates a new scope. 
 86 | 
 87 | ### source_group
 88 | 
 89 | ```
 90 | source_group( [FILES ...] [REGULAR_EXPRESSION ])
 91 | ```
 92 | 
 93 | Group files in IDE folders. `` may contain backslashes to specify subgroups:
 94 | `source_group(outer\\inner ...)`
 95 | 
 96 | - `FILES` :: Source files specified placed group ``. Relative paths are interpreted with
 97 |   respect to the current source directory.  
 98 | - `REGULAR_EXPRESSION` :: File names matching the regex placed in group ``. If matches
 99 |   multiple groups, last group matching favored, if any.
100 | 
101 | To set folder for project once added:
102 |   
103 | ```
104 | set_property(TARGET ${PROJ} PROPERTY FOLDER ${folder})
105 | ```
106 |              
107 |              
108 | Targets
109 | -------
110 | 
111 | ### Library
112 | 
113 | ```cmake
114 | add_library( [STATIC | SHARED | MODULE]
115 |             [EXCLUDE_FROM_ALL]
116 |             source1 [source2 ...])
117 | ```
118 | [docs](https://cmake.org/cmake/help/latest/command/add_library.html)
119 | 
120 | Adds library called `` built from source files listed. `` corresponds to the logical
121 | target name and must be globally unique within a project. `STATIC`, `SHARED`, or `MODULE` may be
122 | given to specify the type of library to be created.
123 | 
124 | - STATIC `.a`, object archive.
125 | - SHARED `.dylib`, dynamically loadable library.
126 | - MODULE `.so`, shared library module. OSX: `.bundle` plug-in.
127 | 
128 | ### Executable
129 | 
130 | ```cmake
131 | add_executable( [WIN32] [MACOSX_BUNDLE]
132 |                [EXCLUDE_FROM_ALL]
133 |                source1 [source2 ...])```
134 | [docs](https://cmake.org/cmake/help/latest/command/add_executable.html)
135 | 
136 | Adds executable called `` to be built from the source files listed. `` corresponds to
137 | the logical target name and must be globally unique within a project. The actual file name of the
138 | executable built is constructed based on conventions of the native platform (such as `.exe`
139 | or just `` ).
140 | 
141 | By default the executable file will be created in the build tree directory corresponding to the
142 | source tree directory in which the command was invoked. See `RUNTIME_OUTPUT_DIRECTORY` target
143 | property to change this location. See `OUTPUT_NAME` target property to change the `` part of
144 | the final file name.
145 | 
146 | - If `WIN32` is given the property `WIN32_EXECUTABLE` will be set on the target created.
147 | - If `MACOSX_BUNDLE` is given the corresponding property will be set on the created target.
148 | - If `EXCLUDE_FROM_ALL` is given the corresponding property will be set on the created target.
149 | 
150 | ### Flags
151 | 
152 | #### C++11
153 | 
154 | Equivalent to `-std=c++11` but backward compatible for GCC 4.6 on Travic-CI.
155 | ```cmake
156 | add_definitions(-std=c++0x) 
157 | ```
158 | 
159 | ### Output
160 | 
161 | - `CMAKE__OUTPUT_DIRECTORY`.
162 | - `ARCHIVE` is static library, `LIBRARY` is shared library, `RUNTIME` is executable.
163 | - *Note*, config is appended to this path, e.g. `Debug` (see below)
164 | 
165 | ```cmake
166 | set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${OUTDIR}/lib)
167 | set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${OUTDIR}/lib)   # or `bin` so DLLs in executable dir 
168 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${OUTDIR}/bin)
169 | ```
170 | 
171 | - `_OUTPUT_DIRECTORY_` : set full path for specific target configuration.
172 |   
173 | ```cmake
174 | set_target_properties(myapp PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG ${OUTDIR}/bin)
175 | ```
176 | 
177 | 
178 | Skeleton
179 | --------
180 | 
181 | ### Skeleton project
182 | 
183 | Root `CMakeLists.txt`;
184 | 
185 | ```cmake
186 | cmake_minimum_required(VERSION 2.8.3)
187 | project(PROJECT_NAME)
188 | 
189 | option(WANT_DOCS "Want project documentation" ON)
190 | 
191 | if(WANT_DOCS)
192 |   find_package(Doxygen)
193 |   if(DOXYGEN_FOUND)
194 |           # add a Doxygen target to the "all" target
195 |           add_custom_target(doxygen
196 |            ALL
197 |            COMMAND doxygen Doxyfile > ${DEV_NULL}
198 |            WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
199 |           )
200 |   else()
201 |     message(WARNING "Doxygen not found")
202 |   endif(DOXYGEN_FOUND)
203 | endif(WANT_DOCS)
204 | 
205 | add_subdirectory(src/lib)
206 | add_subdirectory(src/app)
207 | ```
208 | 
209 | #### src/lib/CMakeLists.txt
210 | 
211 | ```cmake
212 | include_directories("${PROJECT_SOURCE_DIR}/src")
213 | ```
214 | 
215 | #### src/app/CMakeLists.txt
216 | 
217 | ```cmake
218 | include_directories("${PROJECT_SOURCE_DIR}/src")
219 | ```
220 | 
221 | 
222 | Links
223 | -----
224 | 
225 | - [Current docs](https://cmake.org/cmake/help/latest/):
226 |     - [Commands](https://cmake.org/cmake/help/latest/manual/cmake-commands.7.html).
227 | 
228 | 


--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
  1 | 
  2 | 
  3 |   
  4 |     
  5 |     
  6 |     
  7 |     
  8 |     
  9 |     
 10 |     
 11 | 
 12 |     Cheatsheet
 13 | 
 14 |     
 15 |     
 16 |     
 17 |   
 18 | 
 19 |   
 20 |     
 21 |     
 22 |     
23 | 24 | 45 | 46 |
47 | 48 | 57 | 58 | 63 |
64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 330 | 331 | 332 | 333 | -------------------------------------------------------------------------------- /sheets/swift.md: -------------------------------------------------------------------------------- 1 | Swift 2 | ===== 3 | 4 | Variables 5 | --------- 6 | 7 | ### Scalar 8 | 9 | ``` 10 | println("Hello, world") 11 | var myVariable = 42 // variable (can't be nil) 12 | let π = 3.1415926 // constant 13 | let (x, y) = (10, 20) // x = 10, y = 20 14 | let explicitDouble: Double = 1_000.000_1 // 1,000.0001 15 | let label = "some text " + String(myVariable) // Casting 16 | let piText = "Pi = \(π)" // String interpolation 17 | var optionalString: String? = "optional" // Can be nil 18 | optionalString = nil 19 | 20 | /* Did you know /* you can nest multiline comments */ ? */ 21 | ``` 22 | 23 | ### Arrays 24 | 25 | ```swift 26 | var shoppingList = ["catfish", "water", "lemons"] // Array 27 | shoppingList[1] = "bottle of water" // update 28 | shoppingList.count // size of array (3) 29 | shoppingList.append("eggs") 30 | shoppingList += ["Milk"] 31 | ``` 32 | 33 | Array slicing 34 | 35 | ``` 36 | var fibList = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 5] 37 | fibList[4..<6] // [3, 5]. Note: the end range value is exclusive 38 | fibList[0..<(fibList.endIndex-1)] // all except last item 39 | ``` 40 | 41 | Subscripting returns the Slice type, instead of the Array type. 42 | You may need to cast it to Array in order to satisfy the type checker 43 | 44 | ``` 45 | Array(fibList[0..<4]) 46 | ``` 47 | 48 | Variants of creating an array. All three are equivalent. 49 | 50 | ``` 51 | var emptyArray1 = [String]() 52 | var emptyArray2: [String] = [] 53 | var emptyArray3: [String] = [String]() 54 | ``` 55 | 56 | ### Dictionaries 57 | 58 | ``` 59 | var occupations = [ // Dictionary 60 | "Malcolm": "Captain", 61 | "kaylee": "Mechanic" 62 | ] 63 | occupations["Jayne"] = "Public Relations" 64 | var emptyDictionary = Dictionary() 65 | ``` 66 | 67 | 68 | Control Flow 69 | ------------ 70 | 71 | ### for 72 | 73 | Over an array: 74 | 75 | ``` 76 | let myArray = [1, 1, 2, 3, 5] 77 | for value in myArray { // for loop (array) 78 | if value == 1 { 79 | println("One!") 80 | } else { 81 | println("Not one!") 82 | } 83 | } 84 | ``` 85 | 86 | Over a dictionary: 87 | 88 | ``` 89 | var dict = [ 90 | "name": "Steve Jobs", 91 | "title": "CEO", 92 | "company": "Apple" 93 | ] 94 | for (key, value) in dict { // for loop (dictionary) 95 | println("\(key): \(value)") 96 | } 97 | ``` 98 | 99 | Ranged. Use `..` to exclude the last item. 100 | 101 | ``` 102 | for i in -1...1 { // [-1, 0, 1] // for loop (range) 103 | println(i) 104 | } 105 | 106 | for _ in 1...3 { // for loop (ignoring iterator) 107 | // Do something three times. 108 | } 109 | ``` 110 | 111 | ### While 112 | 113 | ``` 114 | var i = 1 115 | while i < 1000 { // while loop 116 | i *= 2 117 | } 118 | ``` 119 | 120 | ### Do While 121 | 122 | ``` 123 | do { // do-while loop 124 | println("hello") 125 | } while 1 == 2 126 | ``` 127 | 128 | ### Switch 129 | 130 | Note, no fallthrough. 131 | 132 | ``` 133 | let vegetable = "red pepper" 134 | switch vegetable { // Switch 135 | case "celery": 136 | let vegetableComment = "Add some raisins and make ants on a log." 137 | case "cucumber", "watercress": 138 | let vegetableComment = "That would make a good tea sandwich." 139 | case let x where x.hasSuffix("pepper"): 140 | let vegetableComment = "Is it a spicy \(x)?" 141 | default: // required (in order to cover all possible input) 142 | let vegetableComment = "Everything tastes good in soup." 143 | } 144 | ``` 145 | 146 | ``` 147 | // Switch to validate plist content 148 | let city:Dictionary = [ 149 | "name" : "Qingdao", 150 | "population" : 2_721_000, 151 | "abbr" : "QD" 152 | ] 153 | switch (city["name"], city["population"], city["abbr"]) { 154 | case (.Some(let cityName as NSString), 155 | .Some(let pop as NSNumber), 156 | .Some(let abbr as NSString)) 157 | where abbr.length == 2: 158 | println("City Name: \(cityName) | Abbr.:\(abbr) Population: \(pop)") 159 | default: 160 | println("Not a valid city") 161 | } 162 | ``` 163 | 164 | Functions 165 | --------- 166 | 167 | ### Functions 168 | 169 | Functions are a first-class type, meaning they can be nested in functions and can be 170 | passed around. 171 | 172 | ``` 173 | func greet(name: String, day: String) -> String { 174 | return "Hello \(name), today is \(day)." 175 | } 176 | greet("Bob", "Tuesday") // call the greet function 177 | ``` 178 | 179 | Function that returns multiple items in a tuple 180 | 181 | ``` 182 | func getGasPrices() -> (Double, Double, Double) { 183 | return (3.59, 3.69, 3.79) 184 | } 185 | ``` 186 | 187 | Function that takes variable number of arguments, collecting them into an array 188 | 189 | ``` 190 | func setup(numbers: Int...) { 191 | // do something 192 | } 193 | setup(5, 16, 38) // call the setup function with array of inputs 194 | ``` 195 | 196 | Nested functions can organize code that is long or complex 197 | 198 | ``` 199 | func printWelcomeMessage() -> String { 200 | var y = "Hello," 201 | func add() { 202 | y += " world" 203 | } 204 | add() 205 | return y 206 | } 207 | printWelcomeMessage() // Hello world 208 | ``` 209 | 210 | Passing and returning functions 211 | 212 | ``` 213 | func makeIncrementer() -> (Int -> Int) { 214 | func addOne(number: Int) -> Int { 215 | return 1 + number 216 | } 217 | return addOne 218 | } 219 | var increment = makeIncrementer() 220 | increment(7) 221 | ``` 222 | 223 | ### Closures 224 | 225 | ``` 226 | Functions are special case closures ({}) 227 | // Closure example. 228 | // `->` separates the arguments and return type 229 | // `in` separates the closure header from the closure body 230 | var numbers = [1, 2, 3, 4, 5] 231 | numbers.map({ 232 | (number: Int) -> Int in 233 | let result = 3 * number 234 | return result 235 | }) 236 | 237 | // When the type is known, like above, we can do this 238 | numbers = [1, 2, 6] 239 | numbers = numbers.map({ number in 3 * number }) 240 | println(numbers) // [3, 6, 18] 241 | 242 | // When a closure is the last argument, you can place it after the ) 243 | // When a closure is the only argument, you can omit the () entirely 244 | // You can also refer to closure arguments by position ($0, $1, ...) rather than name 245 | numbers = [2, 5, 1] 246 | numbers.map { 3 * $0 } // [6, 15, 3] 247 | ``` 248 | 249 | 250 | Classes & Enums 251 | --------------- 252 | 253 | ### Classes 254 | 255 | All methods and properties of a class are public. If you just need to store data in a 256 | structured object, you should use a struct 257 | 258 | ``` 259 | // A parent class of Square 260 | class Shape { 261 | init() { 262 | } 263 | 264 | func getArea() -> Int { 265 | return 0; 266 | } 267 | } 268 | 269 | // A simple class `Square` extends `Shape` 270 | class Square: Shape { 271 | var sideLength: Int 272 | 273 | // Custom getter and setter property 274 | var perimeter: Int { 275 | get { 276 | return 4 * sideLength 277 | } 278 | set { 279 | sideLength = newValue / 4 280 | } 281 | } 282 | 283 | init(sideLength: Int) { 284 | self.sideLength = sideLength 285 | super.init() 286 | } 287 | 288 | func shrink() { 289 | if sideLength > 0 { 290 | --sideLength 291 | } 292 | } 293 | 294 | override func getArea() -> Int { 295 | return sideLength * sideLength 296 | } 297 | } 298 | 299 | var mySquare = Square(sideLength: 5) 300 | print(mySquare.getArea()) // 25 301 | mySquare.shrink() 302 | print(mySquare.sideLength) // 4 303 | 304 | // Access the Square class object, equivalent to [Square class] in Objective-C. 305 | Square.self 306 | 307 | //example for 'willSet' and 'didSet' 308 | class StepCounter { 309 | var totalSteps: Int = 0 { 310 | willSet(newTotalSteps) { 311 | println("About to set totalSteps to \(newTotalSteps)") 312 | } 313 | didSet { 314 | if totalSteps > oldValue { 315 | println("Added \(totalSteps - oldValue) steps to 'totalSteps'") 316 | } 317 | } 318 | } 319 | } 320 | 321 | var stepCounter = StepCounter() 322 | stepCounter.totalSteps = 100 // About to set totalSteps to 100 \n Added 100 steps to 'totalSteps' 323 | stepCounter.totalSteps = 145 // About to set totalSteps to 145 \n Added 45 steps to 'totalSteps' 324 | ``` 325 | 326 | If you don't need a custom getter and setter, but still want to run code 327 | before an after getting or setting a property, you can use `willSet` and `didSet`. 328 | 329 | ### Enums 330 | 331 | Enums can optionally be of a specific type or on their own. They can contain methods 332 | like classes. 333 | 334 | ``` 335 | enum Suit { 336 | case Spades, Hearts, Diamonds, Clubs 337 | func getIcon() -> String { 338 | switch self { 339 | case .Spades: return "♤" 340 | case .Hearts: return "♡" 341 | case .Diamonds: return "♢" 342 | case .Clubs: return "♧" 343 | } 344 | } 345 | } 346 | ``` 347 | 348 | 349 | Protocols 350 | --------- 351 | 352 | A protocol defines a blueprint of methods, properties, and other requirements 353 | that suit a particular task or piece of functionality. 354 | 355 | ``` 356 | protocol SomeProtocol { 357 | // protocol definition goes here 358 | } 359 | ``` 360 | 361 | Extensions & Overloading 362 | ------------------------ 363 | 364 | ### Extensions 365 | 366 | Add extra functionality to an already created type: 367 | 368 | ``` 369 | // adds the methods first and rest to the array type 370 | extension Array { 371 | func first () -> Any? { 372 | return self[0] 373 | } 374 | func rest () -> Array { 375 | if self.count >= 1 { 376 | return Array(self[1..self.endIndex]) 377 | } else { 378 | return [] 379 | } 380 | } 381 | } 382 | ``` 383 | 384 | ### Operator Overloading 385 | 386 | You can overwrite existing operators or define new operators for existing or custom types. 387 | 388 | ``` 389 | @infix func + (a: Int, b: Int) -> Int { // Overwrite existing types 390 | return a - b 391 | } 392 | var x = 5 + 4 // x is 1 393 | ``` 394 | 395 | *You can't overwrite the `=` operator.* Add operators for new types: 396 | 397 | ``` 398 | struct Vector2D { 399 | var x = 0.0, y = 0.0 400 | } 401 | 402 | @infix func + (left: Vector2D, right: Vector2D) -> Vector2D { 403 | return Vector2D(x: left.x + right.x, y: left.y + right.y) 404 | } 405 | ``` 406 | 407 | Operators can be prefix, infix, or postfix. You have to add `@assignment` if you wish 408 | to define compound assignment operators like `+=`, `++` or `-=`. 409 | 410 | ``` 411 | @assignment func += (inout left: Vector2D, right: Vector2D) { 412 | left = left + right 413 | } 414 | ``` 415 | 416 | Operator overloading is limited to the following symbols: `/ = - + * % < > ! & | ^ . ~` 417 | 418 | 419 | Generics 420 | -------- 421 | 422 | Generic code enables you to write flexible, reusable functions and types that can work 423 | with any type. 424 | 425 | ``` 426 | // Generic function, which swaps two any values. 427 | func swapTwoValues(inout a: T, inout b: T) { 428 | let temporaryA = a 429 | a = b 430 | b = temporaryA 431 | } 432 | 433 | // Generic collection type called `Stack`. 434 | struct Stack { 435 | var elements = T[]() 436 | 437 | mutating func push(element: T) { 438 | elements.append(element) 439 | } 440 | 441 | mutating func pop() -> T { 442 | return elements.removeLast() 443 | } 444 | } 445 | ``` 446 | 447 | We can use certain type constraints on the types with generic functions and generic 448 | types. Use where after the type name to specify a list of requirements. 449 | 450 | ``` 451 | // Generic function, which checks that the sequence contains a specified value. 452 | func containsValue< 453 | T where T: Sequence, T.GeneratorType.Element: Equatable> 454 | (sequence: T, valueToFind: T.GeneratorType.Element) -> Bool { 455 | 456 | for value in sequence { 457 | if value == valueToFind { 458 | return true 459 | } 460 | } 461 | 462 | return false 463 | } 464 | ``` 465 | 466 | In the simple cases, you can omit where and simply write the protocol or class name 467 | after a colon. Writing `` is the same as writing ``. 468 | 469 | 470 | Useful links 471 | ------------ 472 | 473 | - [Swift homepage](https://developer.apple.com/swift/). 474 | - [Swift Gitbook](https://mhm5000.gitbooks.io/swift-cheat-sheet/content/dictionaries/index.html) : 475 | origin of these samples. 476 | 477 | 478 | Notes 479 | ----- 480 | 481 | 482 | 483 | 484 | 485 | -------------------------------------------------------------------------------- /sheets/glsl.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | GLSL 4 | ==== 5 | 6 | Vertex Shader 7 | ------------- 8 | 9 | - [OpenGL wiki](https://www.opengl.org/wiki/Vertex_Shader) 10 | 11 | #### Built-in inputs 12 | 13 | ```glsl 14 | in int gl_VertexID; 15 | in int gl_InstanceID; 16 | ``` 17 | 18 | - `gl_VertexID​`: index of vertex being processed. When using non-indexed rendering, it is the 19 | effective index of the current vertex (the number of vertices processed + the first​ value). For 20 | indexed rendering, it is the index used to fetch this vertex from the buffer. Note: gl_VertexID​ 21 | will have the base vertex applied to it. 22 | - `gl_InstanceID​`: index of instance when doing some form of instanced rendering. Instance 23 | count always starts at 0, even when using base instance calls. When not using instanced 24 | rendering, this value 0. 25 | 26 | #### User input 27 | 28 | ```glsl 29 | layout(location = 2) in vec4 a_vec; 30 | ``` 31 | 32 | - `layout(location = #)` optional attribute index. Matrices take one index per column. 33 | 34 | #### Output 35 | 36 | ``` glsl 37 | out gl_PerVertex 38 | { 39 | vec4 gl_Position; 40 | float gl_PointSize; 41 | float gl_ClipDistance[]; 42 | }; 43 | ``` 44 | 45 | - `gl_PerVertex`​ defines *interface block* for outputs. Block is defined without instance name, 46 | so prefixing not required. 47 | - `gl_Position​`: clip-space output position of the current vertex. 48 | - `gl_PointSize​`: pixel width/height of point being rasterized, when rendering point primitives. 49 | Clamped to the `GL_POINT_SIZE_RANGE`. 50 | - `gl_ClipDistance​`: allows the shader to set the distance from the vertex to each user-defined 51 | clipping half-space. 52 | 53 | 54 | Fragment Shader 55 | --------------- 56 | 57 | - [OpenGL wiki](https://www.opengl.org/wiki/Fragment_Shader) 58 | - Fragment shaders are technically an optional shader stage, e.g. shadow mapping. If none, Fragment 59 | output colour values undefined. However, depth and stencil values output = input. 60 | - Fragment shaders have access to the `discard`​ command. Causes output values to be discarded. 61 | Fragment does not proceed to next pipeline stages. 62 | 63 | #### Built-in inputs 64 | 65 | ``` glsl 66 | in vec4 gl_FragCoord; 67 | in bool gl_FrontFacing; 68 | in vec2 gl_PointCoord; 69 | ``` 70 | ``` glsl 71 | // All the following are allowed redeclaration that change behavior 72 | layout(origin_upper_left) in vec4 gl_FragCoord; 73 | layout(pixel_center_integer) in vec4 gl_FragCoord; 74 | layout(origin_upper_left, pixel_center_integer) in vec4 gl_FragCoord; 75 | ``` 76 | 77 | - `gl_FragCoord​`: location of the fragment in window space. XYZ components are the *window-space* 78 | position of the fragment. Z will be written to the depth buffer if `gl_FragDepth`​ not written 79 | to. W component​ is 1/Wclip, where Wclip is the interpolated W of clip-space `gl_Position`​ from 80 | last Vertex Processing stage. The coordinate space of `gl_FragCoord`​ can be modified by redeclaring it: 81 | - `layout(origin_upper_left) in vec4 gl_FragCoord;` : This means that the origin for 82 | `gl_FragCoord​`'s window-space will be the upper-left of the screen, rather than the usual 83 | lower-left. 84 | - `layout(pixel_center_integer​) in vec4 gl_FragCoord;` : OpenGL window space is defined so pixel 85 | centers are on *half-integer* boundaries. Center of lower-left pixel is (0.5, 0.5). Using 86 | `pixel_center_integer`​​ adjust gl_FragCoord​ such that whole integer values represent pixel 87 | centers. Both of these exist to be compatible with D3D's window space. Unless you need your 88 | shaders to have this compatibility, you are advised not to use these features. 89 | - `gl_FrontFacing​`: True if this fragment was generated by the front-face of the primitive; else 90 | false if back. Only triangles have a back face; else this always true. 91 | 92 | - `gl_PointCoord​`: Location *within a point primitive*; defines fragment position relative to side 93 | of point, range [0,1], (0,0) upper-left. Points effectively window-space squares of certain pixel 94 | size, defined by single vertex. Origin can be switched to a bottom-left origin by calling 95 | `glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_LOWER_LEFT);​` 96 | 97 | **OpenGL 4.0+**: 98 | 99 | ```glsl 100 | in int gl_SampleID; 101 | in vec2 gl_SamplePosition; 102 | in int gl_SampleMaskIn[]; 103 | ``` 104 | 105 | - `gl_SampleID​`: Current sample that this fragment is rasterized for. *Warning:* Using this forces 106 | shader evaluation per-sample. Since much of the point of multisampling is to avoid that, you 107 | should use it only when you must. 108 | - `gl_SamplePosition​`: This is the location of the current sample for the fragment within the 109 | pixel's area, with values, range [0,1]. Origin is the bottom-left of the pixel. *Warning:* Using 110 | this forces this shader evaluation per-sample. Since much of the point of multisampling is to 111 | avoid that, you should use it only when you must. 112 | - `gl_SampleMaskIn​`: When using multisampling, this variable contains a bitfield for the sample 113 | mask of the fragment being generated. The array is as long as needed to fill in the number of 114 | samples supported by the GL implementation. 115 | 116 | Some Fragment shader built-in inputs will take values specified by OpenGL, but these values can be overridden by user control. 117 | 118 | ```glsl 119 | in float gl_ClipDistance[]; 120 | in int gl_PrimitiveID; 121 | ``` 122 | 123 | - `gl_ClipDistance​`: This array contains the interpolated clipping plane half-spaces, as output 124 | for vertices from the last Vertex Processing stage. 125 | - `gl_PrimitiveID​`: index of the current primitive being rendered by this drawing command. 126 | 127 | **OpenGL 4.3+**: 128 | 129 | ```glsl 130 | in int gl_Layer; 131 | in int gl_ViewportIndex; 132 | ``` 133 | 134 | - `gl_Layer​`: either 0 or the layer number for this primitive output by the Geometry Shader. 135 | - `gl_ViewportIndex​`: either 0 or the viewport index for primitive output by the Geometry Shader. 136 | 137 | #### Outputs 138 | 139 | ```glsl 140 | layout(location = 1) out int materialID; 141 | layout(location = 4) out vec3 normal; 142 | layout(location = 0) out vec4 diffuseColor; 143 | layout(location = 3) out vec3 position; 144 | layout(location = 2) out vec4 specularColor; 145 | ``` 146 | 147 | 148 | Tips 149 | ---- 150 | 151 | ### Use Swizzle 152 | 153 | ```glsl 154 | gl_Position.x = in_pos.x; 155 | gl_Position.y = in_pos.y; 156 | ``` 157 | faster as: 158 | ```glsl 159 | gl_Position.xy = in_pos.xy; 160 | ``` 161 | 162 | ### MAD 163 | 164 | Use multiply-add, i.e. A*B + C. 165 | ```glsl 166 | vec4 result1 = (value / 2.0) + 1.0; 167 | vec4 result2 = (1.0 + variable) * 0.5; 168 | 169 | // is more efficient as: 170 | vec4 result1 = (value * 0.5) + 1.0; 171 | vec4 result2 = 0.5 * variable + 0.5; // A*B + C 172 | ``` 173 | 174 | Swizzle can be combined: 175 | ```glsl 176 | myOutputColor.xyz = myColor.xyz; 177 | myOutputColor.w = 1.0; 178 | gl_FragColor = myOutputColor; 179 | 180 | // or, better: 181 | const vec2 constantList = vec2(1.0, 0.0); 182 | gl_FragColor = mycolor.xyzw * constantList.xxxy + constantList.yyyx; 183 | ``` 184 | 185 | ### Mix for lerp 186 | 187 | ```glsl 188 | vec3 colorRGB_0, colorRGB_1; 189 | float alpha; 190 | resultRGB = colorRGB_0 * (1.0 - alpha) + colorRGB_1 * alpha; 191 | ``` 192 | 193 | better, MAD: 194 | ```glsl 195 | resultRGB = colorRGB_0 + alpha * (colorRGB_1 - colorRGB_0); 196 | ``` 197 | 198 | best, `mix`: 199 | ```glsl 200 | resultRGB = mix(colorRGB_0, colorRGB_1, alpha); 201 | ``` 202 | 203 | 204 | Types 205 | ----- 206 | 207 | The OpenGL Shading Language supports the following basic data types, grouped as follows. 208 | 209 | ### Transparent types 210 | 211 | Type | Meaning 212 | ---- | ------- 213 | `void` | for functions that do not return a value 214 | `bool` | a conditional type, taking on values of true or false 215 | `int` | a signed integer 216 | `uint` | an unsigned integer 217 | `float` | a single-precision floating-point scalar 218 | `double` | a double-precision floating-point scalar 219 | `vecN` | a multi-component single-precision floating-point vector. N = [2,3,4]. 220 | `dvecN` | a multi-component double-precision floating-point vector. N = [2,3,4]. 221 | `bvecN` | a multi-component Boolean vector. N = [2,3,4]. 222 | `ivecN` | a multi-component signed integer vector. N = [2,3,4]. 223 | `ivecN` | a multi-component unsigned integer vector. N = [2,3,4]. 224 | `matN` | an N×N single-precision floating-point matrix. N = [2,3,4]. 225 | `matNxN` | same as a `matN` 226 | `matNxM` | an NxM double-precision floating-point matrix with N columns and M rows. N,M = [2,3,4]. 227 | `dmatN` | an N×N double-precision floating-point matrix. N = [2,3,4]. 228 | `dmatNxN` | same as a `dmatN` 229 | `dmatNxM` | an NxM double-precision floating-point matrix with N columns and M rows. N,M = [2,3,4]. 230 | 231 | ### Floating-Point Opaque Types 232 | 233 | Type | Meaning 234 | ---- | ------- 235 | `sampler1D`, `image1D` | a handle for accessing a 1D texture 236 | `sampler2D`, `image2D` | a handle for accessing a 2D texture 237 | `sampler3D`, `image3D` | a handle for accessing a 3D texture 238 | `samplerCube`, `imageCube` | a handle for accessing a cube mapped texture 239 | `sampler2DRect`, `image2DRect` | a handle for accessing a rectangle texture 240 | `sampler1DArray`, `image1DArray` | a handle for accessing a 1D array texture 241 | `sampler2DArray`, `image2DArray` | a handle for accessing a 2D array texture 242 | `samplerBuffer`, `imageBuffer` | a handle for accessing a buffer texture 243 | `sampler2DMS`, `image2DMS` | a handle for accessing a 2D multi-sample texture 244 | `sampler2DMSArray`, `image2DMSArray` | a handle for accessing a 2D multi-sample array texture 245 | `samplerCubeArray`, `imageCubeArray` | a handle for accessing a cube map array texture 246 | `sampler1DShadow` |` `a handle for accessing a 1D depth texture with comparison 247 | `sampler2DShadow` | a handle for accessing a 2D depth texture with comparison 248 | `sampler2DRectShadow` | a handle for accessing a rectangle texture with comparison 249 | `sampler1DArrayShadow` | a handle for accessing a 1D array depth texture with comparison 250 | `sampler2DArrayShadow` | a handle for accessing a 2D array depth texture with comparison 251 | `samplerCubeShadow` | a handle for accessing a cube map depth texture with comparison 252 | `samplerCubeArrayShadow` | a handle for accessing a cube map array depth texture with comparison 253 | 254 | TODO - add other opaque types 255 | 256 | ### Storage Qualifiers 257 | 258 | Variable declarations may have at most one storage qualifier specified in front of the type. These are summarized as 259 | 260 | Storage Qualifier | Meaning 261 | ----------------- | ------- 262 | none: default | local read/write memory, or an input parameter to a function 263 | `const` | a variable whose value cannot be changed 264 | `in` | linkage into a shader from a previous stage, variable is copied in 265 | `out` | linkage out of a shader to a subsequent stage, variable is copied out 266 | `attribute` | compatibility profile only and vertex language only; same as in when in a vertex shader 267 | `uniform` | value does not change across the primitive being processed, uniforms form the linkage between a shader, OpenGL, and the application 268 | `varying` | compatibility profile only and vertex and fragment languages only; same as out when in a vertex shader and same as in when in a fragment shader 269 | `buffer` | value is stored in a buffer object, and can be read or written both by shader invocations and the OpenGL API 270 | `shared` | compute shader only; variable storage is shared across all work items in a local work group 271 | 272 | 273 | Glossary 274 | -------- 275 | 276 | - **Compute Processor**: programmable unit that operates independently from the other shader 277 | processors. Compilation units written in the OpenGL Shading Language to run on this processor are 278 | called *compute shaders*. It does not have any predefined inputs nor any fixed-function outputs. 279 | It is not part of the graphics pipeline and its visible side effects are through changes to 280 | images, storage buffers, and atomic counters. A compute shader operates on a group of work items 281 | called a *work group*. 282 | - **Fragment Processor**: programmable unit that operates on fragment values and their associated 283 | data. Compilation units written in the OpenGL Shading Language to run on this processor are 284 | called *fragment shaders*. A fragment shader cannot change a fragment's (x, y) position. Access 285 | to neighboring fragments is not allowed. The values computed by the fragment shader are 286 | ultimately used to update framebuffer memory or texture memory, depending on the current OpenGL 287 | state and the OpenGL command that caused the fragments to be generated. 288 | - **Geometry Processor**: programmable unit that operates on data for incoming vertices for a 289 | primitive assembled after vertex processing and outputs a sequence of vertices forming output 290 | primitives. Compilation units written in the OpenGL Shading Language to run on this processor are 291 | called *geometry shaders*. This single invocation can emit a variable number of vertices that are 292 | assembled into primitives of a declared output primitive type and passed to subsequent pipeline 293 | stages. 294 | - **Opaque Types**: opaque handles to other objects. These objects are accessed through built-in 295 | functions, not through direct reading or writing of the declared variable. They can only be 296 | declared as function parameters or in uniform-qualified variables. 297 | - **Output Variables**: Declared using the storage qualifier `out`. They form the output interface 298 | between the declaring shader and the subsequent stages of the OpenGL pipeline. Output variables 299 | must be declared at global scope. During shader execution they will behave as normal unqualified 300 | global variables. Their values are copied out to the subsequent pipeline stage on shader exit. 301 | Only output variables that are read by the subsequent pipeline stage need to be written; it is 302 | allowed to have superfluous declarations of output variables. 303 | - **Uniform Variables**: The `uniform` qualifier is used to declare global variables whose values 304 | are the same across the entire primitive being processed. All uniform variables are *read-only* 305 | and are initialized externally either at link time or through the API. The link-time initial 306 | value is either the value of the variable's initializer, if present, or 0 if no initializer is 307 | present. Opaque types cannot have initializers, or a compile-time error results. 308 | - **Vertex Processor**: programmable unit that operates on incoming vertices and their 309 | associated data. Compilation units written in the OpenGL Shading Language to run on this 310 | processor are called *vertex shaders*. 311 | - **Work group**: a collection of shader invocations that execute the same code, potentially in 312 | parallel. An invocation within a work group may share data with other members of the same work 313 | group through shared variables and issue memory and control barriers to synchronize with other 314 | members of the same work group. 315 | 316 | 317 | ### Links 318 | 319 | - Source for this doc: https://www.opengl.org/registry/doc/GLSLangSpec.4.40.pdf 320 | - [GLSL wikipedia](https://en.wikipedia.org/wiki/OpenGL_Shading_Language) 321 | - [OpenGL wiki GLSL](https://www.opengl.org/wiki/OpenGL_Shading_Language) 322 | 323 | -------------------------------------------------------------------------------- /sheets/bash.md: -------------------------------------------------------------------------------- 1 | 2 | BASH 3 | ==== 4 | 5 | References 6 | ---------- 7 | 8 | - [BASH reference manual](https://www.gnu.org/software/bash/manual/bash.html). 9 | - [Grymoire](http://www.grymoire.com/Unix/index.html) - intro to UNIX concepts 10 | - [ss64 UNIX commands](http://ss64.com/bash/) - help on each command 11 | - [Shell Fu](http://www.shell-fu.org) 12 | 13 | 14 | Control 15 | ------- 16 | 17 | ### Logic 18 | 19 | ```bash 20 | if [ EXPRESSION ]; then 21 | COMMANDS 22 | fi 23 | ``` 24 | 25 | ```bash 26 | if [ EXPRESSION ]; then 27 | COMMANDS 28 | else 29 | COMMANDS 30 | fi 31 | ``` 32 | 33 | ```bash 34 | if [ EXPRESSION ]; then 35 | commands 36 | elif [ EXPRESSION2 ]; then 37 | COMMANDS 38 | else 39 | COMMANDS 40 | fi 41 | ``` 42 | 43 | ```bash 44 | case STRING in 45 | str1) COMMANDS;; 46 | str2) COMMANDS;; 47 | *) COMMANDS;; 48 | esac 49 | ``` 50 | 51 | ```bash 52 | LIST="one two three" 53 | for VAR1 in $LIST 54 | do 55 | COMMANDS 56 | done 57 | ``` 58 | 59 | ```bash 60 | while [ EXPRESSION ] 61 | do 62 | COMMANDS 63 | done 64 | ``` 65 | 66 | ```bash 67 | until [ EXPRESSION ] 68 | do 69 | COMMANDS 70 | done 71 | ``` 72 | 73 | #### Select 74 | 75 | Easy generation of menus: 76 | 77 | ```bash 78 | select NAME [in WORDS]; do COMMANDS; done 79 | ``` 80 | 81 | - WORDS is expanded, generating *list of items*. 82 | - *List* is printed on the *stderr stream*, each preceded by a number. 83 | - `select N; do COMMANDS; done` - line is read from the standard input, as if `in "$@"` specified. 84 | 85 | The *PS3 prompt* is then displayed and a line is *read from stdin*: 86 | 87 | - If input line a *number* corresponding to displayed word, value of name is set to word. 88 | - If input line *empty*, the words and prompt are displayed again. 89 | - If *EOF* is read, the select command completes. 90 | - Any *other* value read causes name to be set to null. 91 | - The line read is saved in the *variable REPLY*. 92 | 93 | The commands are executed after each selection until a break command is executed (or Ctrl + D). 94 | 95 | ```bash 96 | # Pick a filename from the current directory, and.out displays the name and 97 | # index of the file selected. 98 | select fname in *; 99 | do 100 | echo "You picked $fname \($REPLY\)"; 101 | break; 102 | done 103 | ``` 104 | 105 | ### Functions 106 | 107 | Functions are declared using syntax: 108 | 109 | ```bash 110 | [function] NAME [()] COMPOUND-COMMAND [ REDIRECTIONS ] 111 | ``` 112 | 113 | Functions can have input and output *redirected*. E.g. when called, 114 | *input* comes from`foo.in`, *output* to `foo.out`, and *error* to `foo.err`: 115 | 116 | ```bash 117 | function foo() { 118 | COMMANDS; 119 | } < foo.in > foo.out 2> foo.err 120 | 121 | ``` 122 | 123 | 124 | Input 125 | ----- 126 | 127 | #### read 128 | 129 | Synopsis: `read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name …]` [docs](https://www.gnu.org/software/bash/manual/bash.html#index-read) 130 | 131 | - `-a aname` :: Words are assigned to array variable `aname`, starting at 0. All elements are removed from aname before the assignment. Other name arguments are ignored. 132 | - `-d delim` :: The first character of delim is used to terminate the input line, rather than newline. 133 | - `-e` :: Readline used to obtain line. 134 | - `-i text` :: If Readline used, text placed into editing buffer before editing begins. 135 | - `-n nchars` :: read returns after reading nchars characters rather than waiting for a complete line of input, but honors a delimiter if fewer than nchars characters are read before the delimiter. 136 | - `-N nchars` :: read returns after exactly nchars characters, unless EOF is encountered or read times out. Delimiter chars are not special and do not cause read to return until nchars characters are read. Result is not split on the characters in IFS; the intent is that the variable is assigned exactly the characters read. 137 | - `-p prompt` :: Display prompt, without a trailing newline, before attempting to read any input. Prompt is displayed only if input is coming from a terminal. 138 | - `-r` :: If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not be used as a line continuation. 139 | - `-s` :: Silent mode. If input is coming from a terminal, characters are not echoed. 140 | - `-t timeout` :: Timeout after timeout seconds. Only effective if reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. If read times out, read saves any partial input read into the specified variable name. If timeout is 0, read returns immediately, without trying to read and data. The exit status is 0 if input is available on the specified file descriptor, non-zero otherwise. The exit status is greater than 128 if the timeout is exceeded. 141 | - `-u fd` :: Read input from file descriptor fd. 142 | 143 | ```bash 144 | read -p "prompt> " VAR 145 | echo ${VAR:-"Nothing entered"} 146 | ``` 147 | 148 | #### getopts 149 | 150 | ```bash 151 | while getopts "a:b" options; do 152 | case "${options}" in 153 | a) A=${OPTARG} ;; 154 | b) echo "B" ;; 155 | :) echo "Option ${OPTARG} expects an argument" && exit 2 ;; 156 | *) echo "Unknown option" && exit 2 ;; 157 | esac 158 | done 159 | ``` 160 | 161 | Output 162 | ------ 163 | 164 | #### cat 165 | 166 | Synopsis: `cat [-benstuv] [file ...]` 167 | 168 | Print the contents of file1 to the standard output: 169 | 170 | ```bash 171 | cat file1 172 | ``` 173 | 174 | Sequentially print the contents of file1 and file2 to the file file3, truncating file3 if it 175 | already exists. 176 | 177 | ```bash 178 | cat file1 file2 > file3 179 | ``` 180 | 181 | Print the contents of file1, print data it receives from the standard input until receive an 182 | `EOF` (`^D`) character, print the contents of file2, read and output contents of the standard input 183 | again, then finally output the contents of file3. 184 | 185 | ```bash 186 | cat file1 - file2 - file3 187 | ``` 188 | 189 | Write between markers, with redirection, to file1: 190 | 191 | ```bash 192 | cat << EOM > file1 193 | This line will write to the file. 194 | ${THIS} will also write to the file, with the variable contents substituted. 195 | EOM 196 | ``` 197 | 198 | 199 | Tests 200 | ----- 201 | 202 | `test expression` or `[ expression ]` 203 | 204 | #### Numeric Comparisons 205 | 206 | - `int1 -eq int2` :: True if int1 is equal to int2. 207 | - `int1 -ge int2` :: True if int1 is greater than or equal to int2. 208 | - `int1 -gt int2` :: True if int1 is greater than int2. 209 | - `int1 -le int2` :: True if int1 is less than or equal to int2 210 | - `int1 -lt int2` :: True if int1 is less than int2 211 | - `int1 -ne int2` :: True if int1 is not equal to int2 212 | 213 | 214 | #### String Comparisons 215 | 216 | - `str1 = str2` :: True if str1 is identical to str2. 217 | - `str1 != str2` :: True if str1 is not identical to str2. 218 | - `str` :: True if str is not null. 219 | - `-n str` :: True if the length of str is greater than zero. 220 | - `-z str` :: True if the length of str is equal to zero. (zero is different than null) 221 | 222 | 223 | #### File Comparisons 224 | 225 | - `-d filename` :: True if file, filename is a directory. 226 | - `-f filename` :: True if file, filename is an ordinary file. 227 | - `-r filename` :: True if file, filename can be read by the process. 228 | - `-s filename` :: True if file, filename has a nonzero length. 229 | - `-w filename` :: True if file, filename can be written by the process. 230 | - `-x filename` :: True if file, filename is executable. 231 | 232 | 233 | #### Expression Comparisons 234 | 235 | - `!expression` :: True if expression is not true. 236 | - `expr1 -a expr2` :: True if expr1 and expr2 are true. ( && , and ) 237 | - `expr1 -o expr2` :: True if expr1 or expr2 is true. ( ||, or ) 238 | 239 | 240 | Variables 241 | --------- 242 | 243 | #### Arguments 244 | 245 | - `$0` :: Stores the first word of the entered command (the name of the shell program). 246 | - `$1-$N` :: Stores the arguments (variables) that were passed to the shell program from the command line. 247 | - `$*` :: Stores all the arguments that were entered on the command line `($1 $2 ...)`. 248 | - `"$@"` :: Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...). 249 | - `$?` :: Stores the exit value of the last command that was executed. 250 | 251 | #### Defaults 252 | 253 | - `${PARAM:-WORD}` :: If PARAM is unset or null, the expansion of WORD is substituted. Otherwise, the value of PARAM is substituted. 254 | - `${PARAM:=WORD}` :: If PARAM is unset or null, the expansion of WORD is assigned to PARAM. The value of PARAM is then substituted. Positional parameters and special parameters may not be assigned to in this way. 255 | - `${PARAM:?WORD}` :: If PARAM is null or unset, the expansion of WORD (or a message to that effect if WORD is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of PARAM is substituted. 256 | - `${PARAM:+WORD}` :: If PARAM is null or unset, nothing is substituted, otherwise the expansion of WORD is substituted. 257 | 258 | #### Slicing 259 | 260 | - `${PARAM:OFFSET}` :: All characters after OFFSET. Note: -ve OFFSET is from end. 261 | - `${PARAM:OFFSET:LENGTH}` :: Slice characters after OFFSET for LENGTH. 262 | - `${@:OFFSET}` :: `@` = use positional parameters. OFFSET from start. 263 | - `${@:OFFSET:LENGTH}` :: Slice parameters from OFFSET for LENGTH. 264 | 265 | #### Counting 266 | 267 | - `${#PARAM}` :: Length of PARAM in chars. 268 | 269 | #### Substitution 270 | 271 | - `${PARAM/PATTERN/STRING}` :: Longest match of PATTERN is replaced with STRING. Pattern: `#` = PARAM start. @,* apply to positional params. 272 | - `${PARAM#WORD}` :: WORD is pattern ('?','*' wildcards). Shortest matching pattern deleted from string start. 273 | - `${PARAM##WORD}` :: As above, but longest matching pattern deleted from string start. 274 | - `${PARAM%WORD}` :: WORD is pattern ('?','*' wildcards). Shortest matching pattern deleted from string end. 275 | - `${PARAM%%WORD}` :: As above, but longest matching pattern deleted from string end. 276 | - `${PARAM^PATTERN}` :: Modify case of PARAM where pattern matched. Make upper case first char. 277 | - `${PARAM^^PATTERN}` :: As above. Make upper case all char. 278 | - `${PARAM,PATTERN}` :: As above. Make lower case first char. 279 | - `${PARAM,,PATTERN}` :: As above. Make lower case all chars. 280 | 281 | ### Useful 282 | 283 | * `SCRIPTPATH=$(cd $(dirname $0); pwd -P)` - Path of current script. 284 | 285 | #### set 286 | 287 | ```bash 288 | set -o errexit -o nounset 289 | ``` 290 | 291 | - errexit :: stop executing if any errors occur, by default bash will just continue past any errors 292 | to run the next command 293 | - nounset :: stop executing if an unset variable is encountered, by default bash will use an empty 294 | string for the value of such variables. 295 | 296 | 297 | Date 298 | ---- 299 | 300 | `date +"%FORMAT"` used to display or set date and time. Command: 301 | 302 | date "+DATE: %Y-%m-%d%nTIME: %H:%M:%S" 303 | 304 | displays: 305 | 306 | ```raw 307 | DATE: 1987-11-21 308 | TIME: 13:36:16 309 | ``` 310 | 311 | 312 | %FORMAT String | Description 313 | -------------- | ----------- 314 | `%%` | a literal % 315 | `%a` | locale’s abbreviated weekday name (e.g., Sun) 316 | `%A` | locale’s full weekday name (e.g., Sunday) 317 | `%b` | locale’s abbreviated month name (e.g., Jan) 318 | `%B` | locale’s full month name (e.g., January) 319 | `%c` | locale’s date and time (e.g., Thu Mar 3 23:05:25 2005) 320 | `%C` | century; like %Y, except omit last two digits (e.g., 21) 321 | `%d` | day of month (e.g, 01) 322 | `%D` | date; same as %m/%d/%y 323 | `%e` | day of month, space padded; same as %_d 324 | `%F` | full date; same as %Y-%m-%d 325 | `%g` | last two digits of year of ISO week number (see %G) 326 | `%G` | year of ISO week number (see %V); normally useful only with %V 327 | `%h` | same as %b 328 | `%H` | hour (00..23) 329 | `%I` | hour (01..12) 330 | `%j` | day of year (001..366) 331 | `%k` | hour ( 0..23) 332 | `%l` | hour ( 1..12) 333 | `%m` | month (01..12) 334 | `%M` | minute (00..59) 335 | `%n` | a newline 336 | `%N` | nanoseconds (000000000..999999999) 337 | `%p` | locale’s equivalent of either AM or PM; blank if not known 338 | `%P` | like %p, but lower case 339 | `%r` | locale’s 12-hour clock time (e.g., 11:11:04 PM) 340 | `%R` | 24-hour hour and minute; same as %H:%M 341 | `%s` | seconds since 1970-01-01 00:00:00 UTC 342 | `%S` | second (00..60) 343 | `%t` | a tab 344 | `%T` | time; same as %H:%M:%S 345 | `%u` | day of week (1..7); 1 is Monday 346 | `%U` | week number of year, with Sunday as first day of week (00..53) 347 | `%V` | ISO week number, with Monday as first day of week (01..53) 348 | `%w` | day of week (0..6); 0 is Sunday 349 | `%W` | week number of year, with Monday as first day of week (00..53) 350 | `%x` | locale’s date representation (e.g., 12/31/99) 351 | `%X` | locale’s time representation (e.g., 23:13:48) 352 | `%y` | last two digits of year (00..99) 353 | `%Y` | year 354 | `%z` | +hhmm numeric timezone (e.g., -0400) 355 | `%:z` | +hh:mm numeric timezone (e.g., -04:00) 356 | `%::z` | +hh:mm:ss numeric time zone (e.g., -04:00:00) 357 | `%:::z` | numeric time zone with : to necessary precision (e.g., -04, +05:30) 358 | `%Z` | alphabetic time zone abbreviation (e.g., EDT) 359 | 360 | 361 | Keyboard 362 | -------- 363 | 364 | Shortcut | Comment 365 | ------------------------------ | ----------------------------------------- 366 | CTRL + A | move to beginning of line 367 | CTRL + B | moves backward one character 368 | CTRL + C | halts the current command 369 | CTRL + D | deletes one character backward or logs out of current session, similar to exit 370 | CTRL + E | moves to end of line 371 | CTRL + F | moves forward one character 372 | CTRL + G | aborts the current editing command and ring the terminal bell 373 | CTRL + J | same as RETURN 374 | CTRL + K | deletes (kill) forward to end of line 375 | CTRL + L | clears screen and redisplay the line 376 | CTRL + M | same as RETURN 377 | CTRL + N | next line in command history 378 | CTRL + O | same as RETURN, then displays next line in history file 379 | CTRL + P | previous line in command history 380 | CTRL + R | searches backward 381 | CTRL + S | searches forward 382 | CTRL + T | transposes two characters 383 | CTRL + U | kills backward from point to the beginning of line 384 | CTRL + V | makes the next character typed verbatim 385 | CTRL + W | kills the word behind the cursor 386 | CTRL + X | lists the possible filename completefions of the current word 387 | CTRL + Y | retrieves (yank) last item killed 388 | CTRL + Z | stops the current command, resume with fg in the foreground or bg in the background 389 | 390 | 391 | Tips 392 | ---- 393 | 394 | ### History 395 | 396 | Config (`.bashrc`): 397 | 398 | shopt -s histappend 399 | shopt -s cmdhist 400 | export HISTCONTROL="erasedups:ignoreboth" # ignore duplicates 401 | export HISTIGNORE="&:[ ]*:exit" 402 | export HISTFILESIZE=500000 403 | export HISTSIZE=10000 404 | 405 | Top 10 commands used: 406 | 407 | history | awk '{print $2}' | awk 'BEGIN {FS="|"}{print $1}' | sort | uniq -c | sort -nr | head 408 | 409 | ### Navigation 410 | 411 | Takes you to the previous directory you were in: 412 | 413 | cd - 414 | 415 | List only subdirectoies in current one: 416 | 417 | ls -d */ 418 | 419 | ### Renaming 420 | 421 | Renaming/moving files with suffixes quickly: 422 | 423 | cp /home/foo/realllylongname.cpp{,-old} 424 | 425 | This expands to: 426 | 427 | cp /home/foo/realllylongname.cpp /home/foo/realllylongname.cpp-old 428 | 429 | ### Repeat 430 | 431 | Another favorite: 432 | 433 | `!!` and `!?` (matching) repeats your last command. E.g. 434 | 435 | ```bash 436 | !! # repeat 437 | sudo !! 438 | !?foo # repeat last command starting with "foo" 439 | ``` 440 | 441 | Print last command: 442 | 443 | !!:p 444 | !?foo?:p # print last command starting with "foo" 445 | 446 | `^search^replace` takes the last command applying a search and replace: 447 | 448 | $ ehco foo bar baz 449 | bash: ehco: command not found 450 | $ ^ehco^echo 451 | foo bar baz 452 | 453 | Run command with the previous command's arguments: 454 | 455 | $ mkdir /tmp/new 456 | $ cd !!:* 457 | 458 | 459 | ### Sources 460 | 461 | - Stack Overflow [favourite BASH tricks](http://stackoverflow.com/q/68372/3233) 462 | 463 | 464 | Notes 465 | ----- 466 | 467 | 468 | 469 | #### spe1 470 | 471 | ```bash 472 | VAR=${1:-'default'} 473 | ``` 474 | 475 | 476 | -------------------------------------------------------------------------------- /sheets/textmate.md: -------------------------------------------------------------------------------- 1 | 2 | Textmate 2 3 | ========== 4 | 5 | 6 | Regular Expressions 7 | ------------------- 8 | 9 | Regular-Expressions.info 10 | A.M. Kuchling’s Regular Expression HOWTO 11 | Steve Mansour’s A Tao of Regular Expressions 12 | Jeffrey Friedl’s Mastering Regular Expressions (book) 13 | 14 | Here is a list of places where TextMate makes use of regular expressions: 15 | 16 | - Filtering which files should be shown in folder references (added to projects) is done by 17 | providing regular expressions. 18 | - Find and Find in Project both allow regular expression replacements. 19 | - Folding markers are found via regular expressions. 20 | - Indentation calculations are based on regular expression matches. 21 | - Language grammars are basically a tree (with cycles) that have regular expressions in each node. 22 | - Snippets allow regular expression replacements to be applied to variables and (in realtime) 23 | mirrored placeholders. 24 | 25 | Regex Syntax 26 | ------------ 27 | 28 | TextMate uses the Oniguruma regular expression library by K. Kosako. Oniguruma Regular Expressions 29 | Version 5.6.0 2007/04/03 30 | 31 | syntax: ONIG_SYNTAX_RUBY (default) 32 | 33 | ### Syntax elements 34 | 35 | - `\` :: escape (enable or disable meta character meaning) 36 | - `|` :: alternation 37 | - `(...)` :: group 38 | - `[...]` :: character class 39 | 40 | 41 | #### Characters 42 | 43 | - `\t` :: horizontal tab (0x09) 44 | - `\v` :: vertical tab (0x0B) 45 | - `\n` :: newline (0x0A) 46 | - `\r` :: return (0x0D) 47 | - `\b` :: back space (0x08) 48 | - `\f` :: form feed (0x0C) 49 | - `\a` :: bell (0x07) 50 | - `\e` :: escape (0x1B) 51 | - `\nnn` :: octal char (encoded byte value) 52 | - `\xHH` :: hexadecimal char (encoded byte value) 53 | - `\x{7HHHHHHH}` :: wide hexadecimal char (character code point value) 54 | - `\cx` :: control char (character code point value) 55 | - `\C-x` :: control char (character code point value) 56 | - `\M-x` :: meta (x|0x80) (character code point value) 57 | - `\M-\C-x` :: meta control char (character code point value) 58 | 59 | `* \b` is effective in character class `[...]` only 60 | 61 | 62 | #### Character types 63 | 64 | - `.` :: any character (except newline) 65 | - `\w` :: word character 66 | Not Unicode: alphanumeric, "_" and multibyte char. 67 | Unicode: General_Category -- (Letter|Mark|Number|Connector_Punctuation) 68 | - `\W` :: non word char 69 | 70 | - `\s` :: whitespace char 71 | Not Unicode: `\t`, `\n`, `\v`, `\f`, `\r`, `\x20` 72 | Unicode: 73 | `0009`, `000A`, `000B`, `000C`, `000D`, `0085(NEL)`, 74 | General_Category -- Line_Separator 75 | -- Paragraph_Separator 76 | -- Space_Separator 77 | - `\S` :: non whitespace char 78 | - `\d` :: decimal digit char 79 | Unicode: General_Category -- Decimal_Number 80 | - `\D` :: non decimal digit char 81 | - `\h` :: hexadecimal digit char [0-9a-fA-F] 82 | - `\H` :: non hexadecimal digit char 83 | 84 | 85 | ##### Character Property 86 | 87 | * `\p{property-name}` 88 | * `\p{^property-name}` (negative) 89 | * `\P{property-name}` (negative) 90 | 91 | property-name: 92 | 93 | ```raw 94 | + works on all encodings 95 | Alnum, Alpha, Blank, Cntrl, Digit, Graph, Lower, 96 | Print, Punct, Space, Upper, XDigit, Word, ASCII, 97 | 98 | + works on EUC_JP, Shift_JIS 99 | Hiragana, Katakana 100 | 101 | + works on UTF8, UTF16, UTF32 102 | Any, Assigned, C, Cc, Cf, Cn, Co, Cs, L, Ll, Lm, Lo, Lt, Lu, 103 | M, Mc, Me, Mn, N, Nd, Nl, No, P, Pc, Pd, Pe, Pf, Pi, Po, Ps, 104 | S, Sc, Sk, Sm, So, Z, Zl, Zp, Zs, 105 | Arabic, Armenian, Bengali, Bopomofo, Braille, Buginese, 106 | Buhid, Canadian_Aboriginal, Cherokee, Common, Coptic, 107 | Cypriot, Cyrillic, Deseret, Devanagari, Ethiopic, Georgian, 108 | Glagolitic, Gothic, Greek, Gujarati, Gurmukhi, Han, Hangul, 109 | Hanunoo, Hebrew, Hiragana, Inherited, Kannada, Katakana, 110 | Kharoshthi, Khmer, Lao, Latin, Limbu, Linear_B, Malayalam, 111 | Mongolian, Myanmar, New_Tai_Lue, Ogham, Old_Italic, Old_Persian, 112 | Oriya, Osmanya, Runic, Shavian, Sinhala, Syloti_Nagri, Syriac, 113 | Tagalog, Tagbanwa, Tai_Le, Tamil, Telugu, Thaana, Thai, Tibetan, 114 | Tifinagh, Ugaritic, Yi 115 | ``` 116 | 117 | 118 | ### Quantifier 119 | 120 | #### greedy 121 | 122 | - `?` :: 1 or 0 times 123 | - `*` :: 0 or more times 124 | - `+` :: 1 or more times 125 | - `{n,m}` :: at least n but not more than m times 126 | - `{n,}` :: at least n times 127 | - `{,n}` :: at least 0 but not more than n times (`{0,n}`) 128 | - `{n}` :: n times 129 | 130 | #### reluctant 131 | 132 | - `??` :: 1 or 0 times 133 | - `*?` :: 0 or more times 134 | - `+?` :: 1 or more times 135 | - `{n,m}?` :: at least n but not more than m times 136 | - `{n,}?` :: at least n times 137 | - `{,n}?` :: at least 0 but not more than n times (== `{0,n}?`) 138 | 139 | #### possessive (greedy and does not backtrack after repeated) 140 | 141 | - `?+` :: 1 or 0 times 142 | - `*+` :: 0 or more times 143 | - `++` :: 1 or more times 144 | 145 | (`{n,m}+`, `{n,}+`, `{n}+` are possessive op. in ONIG_SYNTAX_JAVA only) ex. /a*+/ === /(?>a*)/ 146 | 147 | 148 | ### Anchors 149 | 150 | - `^` :: beginning of the line 151 | - `$` :: end of the line 152 | - `\b` :: word boundary 153 | - `\B` :: not word boundary 154 | - `\A` :: beginning of string 155 | - `\Z` :: end of string, or before newline at the end 156 | - `\z` :: end of string 157 | - `\G` :: matching start position 158 | 159 | 160 | ### Character class 161 | 162 | - `^...` :: negative class (lowest precedence operator) 163 | - `x-y` :: range from x to y 164 | - `[...]` :: set (character class in character class) 165 | - `..&&..` :: intersection (low precedence at the next of `^`) 166 | 167 | ex. [a-w&&[^c-g]z] ==> ([a-w] AND ([^c-g] OR z)) ==> [abh-w] 168 | 169 | If you want to use `[`, `-`, `]` as a normal character in a character class, 170 | you should escape these characters by `\`. 171 | 172 | ```text 173 | POSIX bracket ([:xxxxx:], negate [:^xxxxx:]) 174 | 175 | Not Unicode Case: 176 | 177 | alnum alphabet or digit char 178 | alpha alphabet 179 | ascii code value: [0 - 127] 180 | blank \t, \x20 181 | cntrl 182 | digit 0-9 183 | graph include all of multibyte encoded characters 184 | lower 185 | print include all of multibyte encoded characters 186 | punct 187 | space \t, \n, \v, \f, \r, \x20 188 | upper 189 | xdigit 0-9, a-f, A-F 190 | word alphanumeric, "_" and multibyte characters 191 | 192 | 193 | Unicode Case: 194 | 195 | alnum Letter | Mark | Decimal_Number 196 | alpha Letter | Mark 197 | ascii 0000 - 007F 198 | blank Space_Separator | 0009 199 | cntrl Control | Format | Unassigned | Private_Use | Surrogate 200 | digit Decimal_Number 201 | graph [[:^space:]] && ^Control && ^Unassigned && ^Surrogate 202 | lower Lowercase_Letter 203 | print [[:graph:]] | [[:space:]] 204 | punct Connector_Punctuation | Dash_Punctuation | Close_Punctuation | 205 | Final_Punctuation | Initial_Punctuation | Other_Punctuation | 206 | Open_Punctuation 207 | space Space_Separator | Line_Separator | Paragraph_Separator | 208 | 0009 | 000A | 000B | 000C | 000D | 0085 209 | upper Uppercase_Letter 210 | xdigit 0030 - 0039 | 0041 - 0046 | 0061 - 0066 211 | (0-9, a-f, A-F) 212 | word Letter | Mark | Decimal_Number | Connector_Punctuation 213 | ``` 214 | 215 | 216 | ### Extended groups 217 | 218 | - `(?#...)` :: comment 219 | 220 | - `(?imx-imx)` :: option on/off 221 | i: ignore case 222 | m: multi-line (dot(.) match newline) 223 | x: extended form 224 | - `(?imx-imx:subexp)` :: option on/off for subexp 225 | 226 | - `(?:subexp)` :: not captured group 227 | - `(subexp)` :: captured group 228 | 229 | - `(?=subexp)` :: look-ahead 230 | - `(?!subexp)` :: negative look-ahead 231 | - `(?<=subexp)` :: look-behind 232 | - `(? 233 | Subexp of look-behind must be fixed character length. 234 | But different character length is allowed in top level 235 | alternatives only. 236 | ex. (?<=a|bc) is OK. (?<=aaa(?:b|cd)) is not allowed. 237 | 238 | In negative-look-behind, captured group isn't allowed, 239 | but shy group(?:) is allowed. 240 | 241 | - `(?>subexp)` :: atomic group, don't backtrack in subexp. 242 | - `(?subexp)`, `(?'name'subexp)` :: define named group 243 | (All characters of the name must be a word character.) 244 | 245 | Not only a name but a number is assigned like a captured 246 | group. 247 | 248 | Assigning the same name as two or more subexps is allowed. 249 | In this case, a subexp call can not be performed although 250 | the back reference is possible. 251 | 252 | 253 | ### Back reference 254 | 255 | - `\n` :: back reference by group number (n >= 1) 256 | - `\k` :: back reference by group name 257 | - `\k'name'` :: back reference by group name 258 | 259 | In the back reference by the multiplex definition name, 260 | a subexp with a large number is referred to preferentially. 261 | (When not matched, a group of the small number is referred to.) 262 | 263 | Back reference by group number is *forbidden* if named group is defined 264 | in the pattern and ONIG_OPTION_CAPTURE_GROUP is not setted. 265 | 266 | Back reference with nest level: 267 | 268 | - `\k` - n: 0, 1, 2, ... 269 | - `\k` - n: 0, 1, 2, ... 270 | - `\k'name+n'` - n: 0, 1, 2, ... 271 | - `\k'name-n'` - n: 0, 1, 2, ... 272 | 273 | Destinate relative nest level from back reference position. 274 | 275 | ``` 276 | /\A(?|.|(?:(?.)\g\k))\z/.match("reer") 277 | ``` 278 | 279 | ``` 280 | r = Regexp.compile(<<'__REGEXP__'.strip, Regexp::EXTENDED) 281 | (? \g \g* \g ){0} 282 | (? < \g \s* > ){0} 283 | (? [a-zA-Z_:]+ ){0} 284 | (? [^<&]+ (\g | [^<&]+)* ){0} 285 | (? >){0} 286 | \g 287 | __REGEXP__ 288 | 289 | p r.match('fbbbf').captures 290 | ``` 291 | 292 | 293 | ### Subexp call 294 | 295 | ("Tanaka Akira special") 296 | 297 | - `\g` :: call by group name 298 | - `\g'name'` :: call by group name 299 | - `\g` :: call by group number (n >= 1) 300 | - `\g'n'` :: call by group number (n >= 1) 301 | 302 | left-most recursive call is not allowed. 303 | 304 | (?a|\gb) => error 305 | (?a|b\gc) => OK 306 | 307 | Call by group number is forbidden if named group is defined in the pattern and 308 | `ONIG_OPTION_CAPTURE_GROUP` is not setted. 309 | 310 | If the option status of called group is different from calling position then the group's option is 311 | effective. eg. `(?-i:\g)(?i:(?a)){0}` match to "A" 312 | 313 | 314 | ### Captured group 315 | 316 | Behavior of the no-named group (...) changes with the following conditions. 317 | (But named group is not changed.) 318 | 319 | case 1. /.../ (named group is not used, no option) 320 | 321 | (...) is treated as a captured group. 322 | 323 | case 2. /.../g (named group is not used, 'g' option) 324 | 325 | (...) is treated as a no-captured group (?:...). 326 | 327 | case 3. /..(?..)../ (named group is used, no option) 328 | 329 | (...) is treated as a no-captured group (?:...). 330 | numbered-backref/call is not allowed. 331 | 332 | case 4. /..(?..)../G (named group is used, 'G' option) 333 | 334 | (...) is treated as a captured group. 335 | numbered-backref/call is allowed. 336 | 337 | where 338 | g: ONIG_OPTION_DONT_CAPTURE_GROUP 339 | G: ONIG_OPTION_CAPTURE_GROUP 340 | 341 | ('g' and 'G' options are argued in ruby-dev ML) 342 | 343 | 344 | Regex notes 345 | ----------- 346 | 347 | ```raw 348 | A-1. Syntax depend options 349 | 350 | + ONIG_SYNTAX_RUBY 351 | (?m): dot(.) match newline 352 | 353 | + ONIG_SYNTAX_PERL and ONIG_SYNTAX_JAVA 354 | (?s): dot(.) match newline 355 | (?m): ^ match after newline, $ match before newline 356 | 357 | 358 | A-2. Original extensions 359 | 360 | + hexadecimal digit char type \h, \H 361 | + named group (?...), (?'name'...) 362 | + named backref \k 363 | + subexp call \g, \g 364 | 365 | 366 | A-3. Lacked features compare with perl 5.8.0 367 | 368 | + \N{name} 369 | + \l,\u,\L,\U, \X, \C 370 | + (?{code}) 371 | + (??{code}) 372 | + (?(condition)yes-pat|no-pat) 373 | 374 | * \Q...\E 375 | This is effective on ONIG_SYNTAX_PERL and ONIG_SYNTAX_JAVA. 376 | 377 | 378 | A-4. Differences with Japanized GNU regex(version 0.12) of Ruby 1.8 379 | 380 | + add character property (\p{property}, \P{property}) 381 | + add hexadecimal digit char type (\h, \H) 382 | + add look-behind 383 | (?<=fixed-char-length-pattern), (?>]/ in EUC-JP encoding. 395 | + effect range of isolated option is to next ')'. 396 | ex. (?:(?i)a|b) is interpreted as (?:(?i:a|b)), not (?:(?i:a)|b). 397 | + isolated option is not transparent to previous pattern. 398 | ex. a(?i)* is a syntax error pattern. 399 | + allowed incompleted left brace as an usual string. 400 | ex. /{/, /({)/, /a{2,3/ etc... 401 | + negative POSIX bracket [:^xxxx:] is supported. 402 | + POSIX bracket [:ascii:] is added. 403 | + repeat of look-ahead is not allowed. 404 | ex. /(?=a)*/, /(?!b){5}/ 405 | + Ignore case option is effective to numbered character. 406 | ex. /\x61/i =~ "A" 407 | + In the range quantifier, the number of the minimum is omissible. 408 | /a{,n}/ == /a{0,n}/ 409 | The simultanious abbreviation of the number of times of the minimum 410 | and the maximum is not allowed. (/a{,}/) 411 | + /a{n}?/ is not a non-greedy operator. 412 | /a{n}?/ == /(?:a{n})?/ 413 | + invalid back reference is checked and cause error. 414 | /\1/, /(a)\2/ 415 | + Zero-length match in infinite repeat stops the repeat, 416 | then changes of the capture group status are checked as stop condition. 417 | /(?:()|())*\1\2/ =~ "" 418 | /(?:\1a|())*/ =~ "a" 419 | 420 | 421 | A-5. Disabled functions by default syntax 422 | 423 | + capture history 424 | 425 | (?@...) and (?@...) 426 | 427 | ex. /(?@a)*/.match("aaa") ==> [<0-1>, <1-2>, <2-3>] 428 | 429 | see sample/listcap.c file. 430 | 431 | 432 | A-6. Problems 433 | 434 | + Invalid encoding byte sequence is not checked in UTF-8. 435 | 436 | * Invalid first byte is treated as a character. 437 | /./u =~ "\xa3" 438 | 439 | * Incomplete byte sequence is not checked. 440 | /\w+/ =~ "a\xf3\x8ec" 441 | 442 | ``` 443 | 444 | 20.4 Replacement String Syntax (Format Strings) 445 | 446 | When you perform a regular expression replace, the replace string is interpreted as a format string 447 | which can reference captures, perform case foldings, do conditional insertions (based on capture 448 | registers) and support a minimal amount of escape sequences. 449 | 450 | 20.4.1 Captures 451 | 452 | To reference a capture, use $n where n is the capture register number. Using $0 means the entire 453 | match. 454 | 455 | Example: 456 | 457 | Find: 458 | Replace: $1 459 | 20.4.2 Case Foldings 460 | 461 | It is possible to convert the next character to upper or lowercase by prepending it with \u or \l. 462 | This is mainly useful when the next character stems from a capture register. Example: 463 | 464 | Find: ()(.*?)() 465 | Replace: $1\u$2$3 466 | 467 | You can also convert a longer sequence to upper or lowercase by using \U or \L and then \E to 468 | disable the case folding again. Example: 469 | 470 | Find: ()(.*?)() 471 | Replace: $1\U$2\E$3 472 | 20.4.3 Conditional Insertions 473 | 474 | There are times where the replacements depends on whether or not something was matched. This can be 475 | done using (?«n»:«insertion») to insert «insertion» if capture «n» was matched. You can also use 476 | (?«n»:«insertion»:«otherwise») to have «otherwise» inserted when capture «n» was not matched. 477 | 478 | To make a capture conditional either place it in an alternation, e.g. foo|(bar)|fud or append a 479 | question mark to it: (bar)?. Note that (.*) will result in a match, even when zero characters are 480 | matched, so use (.+)? instead. 481 | 482 | So for example if we wish to truncate text to eight words and insert ellipsis only if there were 483 | more than eight words, we can use: 484 | 485 | Find: (\w+(?:\W+\w+){,7})\W*(.+)? 486 | Replace: $1(?2:…) 487 | 488 | Here we first match a word (\w+) followed by up to seven words ((?:\W+\w+){,7}) each preceded by 489 | non-word characters (spacing). Then optionally put anything following that (separated by non-word 490 | characters) into capture register 2 ((.+)?). 491 | 492 | The replacement first inserts the (up to) eight words matched ($1) and then only if capture 2 493 | matched something, ellipsis ((?2:…)). 494 | 495 | 20.4.4 Escape Codes 496 | 497 | In addition to the case folding escape codes, you can insert a newline character with \n, a tab 498 | character with \t and a dollar sign with \$. 499 | -------------------------------------------------------------------------------- /html/marked.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * marked - a markdown parser 3 | * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) 4 | * https://github.com/chjj/marked 5 | */ 6 | (function(){var block={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:noop,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:noop,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:noop,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/};block.bullet=/(?:[*+-]|\d+\.)/;block.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;block.item=replace(block.item,"gm")(/bull/g,block.bullet)();block.list=replace(block.list)(/bull/g,block.bullet)("hr","\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def","\\n+(?="+block.def.source+")")();block.blockquote=replace(block.blockquote)("def",block.def)();block._tag="(?!(?:"+"a|em|strong|small|s|cite|q|dfn|abbr|data|time|code"+"|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo"+"|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b";block.html=replace(block.html)("comment",//)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/])*?>/)(/tag/g,block._tag)();block.paragraph=replace(block.paragraph)("hr",block.hr)("heading",block.heading)("lheading",block.lheading)("blockquote",block.blockquote)("tag","<"+block._tag)("def",block.def)();block.normal=merge({},block);block.gfm=merge({},block.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/});block.gfm.paragraph=replace(block.paragraph)("(?!","(?!"+block.gfm.fences.source.replace("\\1","\\2")+"|"+block.list.source.replace("\\1","\\3")+"|")();block.tables=merge({},block.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/});function Lexer(options){this.tokens=[];this.tokens.links={};this.options=options||marked.defaults;this.rules=block.normal;if(this.options.gfm){if(this.options.tables){this.rules=block.tables}else{this.rules=block.gfm}}}Lexer.rules=block;Lexer.lex=function(src,options){var lexer=new Lexer(options);return lexer.lex(src)};Lexer.prototype.lex=function(src){src=src.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n");return this.token(src,true)};Lexer.prototype.token=function(src,top,bq){var src=src.replace(/^ +$/gm,""),next,loose,cap,bull,b,item,space,i,l;while(src){if(cap=this.rules.newline.exec(src)){src=src.substring(cap[0].length);if(cap[0].length>1){this.tokens.push({type:"space"})}}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);cap=cap[0].replace(/^ {4}/gm,"");this.tokens.push({type:"code",text:!this.options.pedantic?cap.replace(/\n+$/,""):cap});continue}if(cap=this.rules.fences.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"code",lang:cap[2],text:cap[3]||""});continue}if(cap=this.rules.heading.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:"heading",depth:cap[1].length,text:cap[2]});continue}if(top&&(cap=this.rules.nptable.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/\n$/,"").split("\n")};for(i=0;i ?/gm,"");this.token(cap,top,true);this.tokens.push({type:"blockquote_end"});continue}if(cap=this.rules.list.exec(src)){src=src.substring(cap[0].length);bull=cap[2];this.tokens.push({type:"list_start",ordered:bull.length>1});cap=cap[0].match(this.rules.item);next=false;l=cap.length;i=0;for(;i1&&b.length>1)){src=cap.slice(i+1).join("\n")+src;i=l-1}}loose=next||/\n\n(?!\s*$)/.test(item);if(i!==l-1){next=item.charAt(item.length-1)==="\n";if(!loose)loose=next}this.tokens.push({type:loose?"loose_item_start":"list_item_start"});this.token(item,false,bq);this.tokens.push({type:"list_item_end"})}this.tokens.push({type:"list_end"});continue}if(cap=this.rules.html.exec(src)){src=src.substring(cap[0].length);this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&&(cap[1]==="pre"||cap[1]==="script"||cap[1]==="style"),text:cap[0]});continue}if(!bq&&top&&(cap=this.rules.def.exec(src))){src=src.substring(cap[0].length);this.tokens.links[cap[1].toLowerCase()]={href:cap[2],title:cap[3]};continue}if(top&&(cap=this.rules.table.exec(src))){src=src.substring(cap[0].length);item={type:"table",header:cap[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:cap[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:cap[3].replace(/(?: *\| *)?\n$/,"").split("\n")};for(i=0;i])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:noop,tag:/^|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:noop,text:/^[\s\S]+?(?=[\\?(?:\s+['"]([\s\S]*?)['"])?\s*/;inline.link=replace(inline.link)("inside",inline._inside)("href",inline._href)();inline.reflink=replace(inline.reflink)("inside",inline._inside)();inline.normal=merge({},inline);inline.pedantic=merge({},inline.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/});inline.gfm=merge({},inline.normal,{escape:replace(inline.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:replace(inline.text)("]|","~]|")("|","|https?://|")()});inline.breaks=merge({},inline.gfm,{br:replace(inline.br)("{2,}","*")(),text:replace(inline.gfm.text)("{2,}","*")()});function InlineLexer(links,options){this.options=options||marked.defaults;this.links=links;this.rules=inline.normal;this.renderer=this.options.renderer||new Renderer;this.renderer.options=this.options;if(!this.links){throw new Error("Tokens array requires a `links` property.")}if(this.options.gfm){if(this.options.breaks){this.rules=inline.breaks}else{this.rules=inline.gfm}}else if(this.options.pedantic){this.rules=inline.pedantic}}InlineLexer.rules=inline;InlineLexer.output=function(src,links,options){var inline=new InlineLexer(links,options);return inline.output(src)};InlineLexer.prototype.output=function(src){var out="",link,text,href,cap;while(src){if(cap=this.rules.escape.exec(src)){src=src.substring(cap[0].length);out+=cap[1];continue}if(cap=this.rules.autolink.exec(src)){src=src.substring(cap[0].length);if(cap[2]==="@"){text=cap[1].charAt(6)===":"?this.mangle(cap[1].substring(7)):this.mangle(cap[1]);href=this.mangle("mailto:")+text}else{text=escape(cap[1]);href=text}out+=this.renderer.link(href,null,text);continue}if(!this.inLink&&(cap=this.rules.url.exec(src))){src=src.substring(cap[0].length);text=escape(cap[1]);href=text;out+=this.renderer.link(href,null,text);continue}if(cap=this.rules.tag.exec(src)){if(!this.inLink&&/^/i.test(cap[0])){this.inLink=false}src=src.substring(cap[0].length);out+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(cap[0]):escape(cap[0]):cap[0];continue}if(cap=this.rules.link.exec(src)){src=src.substring(cap[0].length);this.inLink=true;out+=this.outputLink(cap,{href:cap[2],title:cap[3]});this.inLink=false;continue}if((cap=this.rules.reflink.exec(src))||(cap=this.rules.nolink.exec(src))){src=src.substring(cap[0].length);link=(cap[2]||cap[1]).replace(/\s+/g," ");link=this.links[link.toLowerCase()];if(!link||!link.href){out+=cap[0].charAt(0);src=cap[0].substring(1)+src;continue}this.inLink=true;out+=this.outputLink(cap,link);this.inLink=false;continue}if(cap=this.rules.strong.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.strong(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.em.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.em(this.output(cap[2]||cap[1]));continue}if(cap=this.rules.code.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.codespan(escape(cap[2],true));continue}if(cap=this.rules.br.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.br();continue}if(cap=this.rules.del.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.del(this.output(cap[1]));continue}if(cap=this.rules.text.exec(src)){src=src.substring(cap[0].length);out+=this.renderer.text(escape(this.smartypants(cap[0])));continue}if(src){throw new Error("Infinite loop on byte: "+src.charCodeAt(0))}}return out};InlineLexer.prototype.outputLink=function(cap,link){var href=escape(link.href),title=link.title?escape(link.title):null;return cap[0].charAt(0)!=="!"?this.renderer.link(href,title,this.output(cap[1])):this.renderer.image(href,title,escape(cap[1]))};InlineLexer.prototype.smartypants=function(text){if(!this.options.smartypants)return text;return text.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…")};InlineLexer.prototype.mangle=function(text){if(!this.options.mangle)return text;var out="",l=text.length,i=0,ch;for(;i.5){ch="x"+ch.toString(16)}out+="&#"+ch+";"}return out};function Renderer(options){this.options=options||{}}Renderer.prototype.code=function(code,lang,escaped){if(this.options.highlight){var out=this.options.highlight(code,lang);if(out!=null&&out!==code){escaped=true;code=out}}if(!lang){return"
"+(escaped?code:escape(code,true))+"\n
"}return'
'+(escaped?code:escape(code,true))+"\n
\n"};Renderer.prototype.blockquote=function(quote){return"
\n"+quote+"
\n"};Renderer.prototype.html=function(html){return html};Renderer.prototype.heading=function(text,level,raw){return"'+text+"\n"};Renderer.prototype.hr=function(){return this.options.xhtml?"
\n":"
\n"};Renderer.prototype.list=function(body,ordered){var type=ordered?"ol":"ul";return"<"+type+">\n"+body+"\n"};Renderer.prototype.listitem=function(text){return"
  • "+text+"
  • \n"};Renderer.prototype.paragraph=function(text){return"

    "+text+"

    \n"};Renderer.prototype.table=function(header,body){return"\n"+"\n"+header+"\n"+"\n"+body+"\n"+"
    \n"};Renderer.prototype.tablerow=function(content){return"\n"+content+"\n"};Renderer.prototype.tablecell=function(content,flags){var type=flags.header?"th":"td";var tag=flags.align?"<"+type+' style="text-align:'+flags.align+'">':"<"+type+">";return tag+content+"\n"};Renderer.prototype.strong=function(text){return""+text+""};Renderer.prototype.em=function(text){return""+text+""};Renderer.prototype.codespan=function(text){return""+text+""};Renderer.prototype.br=function(){return this.options.xhtml?"
    ":"
    "};Renderer.prototype.del=function(text){return""+text+""};Renderer.prototype.link=function(href,title,text){if(this.options.sanitize){try{var prot=decodeURIComponent(unescape(href)).replace(/[^\w:]/g,"").toLowerCase()}catch(e){return""}if(prot.indexOf("javascript:")===0||prot.indexOf("vbscript:")===0){return""}}var out='
    ";return out};Renderer.prototype.image=function(href,title,text){var out=''+text+'":">";return out};Renderer.prototype.text=function(text){return text};function Parser(options){this.tokens=[];this.token=null;this.options=options||marked.defaults;this.options.renderer=this.options.renderer||new Renderer;this.renderer=this.options.renderer;this.renderer.options=this.options}Parser.parse=function(src,options,renderer){var parser=new Parser(options,renderer);return parser.parse(src)};Parser.prototype.parse=function(src){this.inline=new InlineLexer(src.links,this.options,this.renderer);this.tokens=src.reverse();var out="";while(this.next()){out+=this.tok()}return out};Parser.prototype.next=function(){return this.token=this.tokens.pop()};Parser.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0};Parser.prototype.parseText=function(){var body=this.token.text;while(this.peek().type==="text"){body+="\n"+this.next().text}return this.inline.output(body)};Parser.prototype.tok=function(){switch(this.token.type){case"space":{return""}case"hr":{return this.renderer.hr()}case"heading":{return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text)}case"code":{return this.renderer.code(this.token.text,this.token.lang,this.token.escaped)}case"table":{var header="",body="",i,row,cell,flags,j;cell="";for(i=0;i/g,">").replace(/"/g,""").replace(/'/g,"'")}function unescape(html){return html.replace(/&([#\w]+);/g,function(_,n){n=n.toLowerCase();if(n==="colon")return":";if(n.charAt(0)==="#"){return n.charAt(1)==="x"?String.fromCharCode(parseInt(n.substring(2),16)):String.fromCharCode(+n.substring(1))}return""})}function replace(regex,opt){regex=regex.source;opt=opt||"";return function self(name,val){if(!name)return new RegExp(regex,opt);val=val.source||val;val=val.replace(/(^|[^\[])\^/g,"$1");regex=regex.replace(name,val);return self}}function noop(){}noop.exec=noop;function merge(obj){var i=1,target,key;for(;iAn error occured:

    "+escape(e.message+"",true)+"
    "}throw e}}marked.options=marked.setOptions=function(opt){merge(marked.defaults,opt);return marked};marked.defaults={gfm:true,tables:true,breaks:false,pedantic:false,sanitize:false,sanitizer:null,mangle:true,smartLists:false,silent:false,highlight:null,langPrefix:"lang-",smartypants:false,headerPrefix:"",renderer:new Renderer,xhtml:false};marked.Parser=Parser;marked.parser=Parser.parse;marked.Renderer=Renderer;marked.Lexer=Lexer;marked.lexer=Lexer.lex;marked.InlineLexer=InlineLexer;marked.inlineLexer=InlineLexer.output;marked.parse=marked;if(typeof module!=="undefined"&&typeof exports==="object"){module.exports=marked}else if(typeof define==="function"&&define.amd){define(function(){return marked})}else{this.marked=marked}}).call(function(){return this||(typeof window!=="undefined"?window:global)}()); -------------------------------------------------------------------------------- /sheets/moonscript.md: -------------------------------------------------------------------------------- 1 | Moonscript 2 | ========== 3 | 4 | Introduction 5 | ------------ 6 | 7 | ### About 8 | 9 | * These notes are for Moonscript version: 0.5.0 10 | * [Website](http://moonscript.org) 11 | * [License](http://moonscript.org/reference/#license-mit) is MIT. 12 | * [Language reference](http://moonscript.org/reference/) 13 | * [Online compiler](http://moonscript.org/compiler/) 14 | * Moonscript compiles to Lua code. It can therefore use things like LuaJIT, and all Lua libraries. 15 | 16 | ### Comments 17 | 18 | ```moon 19 | -- I am a comment 20 | ``` 21 | 22 | ### Assignment 23 | 24 | New, unassigned names are *local* by default (unlike Lua, where default is global): 25 | 26 | ```moon 27 | hello = 1.75 28 | a,b,c = 1, 2, 3 -- multiple assignment 29 | hello = "Bob" -- uses the existing variable (changing type) 30 | ``` 31 | 32 | 33 | Literals 34 | -------- 35 | 36 | ### Numbers 37 | 38 | ```moon 39 | a,b,c = 1.75, 2.5e10, -7 40 | d = a + b * c / 12.5 41 | ``` 42 | 43 | Minus sign plays two roles, a unary negation operator and a binary subtraction operator: 44 | 45 | ```moon 46 | a = x - 10 -- local a = x - 10 47 | b = x-10 -- local b = x - 10 48 | c = x -y -- local c = x(-y) 49 | d = x- z -- local d = x - z 50 | ``` 51 | 52 | ### Strings 53 | 54 | ```moon 55 | str2 = "double quote" 56 | 57 | str1 = 'single "quote" containing quotes' 58 | 59 | some_string = "Here is a string 60 | that has a line break in it." 61 | 62 | joined = str1 .. " and more" 63 | ``` 64 | 65 | 66 | ### Tables 67 | 68 | Key assigned using `:`. Brackets are optional. 69 | 70 | ```moon 71 | t = {} -- table 72 | 73 | some_values = { 74 | name: "Bill", 75 | age: 200, 76 | ["favorite food"]: "rice", 77 | [1 + 2]: "hello", -- key expression 78 | "hello world": true -- brackets optional 79 | } 80 | 81 | profile = -- no brackets 82 | height: "4 feet", 83 | shoe_size: 13, 84 | favorite_foods: {"ice cream", "donuts"} 85 | ``` 86 | 87 | Can be created on single line: 88 | 89 | ```moon 90 | my_function dance: "Tango", partner: "none" -- pass table to function 91 | 92 | y = type: "dog", legs: 4, tails: 1 -- create & assign 93 | ``` 94 | 95 | Table of variables and where keys same as the variable names: 96 | 97 | ```moon 98 | hair = "golden" 99 | height = 200 100 | person = { :hair, :height, shoe_size: 40 } 101 | ``` 102 | 103 | ### Functions 104 | 105 | No arguments. Indenting defines scope. 106 | 107 | ```moon 108 | func_a = -> print "hello world" 109 | 110 | func_b = -> 111 | value = 100 112 | print "The value:", value 113 | 114 | func_a! -- call with no args, preferred to func_b() 115 | ``` 116 | 117 | With arguments: 118 | 119 | ```moon 120 | print_sum = (x, y) -> print "sum", x + y -- no return value 121 | 122 | calc_sum = (x, y) -> x + y -- implicit return value 123 | 124 | print_sum 1, 2 -- call with 2 args. Note comma(s). 125 | sum = calc_sum 7, 8 -- equivalent to: 126 | sum2 = calc_sum(7, 8) -- note, no space after function name. 127 | 128 | many_args_func 5,4,3, -- args on multiple lines 129 | 8,9, 130 | 10 131 | 132 | my_func 5,6,7, -- multi-line call 133 | 6, another_func 6,7,8, -- call function within args 134 | 9,1,2, 135 | 5,4 136 | ``` 137 | 138 | Can return multiple values: 139 | 140 | ```moon 141 | mystery = (x, y) -> x + y, x - y 142 | a,b = mystery 10, 20 143 | ``` 144 | 145 | Self idiom: 146 | 147 | ```moon 148 | func = (num) => @value + num 149 | ``` 150 | 151 | Argument defaults: 152 | 153 | ```moon 154 | my_function = (name="something", height=100) -> 155 | print "Hello I am", name 156 | print "My height is", height 157 | 158 | -- Note, arguments are evaluated in order of declaration: 159 | some_args = (x=100, y=x+1000) -> 160 | print x + y 161 | ``` 162 | 163 | Comprehensions 164 | -------------- 165 | 166 | ### List Comprehensions 167 | 168 | List comprehensions use `[]`. `items` for key,value. `*items` for value. 169 | 170 | ```moon 171 | items = { 1, 2, 3, 4 } 172 | doubled = [item * 2 for i, item in ipairs items] -- new list, items doubled 173 | 174 | doubled = [item * 2 for item in *items] -- use value iterator 175 | ``` 176 | 177 | Items created conditionally: 178 | 179 | ```moon 180 | slice = [item for i, item in ipairs items when i > 1 and i < 3] 181 | ``` 182 | 183 | Multiple, nested `for` loops: 184 | 185 | ```moon 186 | x_coords = {4, 5, 6, 7} 187 | y_coords = {9, 2, 3} 188 | 189 | points = [{x,y} for x in *x_coords for y in *y_coords] 190 | ``` 191 | 192 | Numeric loop: 193 | 194 | ```moon 195 | evens = [i for i=1,100 when i % 2 == 0] 196 | ``` 197 | 198 | Note, `for` loops can also create arrays: 199 | 200 | ```moon 201 | doubled_evens = for i=1,10 do if i%2 == 0 then i*2 else i 202 | ``` 203 | 204 | ### Table Comprehensions 205 | 206 | Table comprehensions use `{}`. 207 | 208 | ```moon 209 | thing = { 210 | color: "red" 211 | name: "fast" 212 | width: 123 213 | } 214 | 215 | thing_copy = {k,v for k,v in pairs thing} -- copy the table 216 | 217 | numbers = {1,2,3,4} 218 | sqrts = {i, math.sqrt i for i in *numbers} -- use value iterator 219 | 220 | tuples = { {"hello", "world"}, {"foo", "bar"} } 221 | tbl = {unpack tuple for tuple in *tuples} -- key,value pairs 222 | ``` 223 | 224 | Conditionally: 225 | 226 | ```moon 227 | no_color = {k,v for k,v in pairs thing when k != "color"} 228 | ``` 229 | 230 | 231 | Iteration 232 | --------- 233 | 234 | ### For loop 235 | 236 | Numeric and generic `for` loops: 237 | 238 | ```moon 239 | for i = 10, 20 -- print 10 to 20 240 | print i 241 | 242 | for k = 1,15,2 -- odd numbers using step 243 | print k 244 | 245 | for key, value in pairs object -- iterate object 246 | print key, value 247 | ``` 248 | 249 | Can occupy single line: 250 | 251 | ```moon 252 | for item in *items do print item 253 | 254 | for j = 1,10,3 do print j 255 | ``` 256 | 257 | Can be used as expression to create array. Note, to return from a function, must use `return`. 258 | 259 | ```moon 260 | fizz_buzz = for i=1,100 -- make array 261 | if i % 3 == 0 262 | i * 3 263 | elseif i % 5 == 0 264 | i * 5 265 | else 266 | continue -- skip value 267 | 268 | func_a = -> for i=1,10 do i -- return nil 269 | func_b = -> return for i=1,10 do i -- return array 270 | ``` 271 | 272 | ### While loop 273 | 274 | `while` loops can be single or multiple lines. 275 | 276 | ```moon 277 | i = 10 278 | while i > 0 -- print 1 to 10 279 | print i 280 | i -= 1 281 | 282 | while running == true do my_function! 283 | ``` 284 | 285 | Can incorporate `break` and `continue`, with conditionals: 286 | 287 | ```moon 288 | i = 0 289 | while i < 10 290 | continue if i % 2 == 0 291 | print i 292 | break if i > 6 293 | ``` 294 | 295 | Can be used as an expression: 296 | 297 | ```moon 298 | i = 0 299 | array = while true do if i % 3 == 0 continue else if i > 100 break else i 300 | ``` 301 | 302 | 303 | Conditionals 304 | ------------ 305 | 306 | ### If 307 | 308 | `if` can be single or multi-line: 309 | 310 | ```moon 311 | have_coins = false 312 | 313 | if have_coins 314 | print "Got coins" 315 | else 316 | print "No coins" 317 | 318 | if have_coins then print "Got coins" else print "No coins" -- single line 319 | ``` 320 | 321 | Expression: 322 | 323 | ```moon 324 | have_coins = false 325 | print if have_coins then "Got coins" else "No coins" 326 | 327 | is_tall = (name) -> -- function 328 | if name == "Rob" 329 | true 330 | else 331 | false 332 | 333 | message = if is_tall "Rob" -- value assigned 334 | "I am very tall" 335 | else 336 | "I am not so tall" 337 | 338 | print message -- prints: I am very tall 339 | ``` 340 | 341 | With *assignment*: 342 | 343 | ```moon 344 | if user = database.find_user "moon" -- 'user' assigned and then tested 345 | print user.name 346 | 347 | if hello = os.getenv "hello" 348 | print "You have hello", hello 349 | elseif world = os.getenv "world" 350 | print "you have world", world 351 | else 352 | print "nothing :(" 353 | ``` 354 | 355 | ### Unless 356 | 357 | `unless` is the opposite of `if`. 358 | 359 | ```moon 360 | unless os.date("%A") == "Monday" 361 | print "it is not Monday!" 362 | 363 | print "You're lucky!" unless math.random! > 0.1 364 | ``` 365 | 366 | ### Line decorators 367 | 368 | Conditionals can be postfixed on a line. 369 | 370 | ```moon 371 | print "hello world" if name == "Rob" 372 | 373 | print "hello world" unless name == "John" 374 | ``` 375 | 376 | Loops may also be postfixed: 377 | 378 | ```moon 379 | print "item: ", item for item in *items 380 | ``` 381 | 382 | ### Switch 383 | 384 | `switch` is shorthand for a series of `if` statements. Use `then` to write a block on a single line. 385 | 386 | ```moon 387 | name = "Dan" 388 | switch name 389 | when "Robert" 390 | print "You are Robert" 391 | when "Dan", "Daniel" 392 | print "Your name, it's Dan" 393 | else 394 | print "I don't know about your name" 395 | 396 | msg = switch math.random(1, 5) 397 | when 1 then "you are lucky" -- single line 398 | when 2 then "you are almost lucky" 399 | else "not so lucky" 400 | ``` 401 | 402 | 403 | Manipulation 404 | ------------ 405 | 406 | ### Update 407 | 408 | ```moon 409 | x = 0 410 | x += 10 411 | 412 | s = "hello " 413 | s ..= "world" 414 | 415 | b = false 416 | b and= true or false 417 | ``` 418 | 419 | ### Slicing 420 | 421 | A slice is a subset of an index: `items[MIN,MAX]`, i.e. from MIN to MAX, inclusive. Or `items[MIN,MAX,STEP]` using step size. 422 | 423 | ```moon 424 | slice = [item for item in *items[1,5]] -- 1st to 5th items of array 425 | 426 | slice = [item for item in *items[,3]] -- the first 3 427 | 428 | for item in *items[2,]] -- 2nd until last 429 | print item 430 | 431 | for item in *items[,,2] do print item -- all odd items, 1,3,5, ... 432 | ``` 433 | 434 | ### String interpolation 435 | 436 | Evaluate and substitute contents of `#{}`. 437 | 438 | ```moon 439 | print "I am #{math.random! * 100}% sure." 440 | ``` 441 | 442 | 443 | Blocks 444 | ------ 445 | 446 | ### With 447 | 448 | `with` can be used to avoid repetition of instance names: 449 | 450 | ```moon 451 | with Person! 452 | .name = "Oswald" 453 | \add_relative my_dad 454 | \save! 455 | print .name 456 | 457 | file = with File "favorite_foods.txt" -- return created object 458 | \set_encoding "utf8" 459 | 460 | create_person = (name, relatives) -> 461 | with Person! 462 | .name = name 463 | \add_relative relative for relative in *relatives 464 | 465 | me = create_person "Leaf", {dad, mother, sister} 466 | 467 | with str = "Hello" 468 | print "original:", str 469 | print "upper:", \upper! 470 | ``` 471 | 472 | ### Do 473 | 474 | Do can be used to limit scope: 475 | 476 | ```moon 477 | do 478 | var = "hello" 479 | print var 480 | print var -- nil here 481 | ``` 482 | 483 | It can also be used as an expression: 484 | 485 | ```moon 486 | counter = do 487 | i = 0 488 | -> 489 | i += 1 490 | i 491 | 492 | print counter! -- 1 493 | print counter! -- 2 494 | 495 | tbl = { 496 | key: do 497 | print "assigning key!" 498 | 1234 499 | } 500 | ``` 501 | 502 | 503 | Objects 504 | ------- 505 | 506 | A `class` can be declared and called: 507 | 508 | ```moon 509 | class Inventory 510 | new: => 511 | @items = {} 512 | 513 | add_item: (name) => 514 | if @items[name] 515 | @items[name] += 1 516 | else 517 | @items[name] = 1 518 | 519 | inv = Inventory! 520 | inv\add_item "t-shirt" 521 | inv\add_item "pants" 522 | 523 | assert b.__class == BackPack -- check class type 524 | ``` 525 | 526 | Where: 527 | 528 | * `new` is the constructor. 529 | * Use *fat arrow* `=>` when calling instance methods to handle the creation of a `self` argument, like `:` in Lua. 530 | * `@` prefix on variable is shorthand for `self.. @items` becomes `self.items`. 531 | * `\` operator is used to pass `self` to instance method. 532 | * Each class instance carries its type using `__class`. 533 | * [Reference](http://moonscript.org/reference/#the-language/object-oriented-programming). 534 | 535 | ### Inheritance 536 | 537 | `extends` is used to extend a class further. If we don’t define a constructor on the subclass, the parent class' constructor is called when we make a new instance. If we do then we use the `super` method to call the parent constructor. 538 | 539 | ```moon 540 | class BackPack extends Inventory 541 | size: 10 542 | add_item: (name) => 543 | if #@items > size then error "backpack is full" 544 | super name 545 | ``` 546 | 547 | When a subclass is instanced, it sends a message to the parent by calling `__inherited`. The function receives two arguments: 548 | 549 | - the class that is being inherited 550 | - the child class. 551 | 552 | ```moon 553 | class Shelf 554 | @__inherited: (child) => 555 | print @__name, "was inherited by", child.__name 556 | 557 | -- Will print "Shelf was inherited by Cupboard": 558 | class Cupboard extends Shelf 559 | ``` 560 | 561 | ### Super 562 | 563 | `super` can be used in two different ways: 564 | 565 | - As an object, i.e. a reference to the parent class object. 566 | - Called like a function. I.e. It will call the function of the same name in the parent class. Current `self` will automatically be passed as the first argument. 567 | 568 | ```moon 569 | class MyClass extends ParentClass 570 | a_method: => 571 | -- the following have the same effect: 572 | super "hello", "world" 573 | super\a_method "hello", "world" 574 | super.a_method self, "hello", "world" 575 | 576 | assert super == ParentClass -- super as a value is equal to the parent class: 577 | ``` 578 | 579 | 580 | Class details 581 | ------------- 582 | 583 | ### Class objects 584 | 585 | Class properties are shared between all instances of the class, stored in the *base* table. 586 | The base table also holds the class metamethods. 587 | 588 | ```moon 589 | class Person 590 | clothes: {} -- shared, class property (base) 591 | give_item: (name) => -- method also shared (base) 592 | table.insert @clothes, name 593 | 594 | a = Person! 595 | b = Person! 596 | 597 | a\give_item "pants" 598 | b\give_item "shirt" 599 | 600 | print item for item in *a.clothes -- will print both pants and shirt 601 | ``` 602 | 603 | The class instance specific properties are stored in the *class* table. 604 | 605 | ```moon 606 | class Person 607 | @clothes: {} -- per-instance property (class) 608 | give_item: (name) => 609 | table.insert @clothes, name 610 | 611 | a = Person! 612 | b = Person! 613 | 614 | a\give_item "pants" 615 | b\give_item "shirt" 616 | 617 | print item for item in *a.clothes -- will print "pants" 618 | print item for item in *b.clothes -- will print "shirt" 619 | ``` 620 | 621 | Note, class properties may also be declared using `=` assignment. 622 | 623 | ```moon 624 | class Things 625 | @class_var = "hello world" 626 | @another: "hello also!" -- similar 627 | ``` 628 | 629 | ### Class variables 630 | 631 | * To get class name use `__name`. 632 | * To get class instance type use `__class`. 633 | * To get parent class, use `__parent`. This is what subclass extends. 634 | * To get base class, use `__base`. This contains shared properties and metamethods. 635 | 636 | ```moon 637 | instance = Backpack! -- create instance 638 | cls = instance.__class -- get class type of instance 639 | print cls.__name -- name of class type 640 | print cls.__base -- base class type 641 | ``` 642 | 643 | ### @ & @@ 644 | 645 | Use `@property` to access class instance property, short for `self.property`. 646 | 647 | ```moon 648 | class Things 649 | @some_func: => print "Hello from", @__name 650 | 651 | Things\some_func! 652 | 653 | -- class variables not visible in instances 654 | assert Things().some_func == nil 655 | ``` 656 | 657 | Use `@@property` to access class property, short for `self.__class.property`. 658 | 659 | ```moon 660 | class Counter 661 | @count: 0 662 | 663 | new: => 664 | @@count += 1 665 | 666 | Counter! 667 | Counter! 668 | 669 | print Counter.count -- prints 2 670 | ``` 671 | 672 | ### Expressions 673 | 674 | A class maybe be used as an expression and assigned: 675 | 676 | ```moon 677 | x = class Bucket 678 | drops: 0 679 | add_drop: => @drops += 1 680 | ``` 681 | 682 | It may also be assigned *anonymously*. If assigned, the variable name is taken instead. 683 | 684 | ```moon 685 | BigBucket = class extends Bucket 686 | add_drop: => @drops += 10 687 | 688 | assert Bucket.__name == "BigBucket" 689 | ``` 690 | 691 | 692 | Scope 693 | ----- 694 | 695 | ### Global/Export 696 | 697 | All assignment is *local* by default. Use `export` to declare *global variables*. 698 | 699 | ```moon 700 | export some_number, message_str = 100, "hello world" 701 | ``` 702 | 703 | `export` is necessary to declare what is *visible* outside a module. 704 | 705 | ```moon 706 | module "my_module", package.seeall -- module 707 | export print_result 708 | 709 | length = (x, y) -> math.sqrt x*x + y*y 710 | 711 | print_result = (x, y) -> 712 | print "Length is ", length x, y 713 | ``` 714 | 715 | ```moon 716 | require "my_module" -- module user 717 | 718 | my_module.print_result 4, 5 -- prints the result 719 | 720 | print my_module.length 6, 7 -- errors, `length` not visible 721 | ``` 722 | 723 | * `export *` will export all in current scope. 724 | * `export ^` will export all proper names (that begin with a capital letter). 725 | 726 | ### Local 727 | 728 | Use `local` to pre-declare locals: 729 | 730 | ```moon 731 | local a 732 | if something 733 | a = 1 734 | print a -- nil or 1 735 | ``` 736 | 737 | ```moon 738 | local a = 1 739 | if something 740 | local a -- a shadowed 741 | a = 3 742 | print a -- always 1 743 | ``` 744 | 745 | ```moon 746 | local first, second -- allow mutual references 747 | 748 | first = -> second! 749 | 750 | second = -> first! 751 | ``` 752 | 753 | * `local *` will *forward declare* all variables in current scope. 754 | * `local ^` will *forward declare* all proper names (that begin with a capital letter). 755 | 756 | 757 | ```moon 758 | local * -- local first, second, data 759 | 760 | first = -> 761 | print data -- without forward declaration, this would fail 762 | second! -- as would this 763 | 764 | second = -> 765 | first! 766 | 767 | data = {} 768 | ``` 769 | 770 | ### Import 771 | 772 | Use `import` to bring values from a table. 773 | 774 | ```moon 775 | import C, Ct, Cmt from lpeg 776 | 777 | import -- multi-line 778 | assert_csrf 779 | assert_timezone 780 | not_found 781 | require_login 782 | from require "helpers" 783 | ``` 784 | 785 | To import module contents that requires context: 786 | 787 | ```moon 788 | my_module = 789 | state: 100 790 | add: (value) => 791 | self.state + value 792 | 793 | import \add from my_module 794 | 795 | print add 22 -- equivalent to calling my_module\add 22 796 | ``` 797 | 798 | ### Modules 799 | 800 | Files return, like functions. We return what we want exported from the module as a table. 801 | 802 | ```moon 803 | MY_CONSTANT = "hello" 804 | 805 | my_function = -> print "the function" 806 | my_second_function = -> print "another function" 807 | 808 | { :my_function, :my_second_function, :MY_CONSTANT} 809 | ``` 810 | 811 | 812 | Destructuring 813 | ------------- 814 | 815 | Destructuring allows concise *extraction of values* from arrays and tables. 816 | 817 | ```moon 818 | thing = {1,2} -- array 819 | {a,b} = thing -- unpack 820 | print a,b -- 1, 2 821 | ``` 822 | 823 | From tables: 824 | 825 | ```moon 826 | obj = { 827 | hello: "world" 828 | day: "tuesday" 829 | length: 20 830 | } 831 | 832 | {hello: hello, day: the_day} = obj 833 | print hello, the_day 834 | ``` 835 | 836 | ```moon 837 | obj2 = { 838 | numbers: {1,2,3,4} 839 | properties: { -- nested 840 | color: "green" 841 | height: 13.5 842 | } 843 | } 844 | 845 | { 846 | numbers: { first, second } -- 1,2 847 | properties: { 848 | color: color 849 | } 850 | } = obj2 851 | 852 | print first, second, color 853 | 854 | { properties: { :height } } = obj2 -- avoid duplication 855 | 856 | print height 857 | ``` 858 | 859 | Useful to import from standard libraries: 860 | 861 | ```moon 862 | {:concat, :insert} = table 863 | 864 | {:mix, :max, random: rand } = math 865 | ``` 866 | 867 | In `for` loop: 868 | 869 | ```moon 870 | tuples = { 871 | {"hello", "world"} 872 | {"egg", "head"} 873 | } 874 | 875 | for {left, right} in *tuples 876 | print left, right 877 | ``` 878 | 879 | 880 | Using 881 | ----- 882 | 883 | The following may not behave as expected. 884 | 885 | ```moon 886 | i = 100 887 | 888 | -- many lines of code... 889 | 890 | my_func = -> 891 | i = 10 -- name clash 892 | while i > 0 893 | print i 894 | i -= 1 895 | 896 | my_func! 897 | 898 | print i -- will print 0?! 899 | ``` 900 | 901 | The reason being that `i` in the function has been seen before, i.e. it is 902 | declared at `i = 100`. This could be fixed by specifying `local i` before 903 | `i = 10` in the function. 904 | 905 | This problem can be avoided by specifying which external variables 906 | we are `using`. Everything else is then declared *local*. 907 | 908 | `using nil` means "using no external variables". 909 | 910 | ```moon 911 | i = 100 912 | 913 | my_func = (using nil) -> 914 | i = "hello" -- a new local variable is created here 915 | 916 | my_func! 917 | print i -- prints 100, i is unaffected 918 | ``` 919 | 920 | ```moon 921 | tmp = 1213 922 | i, k = 100, 50 923 | 924 | my_func = (add using k,i) -> 925 | tmp = tmp + add -- a new local tmp is created 926 | i += tmp -- using external i 927 | k += tmp -- using external k 928 | 929 | my_func(22) 930 | print i,k -- these have been updated 931 | ``` 932 | 933 | 934 | Idioms 935 | ------ 936 | 937 | ### Function stubs 938 | 939 | Functions from objects may be passed around, using a closure. 940 | 941 | ```moon 942 | my_object = { 943 | value: 1000 944 | write: => print "the value:", @value 945 | } 946 | 947 | run_callback = (func) -> 948 | print "running callback..." 949 | func! 950 | 951 | run_callback my_object.write -- fail: function has no reference to my_object 952 | 953 | run_callback my_object\write -- pass: object bundled into a new function 954 | ``` 955 | 956 | 957 | -------------------------------------------------------------------------------- /html/bootstrap.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap v3.3.5 (http://getbootstrap.com) 3 | * Copyright 2011-2015 Twitter, Inc. 4 | * Licensed under the MIT license 5 | */ 6 | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.5",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.5",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.5",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.5",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
    ',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.5",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.5",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.5",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | cheetsheet: 2 | 3 | GNU GENERAL PUBLIC LICENSE 4 | Version 3, 29 June 2007 5 | 6 | Copyright (C) 2007 Free Software Foundation, Inc. 7 | Everyone is permitted to copy and distribute verbatim copies 8 | of this license document, but changing it is not allowed. 9 | 10 | Preamble 11 | 12 | The GNU General Public License is a free, copyleft license for 13 | software and other kinds of works. 14 | 15 | The licenses for most software and other practical works are designed 16 | to take away your freedom to share and change the works. By contrast, 17 | the GNU General Public License is intended to guarantee your freedom to 18 | share and change all versions of a program--to make sure it remains free 19 | software for all its users. We, the Free Software Foundation, use the 20 | GNU General Public License for most of our software; it applies also to 21 | any other work released this way by its authors. You can apply it to 22 | your programs, too. 23 | 24 | When we speak of free software, we are referring to freedom, not 25 | price. Our General Public Licenses are designed to make sure that you 26 | have the freedom to distribute copies of free software (and charge for 27 | them if you wish), that you receive source code or can get it if you 28 | want it, that you can change the software or use pieces of it in new 29 | free programs, and that you know you can do these things. 30 | 31 | To protect your rights, we need to prevent others from denying you 32 | these rights or asking you to surrender the rights. Therefore, you have 33 | certain responsibilities if you distribute copies of the software, or if 34 | you modify it: responsibilities to respect the freedom of others. 35 | 36 | For example, if you distribute copies of such a program, whether 37 | gratis or for a fee, you must pass on to the recipients the same 38 | freedoms that you received. You must make sure that they, too, receive 39 | or can get the source code. And you must show them these terms so they 40 | know their rights. 41 | 42 | Developers that use the GNU GPL protect your rights with two steps: 43 | (1) assert copyright on the software, and (2) offer you this License 44 | giving you legal permission to copy, distribute and/or modify it. 45 | 46 | For the developers' and authors' protection, the GPL clearly explains 47 | that there is no warranty for this free software. For both users' and 48 | authors' sake, the GPL requires that modified versions be marked as 49 | changed, so that their problems will not be attributed erroneously to 50 | authors of previous versions. 51 | 52 | Some devices are designed to deny users access to install or run 53 | modified versions of the software inside them, although the manufacturer 54 | can do so. This is fundamentally incompatible with the aim of 55 | protecting users' freedom to change the software. The systematic 56 | pattern of such abuse occurs in the area of products for individuals to 57 | use, which is precisely where it is most unacceptable. Therefore, we 58 | have designed this version of the GPL to prohibit the practice for those 59 | products. If such problems arise substantially in other domains, we 60 | stand ready to extend this provision to those domains in future versions 61 | of the GPL, as needed to protect the freedom of users. 62 | 63 | Finally, every program is threatened constantly by software patents. 64 | States should not allow patents to restrict development and use of 65 | software on general-purpose computers, but in those that do, we wish to 66 | avoid the special danger that patents applied to a free program could 67 | make it effectively proprietary. To prevent this, the GPL assures that 68 | patents cannot be used to render the program non-free. 69 | 70 | The precise terms and conditions for copying, distribution and 71 | modification follow. 72 | 73 | TERMS AND CONDITIONS 74 | 75 | 0. Definitions. 76 | 77 | "This License" refers to version 3 of the GNU General Public License. 78 | 79 | "Copyright" also means copyright-like laws that apply to other kinds of 80 | works, such as semiconductor masks. 81 | 82 | "The Program" refers to any copyrightable work licensed under this 83 | License. Each licensee is addressed as "you". "Licensees" and 84 | "recipients" may be individuals or organizations. 85 | 86 | To "modify" a work means to copy from or adapt all or part of the work 87 | in a fashion requiring copyright permission, other than the making of an 88 | exact copy. The resulting work is called a "modified version" of the 89 | earlier work or a work "based on" the earlier work. 90 | 91 | A "covered work" means either the unmodified Program or a work based 92 | on the Program. 93 | 94 | To "propagate" a work means to do anything with it that, without 95 | permission, would make you directly or secondarily liable for 96 | infringement under applicable copyright law, except executing it on a 97 | computer or modifying a private copy. Propagation includes copying, 98 | distribution (with or without modification), making available to the 99 | public, and in some countries other activities as well. 100 | 101 | To "convey" a work means any kind of propagation that enables other 102 | parties to make or receive copies. Mere interaction with a user through 103 | a computer network, with no transfer of a copy, is not conveying. 104 | 105 | An interactive user interface displays "Appropriate Legal Notices" 106 | to the extent that it includes a convenient and prominently visible 107 | feature that (1) displays an appropriate copyright notice, and (2) 108 | tells the user that there is no warranty for the work (except to the 109 | extent that warranties are provided), that licensees may convey the 110 | work under this License, and how to view a copy of this License. If 111 | the interface presents a list of user commands or options, such as a 112 | menu, a prominent item in the list meets this criterion. 113 | 114 | 1. Source Code. 115 | 116 | The "source code" for a work means the preferred form of the work 117 | for making modifications to it. "Object code" means any non-source 118 | form of a work. 119 | 120 | A "Standard Interface" means an interface that either is an official 121 | standard defined by a recognized standards body, or, in the case of 122 | interfaces specified for a particular programming language, one that 123 | is widely used among developers working in that language. 124 | 125 | The "System Libraries" of an executable work include anything, other 126 | than the work as a whole, that (a) is included in the normal form of 127 | packaging a Major Component, but which is not part of that Major 128 | Component, and (b) serves only to enable use of the work with that 129 | Major Component, or to implement a Standard Interface for which an 130 | implementation is available to the public in source code form. A 131 | "Major Component", in this context, means a major essential component 132 | (kernel, window system, and so on) of the specific operating system 133 | (if any) on which the executable work runs, or a compiler used to 134 | produce the work, or an object code interpreter used to run it. 135 | 136 | The "Corresponding Source" for a work in object code form means all 137 | the source code needed to generate, install, and (for an executable 138 | work) run the object code and to modify the work, including scripts to 139 | control those activities. However, it does not include the work's 140 | System Libraries, or general-purpose tools or generally available free 141 | programs which are used unmodified in performing those activities but 142 | which are not part of the work. For example, Corresponding Source 143 | includes interface definition files associated with source files for 144 | the work, and the source code for shared libraries and dynamically 145 | linked subprograms that the work is specifically designed to require, 146 | such as by intimate data communication or control flow between those 147 | subprograms and other parts of the work. 148 | 149 | The Corresponding Source need not include anything that users 150 | can regenerate automatically from other parts of the Corresponding 151 | Source. 152 | 153 | The Corresponding Source for a work in source code form is that 154 | same work. 155 | 156 | 2. Basic Permissions. 157 | 158 | All rights granted under this License are granted for the term of 159 | copyright on the Program, and are irrevocable provided the stated 160 | conditions are met. This License explicitly affirms your unlimited 161 | permission to run the unmodified Program. The output from running a 162 | covered work is covered by this License only if the output, given its 163 | content, constitutes a covered work. This License acknowledges your 164 | rights of fair use or other equivalent, as provided by copyright law. 165 | 166 | You may make, run and propagate covered works that you do not 167 | convey, without conditions so long as your license otherwise remains 168 | in force. You may convey covered works to others for the sole purpose 169 | of having them make modifications exclusively for you, or provide you 170 | with facilities for running those works, provided that you comply with 171 | the terms of this License in conveying all material for which you do 172 | not control copyright. Those thus making or running the covered works 173 | for you must do so exclusively on your behalf, under your direction 174 | and control, on terms that prohibit them from making any copies of 175 | your copyrighted material outside their relationship with you. 176 | 177 | Conveying under any other circumstances is permitted solely under 178 | the conditions stated below. Sublicensing is not allowed; section 10 179 | makes it unnecessary. 180 | 181 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 182 | 183 | No covered work shall be deemed part of an effective technological 184 | measure under any applicable law fulfilling obligations under article 185 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 186 | similar laws prohibiting or restricting circumvention of such 187 | measures. 188 | 189 | When you convey a covered work, you waive any legal power to forbid 190 | circumvention of technological measures to the extent such circumvention 191 | is effected by exercising rights under this License with respect to 192 | the covered work, and you disclaim any intention to limit operation or 193 | modification of the work as a means of enforcing, against the work's 194 | users, your or third parties' legal rights to forbid circumvention of 195 | technological measures. 196 | 197 | 4. Conveying Verbatim Copies. 198 | 199 | You may convey verbatim copies of the Program's source code as you 200 | receive it, in any medium, provided that you conspicuously and 201 | appropriately publish on each copy an appropriate copyright notice; 202 | keep intact all notices stating that this License and any 203 | non-permissive terms added in accord with section 7 apply to the code; 204 | keep intact all notices of the absence of any warranty; and give all 205 | recipients a copy of this License along with the Program. 206 | 207 | You may charge any price or no price for each copy that you convey, 208 | and you may offer support or warranty protection for a fee. 209 | 210 | 5. Conveying Modified Source Versions. 211 | 212 | You may convey a work based on the Program, or the modifications to 213 | produce it from the Program, in the form of source code under the 214 | terms of section 4, provided that you also meet all of these conditions: 215 | 216 | a) The work must carry prominent notices stating that you modified 217 | it, and giving a relevant date. 218 | 219 | b) The work must carry prominent notices stating that it is 220 | released under this License and any conditions added under section 221 | 7. This requirement modifies the requirement in section 4 to 222 | "keep intact all notices". 223 | 224 | c) You must license the entire work, as a whole, under this 225 | License to anyone who comes into possession of a copy. This 226 | License will therefore apply, along with any applicable section 7 227 | additional terms, to the whole of the work, and all its parts, 228 | regardless of how they are packaged. This License gives no 229 | permission to license the work in any other way, but it does not 230 | invalidate such permission if you have separately received it. 231 | 232 | d) If the work has interactive user interfaces, each must display 233 | Appropriate Legal Notices; however, if the Program has interactive 234 | interfaces that do not display Appropriate Legal Notices, your 235 | work need not make them do so. 236 | 237 | A compilation of a covered work with other separate and independent 238 | works, which are not by their nature extensions of the covered work, 239 | and which are not combined with it such as to form a larger program, 240 | in or on a volume of a storage or distribution medium, is called an 241 | "aggregate" if the compilation and its resulting copyright are not 242 | used to limit the access or legal rights of the compilation's users 243 | beyond what the individual works permit. Inclusion of a covered work 244 | in an aggregate does not cause this License to apply to the other 245 | parts of the aggregate. 246 | 247 | 6. Conveying Non-Source Forms. 248 | 249 | You may convey a covered work in object code form under the terms 250 | of sections 4 and 5, provided that you also convey the 251 | machine-readable Corresponding Source under the terms of this License, 252 | in one of these ways: 253 | 254 | a) Convey the object code in, or embodied in, a physical product 255 | (including a physical distribution medium), accompanied by the 256 | Corresponding Source fixed on a durable physical medium 257 | customarily used for software interchange. 258 | 259 | b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the 269 | Corresponding Source from a network server at no charge. 270 | 271 | c) Convey individual copies of the object code with a copy of the 272 | written offer to provide the Corresponding Source. This 273 | alternative is allowed only occasionally and noncommercially, and 274 | only if you received the object code with such an offer, in accord 275 | with subsection 6b. 276 | 277 | d) Convey the object code by offering access from a designated 278 | place (gratis or for a charge), and offer equivalent access to the 279 | Corresponding Source in the same way through the same place at no 280 | further charge. You need not require recipients to copy the 281 | Corresponding Source along with the object code. If the place to 282 | copy the object code is a network server, the Corresponding Source 283 | may be on a different server (operated by you or a third party) 284 | that supports equivalent copying facilities, provided you maintain 285 | clear directions next to the object code saying where to find the 286 | Corresponding Source. Regardless of what server hosts the 287 | Corresponding Source, you remain obligated to ensure that it is 288 | available for as long as needed to satisfy these requirements. 289 | 290 | e) Convey the object code using peer-to-peer transmission, provided 291 | you inform other peers where the object code and Corresponding 292 | Source of the work are being offered to the general public at no 293 | charge under subsection 6d. 294 | 295 | A separable portion of the object code, whose source code is excluded 296 | from the Corresponding Source as a System Library, need not be 297 | included in conveying the object code work. 298 | 299 | A "User Product" is either (1) a "consumer product", which means any 300 | tangible personal property which is normally used for personal, family, 301 | or household purposes, or (2) anything designed or sold for incorporation 302 | into a dwelling. In determining whether a product is a consumer product, 303 | doubtful cases shall be resolved in favor of coverage. For a particular 304 | product received by a particular user, "normally used" refers to a 305 | typical or common use of that class of product, regardless of the status 306 | of the particular user or of the way in which the particular user 307 | actually uses, or expects or is expected to use, the product. A product 308 | is a consumer product regardless of whether the product has substantial 309 | commercial, industrial or non-consumer uses, unless such uses represent 310 | the only significant mode of use of the product. 311 | 312 | "Installation Information" for a User Product means any methods, 313 | procedures, authorization keys, or other information required to install 314 | and execute modified versions of a covered work in that User Product from 315 | a modified version of its Corresponding Source. The information must 316 | suffice to ensure that the continued functioning of the modified object 317 | code is in no case prevented or interfered with solely because 318 | modification has been made. 319 | 320 | If you convey an object code work under this section in, or with, or 321 | specifically for use in, a User Product, and the conveying occurs as 322 | part of a transaction in which the right of possession and use of the 323 | User Product is transferred to the recipient in perpetuity or for a 324 | fixed term (regardless of how the transaction is characterized), the 325 | Corresponding Source conveyed under this section must be accompanied 326 | by the Installation Information. But this requirement does not apply 327 | if neither you nor any third party retains the ability to install 328 | modified object code on the User Product (for example, the work has 329 | been installed in ROM). 330 | 331 | The requirement to provide Installation Information does not include a 332 | requirement to continue to provide support service, warranty, or updates 333 | for a work that has been modified or installed by the recipient, or for 334 | the User Product in which it has been modified or installed. Access to a 335 | network may be denied when the modification itself materially and 336 | adversely affects the operation of the network or violates the rules and 337 | protocols for communication across the network. 338 | 339 | Corresponding Source conveyed, and Installation Information provided, 340 | in accord with this section must be in a format that is publicly 341 | documented (and with an implementation available to the public in 342 | source code form), and must require no special password or key for 343 | unpacking, reading or copying. 344 | 345 | 7. Additional Terms. 346 | 347 | "Additional permissions" are terms that supplement the terms of this 348 | License by making exceptions from one or more of its conditions. 349 | Additional permissions that are applicable to the entire Program shall 350 | be treated as though they were included in this License, to the extent 351 | that they are valid under applicable law. If additional permissions 352 | apply only to part of the Program, that part may be used separately 353 | under those permissions, but the entire Program remains governed by 354 | this License without regard to the additional permissions. 355 | 356 | When you convey a copy of a covered work, you may at your option 357 | remove any additional permissions from that copy, or from any part of 358 | it. (Additional permissions may be written to require their own 359 | removal in certain cases when you modify the work.) You may place 360 | additional permissions on material, added by you to a covered work, 361 | for which you have or can give appropriate copyright permission. 362 | 363 | Notwithstanding any other provision of this License, for material you 364 | add to a covered work, you may (if authorized by the copyright holders of 365 | that material) supplement the terms of this License with terms: 366 | 367 | a) Disclaiming warranty or limiting liability differently from the 368 | terms of sections 15 and 16 of this License; or 369 | 370 | b) Requiring preservation of specified reasonable legal notices or 371 | author attributions in that material or in the Appropriate Legal 372 | Notices displayed by works containing it; or 373 | 374 | c) Prohibiting misrepresentation of the origin of that material, or 375 | requiring that modified versions of such material be marked in 376 | reasonable ways as different from the original version; or 377 | 378 | d) Limiting the use for publicity purposes of names of licensors or 379 | authors of the material; or 380 | 381 | e) Declining to grant rights under trademark law for use of some 382 | trade names, trademarks, or service marks; or 383 | 384 | f) Requiring indemnification of licensors and authors of that 385 | material by anyone who conveys the material (or modified versions of 386 | it) with contractual assumptions of liability to the recipient, for 387 | any liability that these contractual assumptions directly impose on 388 | those licensors and authors. 389 | 390 | All other non-permissive additional terms are considered "further 391 | restrictions" within the meaning of section 10. If the Program as you 392 | received it, or any part of it, contains a notice stating that it is 393 | governed by this License along with a term that is a further 394 | restriction, you may remove that term. If a license document contains 395 | a further restriction but permits relicensing or conveying under this 396 | License, you may add to a covered work material governed by the terms 397 | of that license document, provided that the further restriction does 398 | not survive such relicensing or conveying. 399 | 400 | If you add terms to a covered work in accord with this section, you 401 | must place, in the relevant source files, a statement of the 402 | additional terms that apply to those files, or a notice indicating 403 | where to find the applicable terms. 404 | 405 | Additional terms, permissive or non-permissive, may be stated in the 406 | form of a separately written license, or stated as exceptions; 407 | the above requirements apply either way. 408 | 409 | 8. Termination. 410 | 411 | You may not propagate or modify a covered work except as expressly 412 | provided under this License. Any attempt otherwise to propagate or 413 | modify it is void, and will automatically terminate your rights under 414 | this License (including any patent licenses granted under the third 415 | paragraph of section 11). 416 | 417 | However, if you cease all violation of this License, then your 418 | license from a particular copyright holder is reinstated (a) 419 | provisionally, unless and until the copyright holder explicitly and 420 | finally terminates your license, and (b) permanently, if the copyright 421 | holder fails to notify you of the violation by some reasonable means 422 | prior to 60 days after the cessation. 423 | 424 | Moreover, your license from a particular copyright holder is 425 | reinstated permanently if the copyright holder notifies you of the 426 | violation by some reasonable means, this is the first time you have 427 | received notice of violation of this License (for any work) from that 428 | copyright holder, and you cure the violation prior to 30 days after 429 | your receipt of the notice. 430 | 431 | Termination of your rights under this section does not terminate the 432 | licenses of parties who have received copies or rights from you under 433 | this License. If your rights have been terminated and not permanently 434 | reinstated, you do not qualify to receive new licenses for the same 435 | material under section 10. 436 | 437 | 9. Acceptance Not Required for Having Copies. 438 | 439 | You are not required to accept this License in order to receive or 440 | run a copy of the Program. Ancillary propagation of a covered work 441 | occurring solely as a consequence of using peer-to-peer transmission 442 | to receive a copy likewise does not require acceptance. However, 443 | nothing other than this License grants you permission to propagate or 444 | modify any covered work. These actions infringe copyright if you do 445 | not accept this License. Therefore, by modifying or propagating a 446 | covered work, you indicate your acceptance of this License to do so. 447 | 448 | 10. Automatic Licensing of Downstream Recipients. 449 | 450 | Each time you convey a covered work, the recipient automatically 451 | receives a license from the original licensors, to run, modify and 452 | propagate that work, subject to this License. You are not responsible 453 | for enforcing compliance by third parties with this License. 454 | 455 | An "entity transaction" is a transaction transferring control of an 456 | organization, or substantially all assets of one, or subdividing an 457 | organization, or merging organizations. If propagation of a covered 458 | work results from an entity transaction, each party to that 459 | transaction who receives a copy of the work also receives whatever 460 | licenses to the work the party's predecessor in interest had or could 461 | give under the previous paragraph, plus a right to possession of the 462 | Corresponding Source of the work from the predecessor in interest, if 463 | the predecessor has it or can get it with reasonable efforts. 464 | 465 | You may not impose any further restrictions on the exercise of the 466 | rights granted or affirmed under this License. For example, you may 467 | not impose a license fee, royalty, or other charge for exercise of 468 | rights granted under this License, and you may not initiate litigation 469 | (including a cross-claim or counterclaim in a lawsuit) alleging that 470 | any patent claim is infringed by making, using, selling, offering for 471 | sale, or importing the Program or any portion of it. 472 | 473 | 11. Patents. 474 | 475 | A "contributor" is a copyright holder who authorizes use under this 476 | License of the Program or a work on which the Program is based. The 477 | work thus licensed is called the contributor's "contributor version". 478 | 479 | A contributor's "essential patent claims" are all patent claims 480 | owned or controlled by the contributor, whether already acquired or 481 | hereafter acquired, that would be infringed by some manner, permitted 482 | by this License, of making, using, or selling its contributor version, 483 | but do not include claims that would be infringed only as a 484 | consequence of further modification of the contributor version. For 485 | purposes of this definition, "control" includes the right to grant 486 | patent sublicenses in a manner consistent with the requirements of 487 | this License. 488 | 489 | Each contributor grants you a non-exclusive, worldwide, royalty-free 490 | patent license under the contributor's essential patent claims, to 491 | make, use, sell, offer for sale, import and otherwise run, modify and 492 | propagate the contents of its contributor version. 493 | 494 | In the following three paragraphs, a "patent license" is any express 495 | agreement or commitment, however denominated, not to enforce a patent 496 | (such as an express permission to practice a patent or covenant not to 497 | sue for patent infringement). To "grant" such a patent license to a 498 | party means to make such an agreement or commitment not to enforce a 499 | patent against the party. 500 | 501 | If you convey a covered work, knowingly relying on a patent license, 502 | and the Corresponding Source of the work is not available for anyone 503 | to copy, free of charge and under the terms of this License, through a 504 | publicly available network server or other readily accessible means, 505 | then you must either (1) cause the Corresponding Source to be so 506 | available, or (2) arrange to deprive yourself of the benefit of the 507 | patent license for this particular work, or (3) arrange, in a manner 508 | consistent with the requirements of this License, to extend the patent 509 | license to downstream recipients. "Knowingly relying" means you have 510 | actual knowledge that, but for the patent license, your conveying the 511 | covered work in a country, or your recipient's use of the covered work 512 | in a country, would infringe one or more identifiable patents in that 513 | country that you have reason to believe are valid. 514 | 515 | If, pursuant to or in connection with a single transaction or 516 | arrangement, you convey, or propagate by procuring conveyance of, a 517 | covered work, and grant a patent license to some of the parties 518 | receiving the covered work authorizing them to use, propagate, modify 519 | or convey a specific copy of the covered work, then the patent license 520 | you grant is automatically extended to all recipients of the covered 521 | work and works based on it. 522 | 523 | A patent license is "discriminatory" if it does not include within 524 | the scope of its coverage, prohibits the exercise of, or is 525 | conditioned on the non-exercise of one or more of the rights that are 526 | specifically granted under this License. You may not convey a covered 527 | work if you are a party to an arrangement with a third party that is 528 | in the business of distributing software, under which you make payment 529 | to the third party based on the extent of your activity of conveying 530 | the work, and under which the third party grants, to any of the 531 | parties who would receive the covered work from you, a discriminatory 532 | patent license (a) in connection with copies of the covered work 533 | conveyed by you (or copies made from those copies), or (b) primarily 534 | for and in connection with specific products or compilations that 535 | contain the covered work, unless you entered into that arrangement, 536 | or that patent license was granted, prior to 28 March 2007. 537 | 538 | Nothing in this License shall be construed as excluding or limiting 539 | any implied license or other defenses to infringement that may 540 | otherwise be available to you under applicable patent law. 541 | 542 | 12. No Surrender of Others' Freedom. 543 | 544 | If conditions are imposed on you (whether by court order, agreement or 545 | otherwise) that contradict the conditions of this License, they do not 546 | excuse you from the conditions of this License. If you cannot convey a 547 | covered work so as to satisfy simultaneously your obligations under this 548 | License and any other pertinent obligations, then as a consequence you may 549 | not convey it at all. For example, if you agree to terms that obligate you 550 | to collect a royalty for further conveying from those to whom you convey 551 | the Program, the only way you could satisfy both those terms and this 552 | License would be to refrain entirely from conveying the Program. 553 | 554 | 13. Use with the GNU Affero General Public License. 555 | 556 | Notwithstanding any other provision of this License, you have 557 | permission to link or combine any covered work with a work licensed 558 | under version 3 of the GNU Affero General Public License into a single 559 | combined work, and to convey the resulting work. The terms of this 560 | License will continue to apply to the part which is the covered work, 561 | but the special requirements of the GNU Affero General Public License, 562 | section 13, concerning interaction through a network will apply to the 563 | combination as such. 564 | 565 | 14. Revised Versions of this License. 566 | 567 | The Free Software Foundation may publish revised and/or new versions of 568 | the GNU General Public License from time to time. Such new versions will 569 | be similar in spirit to the present version, but may differ in detail to 570 | address new problems or concerns. 571 | 572 | Each version is given a distinguishing version number. If the 573 | Program specifies that a certain numbered version of the GNU General 574 | Public License "or any later version" applies to it, you have the 575 | option of following the terms and conditions either of that numbered 576 | version or of any later version published by the Free Software 577 | Foundation. If the Program does not specify a version number of the 578 | GNU General Public License, you may choose any version ever published 579 | by the Free Software Foundation. 580 | 581 | If the Program specifies that a proxy can decide which future 582 | versions of the GNU General Public License can be used, that proxy's 583 | public statement of acceptance of a version permanently authorizes you 584 | to choose that version for the Program. 585 | 586 | Later license versions may give you additional or different 587 | permissions. However, no additional obligations are imposed on any 588 | author or copyright holder as a result of your choosing to follow a 589 | later version. 590 | 591 | 15. Disclaimer of Warranty. 592 | 593 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 594 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 595 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 596 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 597 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 598 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 599 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 600 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 601 | 602 | 16. Limitation of Liability. 603 | 604 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 605 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 606 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 607 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 608 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 609 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 610 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 611 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 612 | SUCH DAMAGES. 613 | 614 | 17. Interpretation of Sections 15 and 16. 615 | 616 | If the disclaimer of warranty and limitation of liability provided 617 | above cannot be given local legal effect according to their terms, 618 | reviewing courts shall apply local law that most closely approximates 619 | an absolute waiver of all civil liability in connection with the 620 | Program, unless a warranty or assumption of liability accompanies a 621 | copy of the Program in return for a fee. 622 | 623 | END OF TERMS AND CONDITIONS 624 | 625 | How to Apply These Terms to Your New Programs 626 | 627 | If you develop a new program, and you want it to be of the greatest 628 | possible use to the public, the best way to achieve this is to make it 629 | free software which everyone can redistribute and change under these terms. 630 | 631 | To do so, attach the following notices to the program. It is safest 632 | to attach them to the start of each source file to most effectively 633 | state the exclusion of warranty; and each file should have at least 634 | the "copyright" line and a pointer to where the full notice is found. 635 | 636 | 637 | Copyright (C) 638 | 639 | This program is free software: you can redistribute it and/or modify 640 | it under the terms of the GNU General Public License as published by 641 | the Free Software Foundation, either version 3 of the License, or 642 | (at your option) any later version. 643 | 644 | This program is distributed in the hope that it will be useful, 645 | but WITHOUT ANY WARRANTY; without even the implied warranty of 646 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 647 | GNU General Public License for more details. 648 | 649 | You should have received a copy of the GNU General Public License 650 | along with this program. If not, see . 651 | 652 | Also add information on how to contact you by electronic and paper mail. 653 | 654 | If the program does terminal interaction, make it output a short 655 | notice like this when it starts in an interactive mode: 656 | 657 | Copyright (C) 658 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 659 | This is free software, and you are welcome to redistribute it 660 | under certain conditions; type `show c' for details. 661 | 662 | The hypothetical commands `show w' and `show c' should show the appropriate 663 | parts of the General Public License. Of course, your program's commands 664 | might be different; for a GUI interface, you would use an "about box". 665 | 666 | You should also get your employer (if you work as a programmer) or school, 667 | if any, to sign a "copyright disclaimer" for the program, if necessary. 668 | For more information on this, and how to apply and follow the GNU GPL, see 669 | . 670 | 671 | The GNU General Public License does not permit incorporating your program 672 | into proprietary programs. If your program is a subroutine library, you 673 | may consider it more useful to permit linking proprietary applications with 674 | the library. If this is what you want to do, use the GNU Lesser General 675 | Public License instead of this License. But first, please read 676 | . 677 | 678 | ------------------------------------------------------------------------------- 679 | JQuery: https://jquery.org/license/ 680 | 681 | he MIT License (MIT) 682 | 683 | Copyright (c) 2015 jQuery 684 | 685 | Permission is hereby granted, free of charge, to any person obtaining a copy 686 | of this software and associated documentation files (the "Software"), to deal 687 | in the Software without restriction, including without limitation the rights 688 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 689 | copies of the Software, and to permit persons to whom the Software is 690 | furnished to do so, subject to the following conditions: 691 | 692 | The above copyright notice and this permission notice shall be included in all 693 | copies or substantial portions of the Software. 694 | 695 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 696 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 697 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 698 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 699 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 700 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 701 | SOFTWARE. 702 | 703 | ------------------------------------------------------------------------------- 704 | Bootstrap: 705 | 706 | ## Copyright and Licensing 707 | Copyright 2013 Jonathan Miles 708 | 709 | Licensed under the Apache License, Version 2.0 (the "License"); 710 | you may not use this file except in compliance with the License. 711 | You may obtain a copy of the License at 712 | 713 | Unless required by applicable law or agreed to in writing, software 714 | distributed under the License is distributed on an "AS IS" BASIS, 715 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 716 | See the License for the specific language governing permissions and 717 | limitations under the License. 718 | 719 | ------------------------------------------------------------------------------- 720 | Marked: 721 | 722 | Copyright (c) 2011-2014, Christopher Jeffrey (https://github.com/chjj/) 723 | 724 | Permission is hereby granted, free of charge, to any person obtaining a copy 725 | of this software and associated documentation files (the "Software"), to deal 726 | in the Software without restriction, including without limitation the rights 727 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 728 | copies of the Software, and to permit persons to whom the Software is 729 | furnished to do so, subject to the following conditions: 730 | 731 | The above copyright notice and this permission notice shall be included in 732 | all copies or substantial portions of the Software. 733 | 734 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 735 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 736 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 737 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 738 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 739 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 740 | THE SOFTWARE. 741 | 742 | ------------------------------------------------------------------------------- 743 | Highlight: 744 | 745 | Copyright (c) 2006, Ivan Sagalaev 746 | All rights reserved. 747 | Redistribution and use in source and binary forms, with or without 748 | modification, are permitted provided that the following conditions are met: 749 | 750 | * Redistributions of source code must retain the above copyright 751 | notice, this list of conditions and the following disclaimer. 752 | * Redistributions in binary form must reproduce the above copyright 753 | notice, this list of conditions and the following disclaimer in the 754 | documentation and/or other materials provided with the distribution. 755 | * Neither the name of highlight.js nor the names of its contributors 756 | may be used to endorse or promote products derived from this software 757 | without specific prior written permission. 758 | 759 | THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY 760 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 761 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 762 | DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY 763 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 764 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 765 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 766 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 767 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 768 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 769 | 770 | ------------------------------------------------------------------------------- 771 | js-yaml: 772 | 773 | (The MIT License) 774 | 775 | Copyright (C) 2011-2015 by Vitaly Puzrin 776 | 777 | Permission is hereby granted, free of charge, to any person obtaining a copy 778 | of this software and associated documentation files (the "Software"), to deal 779 | in the Software without restriction, including without limitation the rights 780 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 781 | copies of the Software, and to permit persons to whom the Software is 782 | furnished to do so, subject to the following conditions: 783 | 784 | The above copyright notice and this permission notice shall be included in 785 | all copies or substantial portions of the Software. 786 | 787 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 788 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 789 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 790 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 791 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 792 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 793 | THE SOFTWARE. 794 | --------------------------------------------------------------------------------