756 Commits

Author SHA1 Message Date
anushka-23g b6892fd2f0 Merge 4ddc319a03 into 10872e02d1 2024-06-20 21:03:53 +00:00
Julien Le Coupanec 10872e02d1 Merge pull request #385 from WPRobson/master
add docker init command to docker cheatsheet
2024-06-07 23:35:19 +02:00
Julien Le Coupanec 365b4f72b7 Merge pull request #390 from MagedMohamedTurk/patch-1
Update C.txt
2024-06-07 23:34:57 +02:00
Maged Turkoman 0f74ebe37b Update C.txt 2024-06-01 09:07:47 +03:00
Will Robson bf4c0379f2 add docker init command to docker cheatsheet 2024-05-12 20:01:26 +01:00
Julien Le Coupanec 2aee46f169 Merge pull request #381 from FabricioLopees/fix/java
Update readme: fix grammatical error in java.md
2024-04-15 10:53:51 +02:00
FabricioLopees 22977d5ca1 update readme: fix grammatical error in java.md 2024-04-13 13:05:38 -03:00
FabricioLopees a2c99c9674 update readme: fix grammatical error in java.md 2024-04-13 12:52:16 -03:00
Julien Le Coupanec 559d03ecf3 Merge pull request #372 from cunnellp5/cunnellp/vscode/add-command-and-cleanup-spaces
updates vscode cheat sheet
2024-02-26 18:25:32 +01:00
cunnellp5 bea751612a updates vscode cheat sheet with one command 2024-02-15 07:10:18 -07:00
anushka-23g 4ddc319a03 Update README.md- Add Pieces
Pieces is an on-device copilot that helps you capture, enrich, and reuse useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your workflow.
2024-02-06 16:06:39 +05:30
Julien Le Coupanec d143c60246 Merge pull request #354 from RomjanHossain/patch-1
swap current line with previous
2023-12-29 15:35:14 +01:00
Romjan D. Hossain 44371217a9 swap current line with previous
it should be `ddkP` instead of `ddkp`
2023-12-24 11:53:04 +06:00
Julien Le Coupanec d63d75bb28 Merge pull request #350 from adgan11/patch-1
Fix Issue #316: keygen deprecated
2023-11-07 11:40:11 +01:00
Ahmed Gagan 94087440e5 Fix Issue #316: keygen deprecated 2023-11-06 12:16:17 +05:30
Julien Le Coupanec 8557d4f3d8 Merge pull request #337 from phaneendra24/adding-js-arrayMethod
adding the at() method
2023-07-11 12:20:48 +02:00
phaneendra f8d75a7ccf adding the at method 2023-07-07 16:49:20 +05:30
Julien Le Coupanec 5ff48033e1 Merge pull request #304 from sangeethkc/master
new laravel artisan commands added
2023-06-26 22:00:00 +02:00
SANGEETH 6c3b6ee90e Merge branch 'LeCoupa:master' into master 2023-06-26 15:24:39 +05:30
Julien Le Coupanec 7e9e6af408 Merge pull request #334 from samyak003/master
Added cheatsheet for Firebase CLI
2023-06-19 12:59:07 +02:00
Samyak 0ee3753e2f Added cheatsheet for Firebase CLI 2023-06-18 19:58:27 +05:30
Julien Le Coupanec dd94d3aa70 docs(nginx): tail logs to inspect requests 2023-05-31 16:13:26 +02:00
Julien Le Coupanec 8ec2267167 docs: remove youtube promotion for the time being 2022-12-30 20:31:32 +01:00
sangeethkc cb9ca87a4b new laravel commands added 2022-10-18 15:27:14 +05:30
Julien Le Coupanec ec7afa056b Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2022-08-28 21:08:14 +02:00
Julien Le Coupanec 47ff229fcd docs: update ubuntu 2022-08-28 21:08:12 +02:00
Julien Le Coupanec 4c1540a448 docs: readme 2022-08-28 21:08:02 +02:00
Julien Le Coupanec 5bbef08e46 Merge pull request #293 from EhtashamHaider/master
update html5.html
2022-08-26 17:36:21 +02:00
Julien Le Coupanec bf8cc22dae Merge pull request #294 from mhemanthkmr/patch-1
added rm -f in docker.sh
2022-08-18 21:47:44 +02:00
HemanthKumar M b095a3534d added rm -f in docker.sh
Kindly Verify it
2022-08-05 15:31:25 +05:30
Ehtasham Haider 463d563edf update html5.html
Added an ins tag that is good for writing the content that has been inserted into the document. Browser will automatically underline this text
2022-08-01 12:47:00 +05:00
Julien Le Coupanec 6f67bf688e Merge pull request #290 from Technical-Shubham-tech/css3-added
Created cheatsheet for CSS3
2022-07-12 08:33:20 +02:00
Julien Le Coupanec 335c178141 Merge pull request #292 from simonardejr/patch-1
removing php version
2022-07-06 11:12:11 +02:00
Julien Le Coupanec 313ecb8d53 Merge pull request #284 from mdambro/patch-1
Update java.md
2022-07-06 11:11:02 +02:00
Julien Le Coupanec 936500c032 Merge pull request #286 from codemonkey85/patch-1
Fix a typo
2022-07-06 11:10:33 +02:00
Julien Le Coupanec 908e4a11c7 Merge pull request #287 from ozayman/patch-1
UPDATE
2022-07-06 11:10:16 +02:00
Simonarde Lima 153d665c53 removing php version
str_replace it's been around since php 4 ( https://www.php.net/manual/pt_BR/function.str-replace.php ) 😁
2022-07-01 07:13:44 -03:00
Sanidhya Kr. Verma ab8f391f60 created cheatsheet for CSS3 2022-06-10 22:43:19 +05:30
Olindo Zaman 7c9fb9e945 UPDATE 2022-05-27 13:17:42 +06:00
Michael Bond 28c89f1a3b Fix a typo 2022-05-25 08:39:25 -04:00
Matías D'Ambrosio eb59197c8d Update java.md
Add data types and assignment statements.
2022-05-11 12:49:19 -03:00
Julien Le Coupanec 2137ac0559 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2022-04-15 22:01:16 +02:00
Julien Le Coupanec 5b44f78be2 build: set up commitlint 2022-04-15 22:01:00 +02:00
Julien Le Coupanec 44727dec60 Merge pull request #278 from MikeGalyen/main
adds a space between 'go' and 'to' on line 15 and and delete the void…
2022-04-11 11:41:06 +02:00
mike bb482c05bb adds a space between 'go' and 'to' on line 15 and and delete the void modifier on lines 64, 65, and 66 2022-04-04 01:07:48 -04:00
Julien Le Coupanec d85a74febf docs: search processes 2022-03-06 20:00:44 +01:00
Julien Le Coupanec a8b0e9978c docs: search and kill process 2022-03-06 20:00:38 +01:00
Julien Le Coupanec 8dac93f947 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2022-02-23 16:08:52 +01:00
Julien Le Coupanec 30566a3a9f docs: resize volume 2022-02-23 16:08:50 +01:00
Julien Le Coupanec 4c3bde64f9 docs: update readme 2022-01-22 11:38:46 +01:00
Julien Le Coupanec c197c1e906 Merge pull request #263 from ekramasif/patch-1
Contributors Added on README.md
2022-01-22 11:37:55 +01:00
Julien Le Coupanec 3bd1097f99 Merge pull request #265 from haroldao/master 2022-01-21 00:56:41 +01:00
Harold AO 3b578313c3 strike replaced by del (strike is obsolete) 2022-01-17 20:55:47 +01:00
Ekram Asif 9edc51c045 Contributors Added on README.md 2022-01-02 00:11:24 +06:00
Julien Le Coupanec c958d3b39a Merge pull request #261 from AnuragSharma122/patch-1
I have added a part of database in this file
2021-12-21 16:18:08 +01:00
AnuragSharma122 8b92343e9e I have added a part of database in this file 2021-12-21 18:19:54 +05:30
Julien Le Coupanec 13b8d8b72d Merge pull request #246 from el-abdel/master
Added mongoDB cheatSheet
2021-12-18 17:02:53 +01:00
Julien Le Coupanec 94a3376844 Merge pull request #252 from JuGid/master
More PHP elements
2021-12-18 17:01:46 +01:00
Julien Le Coupanec 4ea99284cb Merge pull request #254 from VesitoDev/master
added shortcuts in vscode.md (more info in deskcription)
2021-12-18 17:00:32 +01:00
Julien Le Coupanec 92c29be4bb Merge pull request #253 from rparwaiz/patch-3
Update bash.sh
2021-12-18 17:00:02 +01:00
Julien Le Coupanec c84099568f Merge pull request #255 from sheikhhaziq/master
Update javascript.js
2021-12-18 12:19:48 +01:00
Julien Le Coupanec e72dd6a956 Merge pull request #258 from rparwaiz/patch-6
Update bash.sh
2021-12-12 22:46:46 +01:00
Julien Le Coupanec 3028f3ba76 Merge pull request #256 from rparwaiz/patch-4
Update bash.sh
2021-12-12 22:46:08 +01:00
Julien Le Coupanec 55afd60d33 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2021-12-09 19:58:00 +01:00
Julien Le Coupanec fdb11164f1 docs: List last 100 logs for specific service 2021-12-09 19:57:58 +01:00
rparwaiz 4c1da007c0 Update bash.sh 2021-12-09 15:59:43 +00:00
rparwaiz acb515c171 Update bash.sh
typeset -l <x>                 # makes variable local - <x> must be an interger

declare -l                   # uppercase values in the variable are converted to lowercase
declare -A                   # makes it an associative array
2021-12-07 16:53:56 +00:00
Sheikh Haziq c245e58730 Update javascript.js 2021-12-07 20:34:25 +05:30
El. Abdellah 1b6b59947a Merge branch 'LeCoupa:master' into master 2021-12-07 15:40:55 +01:00
VesitoDev 6b29cb5c71 added shortcuts in vscode.md (more info in deskcription)
added general and basic editing shortcuts for vs code. I added those in the Linux category, I am not sure if they are the same for other OSs but in my resources, they said they are for Linux so if there are mistakes please correct them. Also, let me know if I should add more shortcuts.
2021-12-02 15:35:56 +02:00
rparwaiz 7c9ebfc0be Update bash.sh 2021-12-02 11:08:52 +00:00
Jugid d5b2d4abb6 Some more 2021-12-01 23:04:16 +01:00
Jugid 014126e4d7 More PHP elements 2021-12-01 22:45:46 +01:00
Julien Le Coupanec cc3cb1bc11 Merge pull request #251 from rparwaiz/patch-2
Update bash.sh
2021-12-01 18:13:11 +01:00
rparwaiz 08ad0bea19 Update bash.sh 2021-12-01 17:11:42 +00:00
Julien Le Coupanec e1e779509c Merge pull request #248 from VesitoDev/master
added ":w" to exiting
2021-12-01 16:25:58 +01:00
VesitoDev 45dc3252bb added ":w" to exiting 2021-11-29 19:50:57 +02:00
Julien Le Coupanec 32d5770fb4 Merge pull request #247 from dave-hay/patch-1
Typo + General Formatting
2021-11-21 00:46:16 +01:00
David Hay 271d4ef931 Typo + General Formatting
CTRAL+A > CTRL+A
2021-11-17 23:16:34 -08:00
El. Abdellah 734a77342f Added mongoDB cheatSheet 2021-11-12 11:28:07 +01:00
Julien Le Coupanec d7fb65e5c5 Merge pull request #243 from V-Play-Games/master
Fixed Typos
2021-11-02 12:33:39 +01:00
V Play Games 704b8ecd39 Fixed Typos 2021-11-01 11:16:41 +05:30
Julien Le Coupanec 14d53d31c8 Merge pull request #242 from tyonirwansyah/patch-1
docs(vscode-cheatsheet): new vscode extensions
2021-10-24 15:49:33 +02:00
Tyo Nirwansyah 5dc55f1a83 docs(vscode-cheatsheet): new vscode extensions
added new git, theme and handy extensions for your vscode workflow.
2021-10-20 10:36:14 +03:00
Julien Le Coupanec e668f3c19c Merge pull request #237 from erfanansari/update_git
Update git.sh
2021-10-14 20:14:02 +02:00
Erfan Ansari 40303cb79f Update git 2021-10-14 20:12:34 +03:30
Julien Le Coupanec f0b87463ed Merge pull request #235 from ahmettortumlu/feature/add-linux-command
Feature/add linux command
2021-10-10 20:36:34 +02:00
tortumlu a580e2d175 add ctrl+a then e command to bash commands 2021-10-10 19:59:19 +03:00
tortumlu 4a0d72fc35 add resize2fs command to bash commands 2021-10-10 19:57:23 +03:00
tortumlu d66d0db292 add netstat command to bash commands 2021-10-10 19:53:15 +03:00
Julien Le Coupanec 92c6c88716 Merge pull request #234 from rhyw/python-fix-typo
Fix several typos in python.md
2021-10-08 12:59:43 +02:00
Yuguang Wang 09602e03fd Fix several typos in python.md 2021-10-08 11:11:28 +08:00
Julien Le Coupanec 9ff4eb1d9c Merge pull request #212 from ZohebMOPO/temp 2021-10-02 01:34:25 +02:00
Julien Le Coupanec 94694884dc Merge pull request #231 from NikolasMelui/patch-1 2021-10-02 01:33:03 +02:00
Julien Le Coupanec 8b81bc13fd Merge pull request #232 from AmateurDevs/master 2021-10-02 01:32:27 +02:00
Julien Le Coupanec 4f44c24030 Merge pull request #230 from yashd-dev/master 2021-10-02 01:30:54 +02:00
Steven Tracey c64afd2158 Use http2
http2 is a more secure connection and in some cases can improve load times.
2021-09-29 10:10:15 -04:00
nikolasmelui 31b098ac63 Update node.js 2021-09-27 13:09:02 +03:00
Yash 71e45aa43e Update python.md 2021-09-25 14:31:50 +05:30
Julien Le Coupanec dbc5b69dc8 Merge pull request #228 from CookieGamer733/patch-1
Correct spelling.
2021-09-23 15:29:10 +02:00
CookieGamer733 ae5f62c7f8 Correct spelling. 2021-09-21 12:24:24 -05:00
Julien Le Coupanec 01cbe6f0bd Merge pull request #224 from yogesnsamy/patch-1
Update golang.md
2021-09-17 14:36:24 +02:00
yogesnsamy b885d645fe Update golang.md
Use propercase in renaming the function in the `Testing` example
2021-09-17 10:57:51 +08:00
Julien Le Coupanec b6537404c7 docs: ubuntu 2021-09-07 11:43:55 +02:00
Julien Le Coupanec ba760faecd docs: macos 2021-09-07 11:42:54 +02:00
Julien Le Coupanec 32ed1e33f0 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2021-09-06 12:27:04 +02:00
Julien Le Coupanec d787d6cf8d docs: mysql 2021-09-06 12:27:02 +02:00
Julien Le Coupanec b443850b2a docs: mysql update 2021-09-06 12:22:38 +02:00
Julien Le Coupanec d32e1a7fc4 Merge pull request #220 from mhyrzt/patch-1
added 'ngg' command
2021-08-04 10:53:47 +02:00
Mahyar 31690932c5 added 'ngg' command
hello There :)
i noticed that you did not mention 'ngg' for going to line n so i added it at line 32
p.s: it's my first contribution :D
regards
2021-08-04 01:32:22 +04:30
Julien Le Coupanec a2d51368dc Merge pull request #219 from dreamysap/Sapna-JavaChanges
Updated java.md
2021-07-17 14:51:56 +02:00
Sapna Katti 1836f22a54 Updated java.md
Updated java.md
Added the enhanced for loop/for-each with example.
2021-07-17 11:15:15 +05:30
Julien Le Coupanec 78022a5e95 Merge pull request #218 from theEpicjosh/patch-1 2021-07-14 19:01:20 +02:00
Josh Young a751a64a01 Update html5.html
Near <sub></sub>, an extra space was removed from the description part.
2021-07-14 13:05:54 -03:00
Julien Le Coupanec 2fe2e8d2f9 Merge pull request #217 from DeadlyChambers/patch-1 2021-07-11 22:38:35 +02:00
Julien Le Coupanec 5ba6b5e93f Merge pull request #216 from DeadlyChambers/master 2021-07-11 22:37:59 +02:00
shane chambers f668201688 Added a few sed commands, info, help, switch user, and sudo 2021-07-11 06:17:55 -06:00
shane chambers e17d236bee fixing a spelling issue 2021-07-11 05:00:47 -06:00
Julien Le Coupanec 3c1dab9dda Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2021-07-05 22:49:21 +02:00
Julien Le Coupanec 1c6d4ee480 docs(mysql): Run SQL query in the background 2021-07-05 22:49:19 +02:00
Julien Le Coupanec 23488da297 Merge pull request #213 from plskz/master
Update git.sh
2021-06-30 20:32:21 +02:00
plskz 2021c90140 Update git.sh 2021-07-01 01:13:11 +08:00
Zoheb Alli Khan d4fe30f94b Added in Readme 2021-06-04 16:38:50 +05:30
Zoheb Alli Khan 2fa3e1b155 Whole Cheatsheet 2021-06-04 16:17:37 +05:30
Zoheb Alli Khan 862c113892 BodyParser 2021-06-04 11:51:15 +05:30
Zoheb Alli Khan 106d656567 Response methods 2021-06-04 11:41:30 +05:30
Zoheb Alli Khan b995f9e2c4 Distinction 2021-06-04 10:47:31 +05:30
Zoheb Alli Khan e775f8e675 Request Method and Props 2021-06-04 10:45:05 +05:30
Zoheb Alli Khan 8008c44d49 HTTP App Routes 2021-06-04 09:54:29 +05:30
Zoheb Alli Khan b9be6c4cbc Added some cheatsheets 2021-06-03 23:14:49 +05:30
Zoheb Alli Khan 24faa1e1c1 Changes 2021-06-03 14:20:43 +05:30
Zoheb Alli Khan 859556dc1f App Properties 2021-06-03 12:04:27 +05:30
Zoheb Alli Khan 9731e6841b Structured Components 2021-06-03 09:59:08 +05:30
Zoheb Alli Khan 81add6e07b Added all express methods 2021-06-03 09:54:44 +05:30
Zoheb Alli Khan 3efedb4ded Two methods added 2021-06-03 08:06:46 +05:30
Julien Le Coupanec f0d26648ae Merge pull request #209 from Codyhintzch/patch-1
Added some basics commands and key combos
2021-05-15 09:51:48 +02:00
Codyhintzch d6ba64e4b9 Added some basics commands and key combos
Noticed there was some stuff missing that I consider good basics to use so I compared the cheat sheet with my own personal cheat sheet and added some stuff. I tried to stay basic enough that it stayed relevant to anybody doing bash stuff
2021-05-14 15:45:11 -06:00
Julien Le Coupanec d8d6fa49c0 Merge pull request #208 from nicolasDonkey/patch-1
Update Mysql.sh add create user command
2021-05-13 13:22:02 +02:00
nicolasDonkey a37345dc55 Update Mysql.sh add create user command 2021-05-13 12:38:31 +02:00
Julien Le Coupanec 5afbb2dd0f Merge pull request #195 from Devorein/redis-lpushx
Added redis lpushx command
2021-05-08 00:37:04 +02:00
Julien Le Coupanec 7148273bc4 fix: typo 2021-05-07 20:04:46 +02:00
Julien Le Coupanec b2e4dd2b91 Merge pull request #201 from Eyob-mulualem/patch-1
Update git cheat-sheets
2021-05-07 13:29:11 +02:00
Eyob Mulualem 5fa1f190c1 Update git cheetsheet
add remote reposiory
2021-05-07 08:04:22 +03:00
Safwan Shaheer e1828cbe2c Added redis lpushx command 2021-04-30 20:33:24 +06:00
Julien Le Coupanec 05f8c9ee01 Merge pull request #193 from tosi29/remove-duplicate
Remove duplicate description from Python Basic Datatypes
2021-04-21 10:07:11 +02:00
tosi29 283257b750 Remove duplicate from Basic Datatypes 2021-04-21 16:41:13 +09:00
Julien Le Coupanec b6dc8fb718 Merge pull request #192 from SabryTarek/master
add equivalent to bash command
2021-04-16 18:08:15 +02:00
SabryTarek f806fefafb add equivalent to bash command 2021-04-16 13:49:26 +00:00
Julien Le Coupanec 016c07af64 Merge pull request #186 from inoue0426/master
add perl extensions for visual studio code
2021-03-28 11:52:45 +02:00
inoue0426 e591db15a3 add perl extensions for vsc 2021-03-28 14:57:20 +09:00
Julien Le Coupanec 7ccf0d3a92 Merge pull request #184 from kobito-kun/patch-1
Minor Fix
2021-03-26 17:01:29 +01:00
Kobi 1030d6737d Minor Fix
Just a character fix.
2021-03-26 01:24:55 -04:00
Julien Le Coupanec 7989cb9a6f Merge pull request #183 from kasperfrederiksen/patch-1
Fixed wrong declaration in variable section
2021-03-25 15:45:15 +01:00
Kasper Frederiksen 53ad5697e8 Fixed wrong declaration in variable section 2021-03-25 15:25:41 +01:00
Julien Le Coupanec cff39967e1 Merge pull request #181 from nitish770/master
Sublime Text : Extra keys added
2021-03-23 13:50:24 +01:00
nk 336ef76baa Sublime Text : Extra keys added 2021-03-23 17:58:59 +05:30
Julien Le Coupanec 81a237ae9f Merge pull request #180 from Weltraum/patch-1
Update golang.md
2021-03-21 13:57:26 +01:00
Vlad 46f2b2e3a1 Update golang.md 2021-03-21 14:33:51 +03:00
Julien Le Coupanec db0520dc23 Merge pull request #179 from nitish770/master
python.md Incorrect Keywords fixed
2021-03-16 15:16:24 +01:00
nitish770 27d1831c27 broken table in python keywords fixed 2021-03-16 12:49:38 +05:30
nitish770 2c92735c4f #177 python keywords corrected 2021-03-16 12:47:34 +05:30
Julien Le Coupanec 987b708b36 Merge pull request #171 from G0ldmember/patch-1
Update java.md
2021-03-13 19:14:06 +01:00
G0ldmember 7fdab9da66 Update java.md
fixed typos
2021-03-11 18:55:18 +01:00
Julien Le Coupanec 89761b71da Merge pull request #170 from Pospelove/patch-1
Fix typo in java.md
2021-03-11 13:27:25 +01:00
Leonid Pospelov 641fa33773 Update java.md 2021-03-11 15:11:11 +03:00
Julien Le Coupanec 75ed33d564 docs: reorder imperative languages alphabetically 2021-03-10 12:50:17 +01:00
Julien Le Coupanec d04175dd56 Merge pull request #163 from LuanSilveiraSouza/add-go-language
Add Go language
2021-03-10 12:49:32 +01:00
LuanSilveiraSouza 9b89b3136a fix: add anon funcs in go cheatsheet 2021-03-09 15:56:15 -03:00
LuanSilveiraSouza 61f5d0359f docs: add routines to go cheatsheet 2021-03-09 15:44:47 -03:00
LuanSilveiraSouza 9349857693 docs: start libs section of go cheatsheet 2021-03-06 21:07:16 -03:00
LuanSilveiraSouza 609f229542 docs: start advanced section of go cheatsheet 2021-03-06 20:02:59 -03:00
LuanSilveiraSouza 3775de44b5 docs: add syntax section to go cheatsheet 2021-03-06 13:02:49 -03:00
LuanSilveiraSouza d3a4a69ce9 docs: start golang cheatsheet 2021-03-06 11:40:00 -03:00
Julien Le Coupanec 75eab8746b Merge pull request #161 from theRay1s/patch-2
tools(heroku.sh): Update heroku.sh
2021-02-06 11:53:11 +01:00
Rehan Singh 61cd930585 tools(heroku.sh): Update heroku.sh 2021-02-06 10:35:33 +05:30
Julien Le Coupanec 47675c4fa3 Merge pull request #159 from devansh-07/patch-1
Correct misspelled word
2021-02-05 18:37:40 +01:00
Devansh Soni 1de769e598 Correct misspelled word 2021-02-05 18:14:31 +05:30
Julien Le Coupanec b7726cf471 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-12-31 15:30:23 +01:00
Julien Le Coupanec ea8e8cd900 docs(elasticsearch): add brew command 2020-12-31 15:30:21 +01:00
Julien Le Coupanec 5e0c76a63e Merge pull request #155 from jveer634/patch-1
Added python cheat sheet to the languages folder.
2020-12-12 11:41:09 +01:00
Jay 2ab007e2a3 Added Python link to README 2020-12-12 15:56:23 +05:30
Jay d590c82ecb Added python cheat sheet to the languages folder.
I intentionally skipped the OOPS concept as it consists more data which is making cheat book but not sheet,
Please do mention if I'm missing, I will add them.
2020-12-08 00:36:18 +05:30
Julien Le Coupanec be167bc112 Merge pull request #154 from Hiebs915/master
Grammatical Error under Visual Studio Cheatsheet > Git
2020-12-07 18:10:59 +01:00
Julien Le Coupanec 32586c3fcf fix(ubuntu): remove duplicated command 2020-12-07 17:22:24 +01:00
Julien Le Coupanec 731020d2e4 docs(ubuntu): display ip of the server 2020-12-07 17:22:08 +01:00
Matthew Hiebing f59ffcfa93 Grammatical Error under Visual Studio Cheatsheet > Git
Small grammatical error under VSC > Git.

Changed, "- [`Gitignore`](https://marketplace.visualstudio.com/items?itemName=codezombiech.gitignore): A extension for Visual Studio Code that assists you in working with .gitignore files."

to: "- [`Gitignore`](https://marketplace.visualstudio.com/items?itemName=codezombiech.gitignore): An extension for Visual Studio Code that assists you in working with .gitignore files."
2020-12-06 20:22:45 -06:00
Julien Le Coupanec 0c37900ef0 Merge pull request #152 from Alkkem/patch-1
Added more shortcuts to the "ALT" section in the bash shortcut list.
2020-12-03 17:10:23 +01:00
Alkkem 1643b90b9e Added more shortcuts to the "ALT" section
Added shortcuts to the ALT section, in particular those that come after "ALT+H"
2020-12-03 16:28:56 +01:00
Julien Le Coupanec 3201fb52f5 docs(mysql): update grant commannd 2020-12-03 13:04:22 +01:00
Julien Le Coupanec 52e94ebc3c docs(mysql): update grand all privileges command 2020-12-03 13:03:38 +01:00
Julien Le Coupanec 61813a4812 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-11-30 18:18:00 +01:00
Julien Le Coupanec 08ffddee57 docs(mysql): update all privileges 2020-11-30 17:20:50 +01:00
Julien Le Coupanec c689d6cbbf Merge pull request #119 from iamdhrv/master
Created Cheat sheet for Java  language.
2020-11-08 17:29:43 +01:00
Julien Le Coupanec a0ed757c9a Merge pull request #151 from theRay1s/patch-1
Setting Stac of  app to Container
2020-11-03 15:52:41 +01:00
Rehan Singh 54147873d8 Setting Stac of app to Container 2020-11-02 14:11:27 +05:30
Julien Le Coupanec 1ecb0b8a54 Merge pull request #147 from louisboilard/vim-delete-til
Added change/delete command and zz command to vim.txt.
2020-11-01 18:27:35 +01:00
Julien Le Coupanec d41b6bb7da docs(vim): updates 2020-11-01 18:27:21 +01:00
Julien Le Coupanec 1f021560e2 Merge pull request #148 from Charlie-117/master
docs(git): update git.sh
2020-11-01 18:24:45 +01:00
Charlie-117 8a58903ad1 docs(git): update git.sh
* fix some typos
* add some commands
2020-11-01 16:52:19 +05:30
louisboilard e6cdab4c5d Added change/delete command and zz command. 2020-10-31 21:14:48 -04:00
Julien Le Coupanec fa869f5dd2 Merge pull request #145 from Vishalghyv/master
Drush Cheatsheet
2020-10-06 15:52:46 +02:00
Vishalghyv b010a3436f Read me link and alignment of commands 2020-10-06 17:50:28 +05:30
Vishalghyv 5af126a834 Basic Link 2020-10-06 17:31:41 +05:30
Vishalghyv 02bdc8f1df Drush Cheatsheet 2020-10-06 17:28:59 +05:30
Julien Le Coupanec 484d17d7e7 Merge pull request #144 from Vishalghyv/master
PHP Regex
2020-10-06 12:46:47 +02:00
Vishalghyv a5b2db95f2 Minor Change 2020-10-06 15:57:19 +05:30
Vishalghyv 20594479f3 PHP Regex 2020-10-06 15:55:29 +05:30
Julien Le Coupanec 2ded33ce9e Merge pull request #143 from laurenah/master
add links to extension references
2020-10-06 11:04:56 +02:00
laurenah 6f10eb9335 add links to extension references 2020-10-06 16:26:17 +11:00
Julien Le Coupanec 5502ffd277 Merge pull request #142 from optimist2309/master
bash cheat sheet updated
2020-10-05 00:02:07 +02:00
optmist2309 6d88c3db05 bash cheatsheet updated 2020-10-05 00:47:41 +05:30
Julien Le Coupanec ad8febdfe2 Merge pull request #141 from thangtd-0050/patch-1
Add some useful git commands
2020-10-02 19:29:29 +02:00
thangtd-0050 517ce0ea59 Add some useful git commands
Add some useful git commands, about `git reset --hard`, `git rm --cached`, `git remote rm`, `git log --oneline`, `git commit --amend`, `git show`, `git diff` ...
2020-10-02 22:49:53 +07:00
Julien Le Coupanec f13ec4ac2a Merge pull request #140 from sumankumari13/master
Some more tags
2020-10-02 13:08:48 +02:00
sumankumari13 640bdfc7fd Some more tags 2020-10-02 16:34:13 +05:30
Julien Le Coupanec 4d237c2a57 Merge pull request #139 from anishkashukla/master
Add some more tags
2020-10-02 11:16:45 +02:00
11anishka ad1d39b9dd Add some more tags 2020-10-02 14:20:36 +05:30
Julien Le Coupanec fee6bc10ed Merge pull request #138 from jav-rojas/jav-rojas
Added 'Users and Privileges' on mysql file and several configs to nginx file
2020-10-01 21:34:03 +02:00
jrojasc 133bf721ce Added 'Users and Privileges' in mysql file and several groups of config for nginx file 2020-10-01 16:28:55 -03:00
Julien Le Coupanec e963b93ded docs(redis): check redis status and restart 2020-09-28 14:23:49 +02:00
Julien Le Coupanec 8b1ae69f76 docs(git): rework the way we delete a branch 2020-09-27 17:56:05 +02:00
Julien Le Coupanec 6a18dc96f1 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-09-26 19:44:08 +02:00
Julien Le Coupanec 456df7dbe9 docs(ubuntu): log as root 2020-09-26 16:06:01 +02:00
Julien Le Coupanec 849ade7392 Merge pull request #136 from thangvo38/various-additions
Add PM2 cheat sheet + various additions
2020-09-21 12:30:27 +02:00
Thang Vo a6ff7b33d1 Add PM2 cheat sheet + various additions 2020-09-21 17:06:46 +07:00
Julien Le Coupanec d00eb3352c Merge pull request #135 from thangvo38/aws-cli-basic
Add basic AWS CLI commands
2020-09-21 09:42:26 +02:00
Thang Vo 9dc86ca020 Reorder aws in readme.md 2020-09-21 14:39:49 +07:00
Thang Vo 6749197e76 Add basic AWS CLI commands 2020-09-21 14:22:00 +07:00
Julien Le Coupanec 8f8dd58758 docs(elastic): check version 2020-09-17 11:18:09 +02:00
Julien Le Coupanec e8be8df3d6 docs(mysql): grant all privileges 2020-09-11 11:02:31 +02:00
Julien Le Coupanec 0b10cb93d6 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-09-11 10:45:30 +02:00
Julien Le Coupanec fd07239b2b docs(ubuntu): add scp commands 2020-09-11 10:45:29 +02:00
Julien Le Coupanec 0ca7c26953 Merge pull request #134 from githubsaturn/patch-1
Fixed typo
2020-09-03 11:12:36 +02:00
Kasra Bigdeli 571dedea7f Fixed typo 2020-09-02 22:31:26 -04:00
Julien Le Coupanec b731f9f149 Merge pull request #133 from Madhav2310/patch-1
Update django.py
2020-08-17 09:37:39 +02:00
Madhav Mittal 2bd53d642d Update django.py
App creation
2020-08-17 03:45:21 +05:30
Julien Le Coupanec fa678c61ac Merge pull request #132 from SConaway/patch-1
MySQL is a SQL db
2020-07-31 10:46:22 +02:00
Steven Conaway f67969bcd5 MySQL is a SQL db 2020-07-30 17:29:30 -07:00
Julien Le Coupanec 62efe852d1 docs(adonis): add callback to attach method 2020-07-22 10:07:50 +02:00
Julien Le Coupanec 9025748f03 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-07-21 21:18:43 +02:00
Julien Le Coupanec 0c65389ebd docs(adonis): add relationship methods 2020-07-21 21:18:41 +02:00
Julien Le Coupanec 25fa495060 Merge pull request #130 from mihir-1997/master
refactor(docs): updated link for kubernetes
2020-07-19 11:22:27 +02:00
Mihir 7cc8640251 refactor(docs): updated link for kubernetes 2020-07-19 02:12:05 -07:00
Julien Le Coupanec 284db700fb Merge pull request #129 from mihir-1997/master
Convert kubernetes .sh file to .md
2020-07-19 09:58:21 +02:00
mihir 3b591063c0 Merge pull request #1 from mihir-1997/feature-convert-md
refactor(docs): convert .sh file to .md
2020-07-18 15:29:48 -07:00
Mihir 00918e7080 refactor(docs): convert .sh file to .md 2020-07-18 15:24:42 -07:00
Julien Le Coupanec 69d3cf7abb Merge pull request #128 from mihir-1997/master
added exec and set namespace commands
2020-07-13 11:42:56 +02:00
Mihir b35cf4043d added exec and set namespace commands 2020-07-12 16:10:44 -07:00
Julien Le Coupanec f8eb132e2f Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-07-03 14:29:08 +02:00
Julien Le Coupanec 4d9adef433 docs(mysql): SHOW PROCESSLIST 2020-07-03 14:29:06 +02:00
Julien Le Coupanec 7a5d523e80 Merge pull request #127 from zekinah/updates-php
Adds Declaring and Sorting an Array in PHP
2020-07-02 12:10:59 +02:00
zekinah 08af064a39 Adds Declaring and Sorting Array in PHP 2020-07-01 17:55:22 -07:00
Julien Le Coupanec b8e818c1a4 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-07-01 11:31:06 +02:00
Julien Le Coupanec d2e6e17e9e docs(ubuntu): add commands 2020-07-01 11:31:00 +02:00
Julien Le Coupanec 1495ca6ab9 Merge pull request #126 from yogeshojha/master
CSS properties added for Emmet
2020-06-28 10:29:52 +02:00
Yogesh Ojha 7c8d3339a9 margin and padding property css properties added 2020-06-28 00:08:07 +05:30
Yogesh Ojha 7eb73eaf50 css property table 2020-06-28 00:05:51 +05:30
Yogesh Ojha abc93ca13c added some css properties 2020-06-28 00:00:47 +05:30
Julien Le Coupanec 328b62fcb8 docs(ubuntu): df -h command 2020-06-21 18:38:14 +02:00
Julien Le Coupanec 9a571c5ffe docs(mysql): import/export commands 2020-06-21 18:37:44 +02:00
Julien Le Coupanec 25e170d887 docs(ubuntu): initialize cheatsheet 2020-06-21 18:37:36 +02:00
Julien Le Coupanec f49d6e026b docs(mysql): initialize cheatsheet 2020-06-21 18:03:59 +02:00
Julien Le Coupanec 8d9071dff6 Merge pull request #125 from yogeshojha/master
Emmet cheatsheet added
2020-06-21 18:01:49 +02:00
Yogesh Ojha 11f5b5b6c8 Emmet in alphabetical order 2020-06-21 21:26:15 +05:30
Yogesh Ojha 850e7b56f2 Merge branch 'tool/emmet' 2020-06-21 21:12:39 +05:30
Yogesh Ojha b888d801db Typos fixed 2020-06-21 21:12:31 +05:30
Yogesh Ojha a69efb19bb Merge branch 'master' of https://github.com/LeCoupa/awesome-cheatsheets 2020-06-21 21:09:49 +05:30
Yogesh Ojha 8a1b3c86ce Tips and Cheatsheet added for Emmet 2020-06-21 21:03:10 +05:30
Yogesh Ojha e4930c1e2f Updated Readme.md 2020-06-21 21:02:23 +05:30
Julien Le Coupanec 9b6ed3bffa Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-06-21 17:21:55 +02:00
Julien Le Coupanec abed550112 docs(nginx): initialize cheatsheet 2020-06-21 17:21:53 +02:00
Yogesh Ojha 499ce17202 Attributes and contents added for Emmet 2020-06-21 20:38:22 +05:30
Yogesh Ojha 5f2ce01663 Groupings added 2020-06-21 20:28:47 +05:30
Yogesh Ojha b70c19b739 Cheatsheet for Emmet created 2020-06-21 20:15:24 +05:30
Julien Le Coupanec e7ccca4a90 Merge pull request #124 from nswinson/patch-2
Update bash.sh
2020-06-20 18:47:16 +02:00
nswinson c2295bf7e4 Update bash.sh 2020-06-20 10:45:05 -06:00
Julien Le Coupanec 114f38ea97 Merge pull request #123 from nswinson/patch-1
Update bash.sh
2020-06-20 18:13:36 +02:00
nswinson fbbaaa6f0a Update bash.sh 2020-06-20 10:05:40 -06:00
Julien Le Coupanec d89e4aed41 Merge pull request #122 from Kombatologist/patch-1
Fixed typo
2020-06-19 02:21:39 +02:00
Jason Shearer ef7aab4ab8 Fixed typo 2020-06-18 16:01:49 -07:00
Julien Le Coupanec 665830f2bf docs(elasticsearch): add service commands 2020-06-07 21:49:12 +02:00
iamdhrv 69a7080ab6 Update README.md
Added Java extensions in Readme.md file.
2020-06-06 14:07:18 +05:30
Dhruv 1bdf7b8a56 Created Cheat sheet for Java language.
Improvement in @raulvillora 's file and also added many new JAVA topics with github md extension suppport.
2020-06-05 16:37:59 +05:30
Julien Le Coupanec 64d2004dcc docs(elastic-search): add javascript api client 2020-06-04 16:24:22 +02:00
Julien Le Coupanec 7b4b3306c0 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-06-04 12:06:50 +02:00
Julien Le Coupanec f966187fe7 docs(elastic-search): initialize cheatsheets 2020-06-04 12:06:47 +02:00
Julien Le Coupanec f3849c72d9 Merge pull request #118 from Ancy1987/master
Git clean commands added
2020-05-25 13:04:23 +02:00
Ancy1987 2c0805a4a6 Merge pull request #1 from Ancy1987/Ancy1987-patch-1
Git clean commands added
2020-05-25 16:16:15 +05:30
Ancy1987 d2b44bed00 Git clean commands added 2020-05-25 16:14:33 +05:30
Julien Le Coupanec bf63539aa7 docs(adonis): helpers 2020-05-06 10:40:31 +02:00
Julien Le Coupanec 78a1128dff docs(adonis): file storage 2020-05-01 14:13:38 +02:00
Julien Le Coupanec 3983651d8f docs(puppeteer): reorganize 2020-05-01 14:07:22 +02:00
Julien Le Coupanec 6e7dc502d2 docs(adonis): initialize query builder section 2020-04-27 23:07:31 +02:00
Julien Le Coupanec 8168181146 docs(adonis): add toJSON method 2020-04-25 19:51:51 +02:00
Julien Le Coupanec 27202646b5 feat(adonis): social authentication 2020-04-25 17:17:49 +02:00
Julien Le Coupanec eb7f97c535 feat(adonis) add lucid methods 2020-04-24 20:58:50 +02:00
Julien Le Coupanec e69c95694e docs(adonis): encryption and hashing 2020-04-18 12:28:32 +02:00
Julien Le Coupanec 35039d583f docs(adonis): adjustments 2020-04-18 12:21:29 +02:00
Julien Le Coupanec 0199acf956 docs(adonis): logger methods 2020-04-18 12:19:43 +02:00
Julien Le Coupanec b52da9aa7e docs(adonis): add sessions 2020-04-15 22:12:48 +02:00
Julien Le Coupanec b0c3c912db docs(adonis): add response 2020-04-15 21:49:11 +02:00
Julien Le Coupanec d0452250dc docs(adonis): add events 2020-04-14 14:23:46 +02:00
Julien Le Coupanec 8ec2450866 docs(adonis): request 2020-04-13 17:10:16 +02:00
Julien Le Coupanec 490b5c1f59 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-04-12 17:05:48 +02:00
Julien Le Coupanec a3e8091ca2 docs(adonis): add validation rules 2020-04-12 17:05:46 +02:00
Julien Le Coupanec 94f2ad38fa Merge pull request #117 from yurnov/curl
initial cURL cheatsheet added
2020-04-12 15:43:15 +02:00
Yuriy Novostavskyy 53438bfd1c fixed alphabetical order of tools in README.md 2020-04-12 13:45:42 +03:00
Yuriy Novostavskyy d0b259d262 initial commit for cURL 2020-04-12 12:23:16 +03:00
Julien Le Coupanec b310c4b285 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-04-11 21:39:19 +02:00
Julien Le Coupanec 576452d67e docs(adonis): available hooks 2020-04-11 21:39:17 +02:00
Julien Le Coupanec 9bff9c9c99 Merge pull request #116 from yurnov/patch-1
colors added
2020-04-11 17:22:00 +02:00
Yuriy Novostavskyy 09145624f5 fixed typo (thanks @neexite) 2020-04-11 17:21:08 +03:00
Yuriy Novostavskyy 7546157094 additional collor added 2020-04-11 15:21:27 +03:00
yurnov 494adccb87 Colors and test effect added
added codes and examples of how to use colors, bolds, and effects
2020-04-11 14:54:51 +03:00
Julien Le Coupanec 627cc06a0f docs(adonis): routing 2020-04-11 13:11:09 +02:00
Julien Le Coupanec 0b29b9bb54 docs(adonis): add migration commands 2020-04-10 18:00:31 +02:00
Julien Le Coupanec 577f507189 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-04-10 14:40:16 +02:00
Julien Le Coupanec 727f636651 docs(adonis): initialize cheatsheet` 2020-04-10 14:40:13 +02:00
Julien Le Coupanec 6ed61dd6ad Merge pull request #114 from rmlzy/master
docs(git): update git.sh
2020-04-07 15:48:20 +02:00
rmlzy e8af65049d docs(git): update git.sh 2020-04-07 09:18:35 +08:00
Julien Le Coupanec 330e60d307 Merge pull request #112 from ltctl/master
Update bash.sh
2020-04-01 23:08:45 +02:00
Julien Le Coupanec f7ce5d0f49 docs(tailwind): screen readers 2020-03-29 18:13:01 +02:00
Julien Le Coupanec 190aa8a295 docs(tailwind): svg 2020-03-29 18:11:47 +02:00
Julien Le Coupanec a578ea612f docs(tailwind): interactivity 2020-03-29 18:10:15 +02:00
Julien Le Coupanec 92ef8999de docs(tailwind): transforms 2020-03-29 18:05:53 +02:00
Julien Le Coupanec 2c7445ee21 docs(tailwind): transitions 2020-03-29 17:59:52 +02:00
Julien Le Coupanec 330f8970f4 docs(tailwind): add opacity 2020-03-29 17:48:27 +02:00
Julien Le Coupanec b7d5f219aa docs(tailwind): tables 2020-03-29 17:10:29 +02:00
Julien Le Coupanec 25ec9ee6b0 docs(tailwind): border-collapse 2020-03-29 17:08:12 +02:00
Julien Le Coupanec 893be71f40 docs(tailwind): border 2020-03-29 17:07:01 +02:00
Julien Le Coupanec d9ade96c1c docs(tailwind): backgrounds 2020-03-29 16:42:18 +02:00
Julien Le Coupanec dc1f5bda1a docs(tailwind): typography 2020-03-29 16:10:26 +02:00
Julien Le Coupanec 90fd9e5872 docs(tailwind): sizing 2020-03-29 15:46:31 +02:00
Julien Le Coupanec 087b076040 docs(tailwind): spacing 2020-03-29 15:30:58 +02:00
Julien Le Coupanec 3f451ea5f4 docs(tailwind): grid classes 2020-03-29 15:22:43 +02:00
Julien Le Coupanec e592128bd3 docs(tailwind): flexbox 2020-03-29 14:38:47 +02:00
Julien Le Coupanec 267e4cc1de docs(tailwind): align-content 2020-03-29 14:18:58 +02:00
Julien Le Coupanec eef88d09e1 docs(tailwind): align items 2020-03-29 14:16:25 +02:00
Julien Le Coupanec 2d5dcd1ff0 docs(tailwind): flex-wrap 2020-03-29 14:13:05 +02:00
Julien Le Coupanec 01576657fe docs(tailwind): flex direction 2020-03-29 14:08:57 +02:00
Julien Le Coupanec 43f33e5ac0 docs(tailwind): top right bottom left 2020-03-29 12:51:33 +02:00
Julien Le Coupanec 47a5e3cb7b docs(tailwind): position 2020-03-29 12:46:50 +02:00
Julien Le Coupanec 56229c1a46 docs(tailwind): add structure 2020-03-29 12:34:47 +02:00
Julien Le Coupanec 8c35714275 docs(tailwind): add overflow 2020-03-28 23:28:07 +01:00
Julien Le Coupanec 3063b14961 docs(tailwind): add space to comments 2020-03-28 23:25:29 +01:00
Julien Le Coupanec 59b886f3de docs(tailwind): add object position 2020-03-28 23:24:19 +01:00
Julien Le Coupanec aeace17659 docs(tailwind): object-fit 2020-03-28 23:07:29 +01:00
Julien Le Coupanec 54c206f63d docs(tailwind): rework style 2020-03-28 22:20:11 +01:00
Julien Le Coupanec a821fe9d12 docs(tailwind): add clear 2020-03-28 22:16:02 +01:00
Julien Le Coupanec 2a18405341 docs(tailwind): add floats 2020-03-28 22:12:59 +01:00
Julien Le Coupanec 9f5a51f11f docs(tailwind): add display 2020-03-28 22:10:06 +01:00
Julien Le Coupanec e3e212be25 docs(tailwind): add breakpoints + container + box-sizing 2020-03-28 22:03:51 +01:00
Julien Le Coupanec f305520707 docs(tailwind): initialize stylesheet 2020-03-28 19:51:38 +01:00
Julien Le Coupanec 4217db8c62 docs(laravel): add foreign key constraints 2020-03-28 19:50:02 +01:00
Yoko Lau 026729934f Update bash.sh 2020-03-24 19:46:33 +08:00
Julien Le Coupanec b2aaf18e17 docs(laravel): add migrations columns 2020-03-23 16:19:10 +01:00
Julien Le Coupanec 8580ca1973 docs(laravel): add table options 2020-03-23 16:07:39 +01:00
Julien Le Coupanec 45bf363110 docs(laravel): add collection column modifiers 2020-03-23 16:05:32 +01:00
Julien Le Coupanec 2269417161 docs(laravel): Add collection column types 2020-03-23 16:01:29 +01:00
Julien Le Coupanec 296c01b279 docs(puppeteer): final cheatsheet 2020-03-19 16:19:50 +01:00
Julien Le Coupanec 919c839e24 docs(puppeteer): response functions 2020-03-19 16:16:20 +01:00
Julien Le Coupanec 52c05c5cf4 docs(puppeteer): add request functions 2020-03-19 16:10:08 +01:00
Julien Le Coupanec 5a558f6f60 docs(puppeteer): add elementHandle functions 2020-03-19 16:07:26 +01:00
Julien Le Coupanec 10c84a7691 fix(puppeteer): typo 2020-03-19 16:00:12 +01:00
Julien Le Coupanec b994cac48a docs(puppeteer): add executionContext and jsHandle functions 2020-03-19 15:59:32 +01:00
Julien Le Coupanec c293a96a12 docs(puppeteer): add frame functions 2020-03-19 15:46:04 +01:00
Julien Le Coupanec c5464a8232 docs(puppetter): add mouse, touchscreen, tracing, fileChooser, dialog and consoleMessage 2020-03-19 15:21:37 +01:00
Julien Le Coupanec c4a179267f feat(puppeteer): add keyboard functions 2020-03-19 15:12:59 +01:00
Julien Le Coupanec 2a8409ed54 docs(puppeteer): add accessibility functions 2020-03-19 14:42:57 +01:00
Julien Le Coupanec c2e320b3d3 feat(puppeteer): add worker functions 2020-03-19 14:42:35 +01:00
Julien Le Coupanec d514e86e11 docs(puppeteer): page functions 2020-03-18 14:38:54 +01:00
Julien Le Coupanec 1716f3f575 feat(puppeteer): add page functions 2020-03-17 22:07:34 +01:00
Julien Le Coupanec 7937ffea53 docs(puppeteer): browser functions 2020-03-17 15:23:55 +01:00
Julien Le Coupanec c7ad1bf574 docs(puppeteer): add browser functions 2020-03-17 15:10:34 +01:00
Julien Le Coupanec c5faec60ef feat(puppeteer): add comments 2020-03-17 14:13:45 +01:00
Julien Le Coupanec c882af50b7 feat(puppeteer): add puppeeter and browserfetcher 2020-03-17 13:14:24 +01:00
Julien Le Coupanec 0a88f6209f docs(puppeteer): wip 2020-03-16 16:28:02 +01:00
Julien Le Coupanec b525056ac8 docs(readme): add pupeeteer 2020-03-16 15:27:33 +01:00
Julien Le Coupanec 873782d90a Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2020-03-16 15:26:49 +01:00
Julien Le Coupanec b3444b6a31 docs(puppeteer): initialize cheatsheet 2020-03-16 15:26:48 +01:00
Julien Le Coupanec 08f4e886d6 Merge pull request #110 from janstuemmel/patch-1
Fix php cheatsheet, for loop
2020-01-22 00:13:37 +01:00
Jan Stümmel e28a4a9cec Fix php cheatsheet, for loop
iterates over all values, not just n-1 values
2020-01-21 18:57:12 +01:00
Julien Le Coupanec 6c27bf77de Merge pull request #108 from kerolloz/patch-1
Fix a typo
2019-12-12 19:16:28 +01:00
Kerollos Magdy a0aa12efa7 Fix a typo 2019-12-12 13:13:15 +02:00
Julien Le Coupanec 21a99e7bd6 Merge pull request #106 from qiisziilbash/minor-edits-django
Minor edits to the django start project steps
2019-12-10 21:43:50 +01:00
qiisziilbash 3f4277fafe django start project steps reordered, in order to install django in venv instead of /usr 2019-12-10 12:13:04 -07:00
Julien Le Coupanec 5f0b94b7c2 style(django): remove empty lines 2019-12-09 11:51:16 +01:00
Julien Le Coupanec 4aa6588b3d Merge pull request #105 from qiisziilbash/django-project-commands
Django project commands
2019-12-09 11:50:05 +01:00
Julien Le Coupanec 65f7f7fda3 style(git): rework 2019-12-09 11:48:40 +01:00
Julien Le Coupanec 0aea889c05 Merge pull request #104 from qiisziilbash/git-cheatsheet
git cheatsheet is added
2019-12-09 11:44:49 +01:00
qiisziilbash 5b2794a35e Django start project and deployment steps were added 2019-12-08 17:50:49 -07:00
qiisziilbash 66c417155a git cheatsheet is added 2019-12-08 16:52:57 -07:00
Julien Le Coupanec 394910144d style(laravel): remove empty spaces 2019-12-06 14:15:34 +01:00
Julien Le Coupanec 7473bd427d Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2019-12-06 14:06:37 +01:00
Julien Le Coupanec 12e8b98f33 docs(laravel): add validation fields 2019-12-06 14:06:33 +01:00
Julien Le Coupanec ab94980dd5 Merge pull request #103 from pfeinsondev/patch-1
Update django.py
2019-11-21 09:45:28 +01:00
pfeinsondev b7a5aa284c Update django.py
Ammend runserver with optional port parameter. Useful if 8000 is unavailable.
2019-11-20 21:37:39 -08:00
Julien Le Coupanec 393164662c Merge pull request #76 from tintinsnowy/master
XML cheat sheet
2019-11-17 17:37:12 +01:00
Julien Le Coupanec d0c4d84c72 Merge pull request #101 from JenniferStamm/patch-1
update redis cheatsheet
2019-11-01 19:13:17 +01:00
JenniferStamm d9ff0ab379 update redis cheatsheet
HLEN had the same description as HKEYS. Fixed it to say that it gets the number of fields instead of the fields themselves.
2019-11-01 12:41:06 +01:00
Julien Le Coupanec ea73801d9b Merge pull request #100 from Alexound/master
Update on Vim.
2019-10-25 09:32:05 +02:00
Alexound c3ad4a15ab Minor additions. 2019-10-25 01:41:59 +04:00
Alexound de864ea195 Updated VIM cheatsheet a bit.
Ignore case while searching: on and off command.
Run command in multiple buffers with 'bufdo'.
2019-10-25 01:37:20 +04:00
Julien Le Coupanec 029e2b44b2 Merge pull request #99 from Alexound/master
'bash' language cheatsheet: fixed and improved.
2019-10-24 10:40:33 +02:00
Alexound 6fe0435c77 Keep working on 'bash' cheetsheet.
Minor corrections.
2019-10-24 12:02:15 +04:00
Alexound aa8b4efb86 Fixed tabs and spaces. 2019-10-24 11:52:27 +04:00
Alexound d2c01dccd4 Fixed and improved SHORTCUTS module.
Now it's 'SHORTCUTS and HISTORY'.
2019-10-24 11:41:37 +04:00
Alexound f0fae838f8 Added match '*.swp' to work with Vim in 'gitgnore'. 2019-10-24 11:21:36 +04:00
Julien Le Coupanec 52e18e5933 Merge pull request #98 from XVR147/html_small_fix
Html small fix
2019-10-16 22:28:31 +02:00
XVR147 7915beb1d6 Merge branch 'html_small_fix' of https://github.com/XVR147/awesome-cheatsheets into html_small_fix 2019-10-16 20:47:04 +02:00
XVR147 1eec2b0273 Fix small errors in HTML cheatsheet
Just some casing, spacing  and misspelling fixes.
2019-10-16 20:44:13 +02:00
XVR147 c946fe9b67 Fix small errors in HTML cheatsheet
Just some casing and misspelling fixes.
2019-10-16 20:39:29 +02:00
Julien Le Coupanec 32a915da58 docs(readme): updates 2019-10-12 20:58:43 +02:00
Julien Le Coupanec 1df7874d1d Merge branch 'amaurybsouza-master' 2019-10-12 12:42:44 +02:00
Julien Le Coupanec 03581585cf docs(bash): align comments 2019-10-12 12:42:32 +02:00
Amaury Souza a552f052d1 Update bash.sh 2019-10-11 22:12:09 -03:00
Julien Le Coupanec 926b0cb279 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2019-10-11 18:28:26 +02:00
Julien Le Coupanec 56d8d41136 docs(vscode): add better comments 2019-10-11 18:28:24 +02:00
Julien Le Coupanec b473bf3c66 Merge pull request #96 from thewolfcommander/patch-8
Four more django-admin commands added
2019-10-10 22:20:49 +02:00
Manoj Tyagi d309cb8546 Reordered the commands alphabetically 2019-10-11 00:17:27 +05:30
Manoj Tyagi 166ca58ac3 Four more django-admin commands added
I have added four more app-related django-admin commands.
2019-10-10 23:45:55 +05:30
Julien Le Coupanec 1bdc64dcf1 Merge pull request #93 from neo-0224/patch-5
Google Cloud Platform Cheat sheet in Tools section
2019-10-01 16:42:31 +02:00
Julien Le Coupanec 3aff588350 Merge pull request #94 from neo-0224/patch-6
Cheat sheet added for Sublime Text 3
2019-10-01 16:42:09 +02:00
Manoj Tyagi 70e7886997 Cheat sheet added for Sublime Text 3
A well-described cheat sheet for Sublime Text 3 added for tools section.
2019-09-30 22:35:29 +05:30
Manoj Tyagi 4042809cde Google Cloud Platform Cheat sheet in Tools section
I have added Most used Google Cloud Platform Cheat Sheet in the Tools section of the repository
2019-09-30 21:53:37 +05:30
Julien Le Coupanec 710ec22c52 Merge pull request #92 from neo-0224/master
Added Heroku CLI in tools subsection in Readme
2019-09-30 14:00:39 +02:00
Manoj Tyagi c3861473e8 Added Heroku CLI in tools subsection 2019-09-30 13:59:16 +05:30
Julien Le Coupanec 841dc6ce33 docs(django): update 2019-09-24 09:26:33 +02:00
Julien Le Coupanec ac2dca8860 Merge pull request #91 from neo-0224/patch-4
Some more django-admin commands added
2019-09-23 22:18:14 +02:00
Julien Le Coupanec c77151fb31 Merge pull request #90 from neo-0224/patch-3
Created basic cheatsheet for Heroku CLI
2019-09-23 22:17:45 +02:00
Manoj Tyagi a38e141789 Some more django-admin commands added
I have added some more useful and some advanced django-admin commands with there use and description in a proper format.
2019-09-24 01:30:10 +05:30
Manoj Tyagi dfe3d9c173 Created basic cheatsheet for Heroku CLI
I have created a cheat sheet on Heroku CLI where I have included all the basic commands with basic deployment methods needed to deploy and manage the application on the Heroku platform
2019-09-24 00:38:07 +05:30
Julien Le Coupanec 92b9bd8403 Merge pull request #89 from arkadiusjonczek/master
Add trait example to php language
2019-09-17 20:59:38 +02:00
Arkadius Jonczek 12e5e7747e add trait example to php language 2019-09-13 23:26:53 +02:00
Julien Le Coupanec d9eee18d87 docs(vscode): add XML Format plugin 2019-09-07 16:32:05 +02:00
Julien Le Coupanec 68933acade docs(laravel): update Valet commands 2019-09-05 13:39:35 +02:00
Julien Le Coupanec 7d7afdd218 docs(laravel): add valet commands 2019-09-05 12:57:22 +02:00
Julien Le Coupanec bde96af436 Merge pull request #88 from sudhakar3697/patch-1
Fixing a missed spacing
2019-08-30 12:59:37 +02:00
Sudhakar R 75058411bb Fixing a missed spacing 2019-08-29 15:50:13 +05:30
Julien Le Coupanec c6251b8fd9 Merge pull request #87 from daffl/patch-1
Update FeathersJS cheatsheet to Feathers v4
2019-08-28 18:19:05 +02:00
David Luecke 432c2c8bec Update FeathersJS cheatsheet to Feathers v4 2019-08-28 08:57:12 -07:00
Julien Le Coupanec 81eae536b6 Merge pull request #86 from artic92/bash-cheatsheet-correction
Corrected the bash cheatsheet
2019-08-03 15:00:41 +03:00
Antonio Riccio 1dfacb674a Corrected the bash cheatsheet
- modified the condition to verify if two values are identical
2019-08-01 11:06:56 +01:00
Julien Le Coupanec b5923b7b59 Merge pull request #85 from MoeLove/add-docker-volume-and-network-prune
Add docker volume prune and docker network prune
2019-07-21 12:49:04 +02:00
Jintao Zhang dd8dbbfe48 Add docker volume prune and docker network prune
Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com>
2019-07-21 07:55:07 +08:00
Julien Le Coupanec 7536d71c8d docs(nanobox): update django by laravel 🌟 2019-04-24 23:44:54 +02:00
Julien ba836197c6 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2019-04-24 18:54:30 +02:00
Julien c396e8470c docs(laravel): http tests assertions 2019-04-24 18:54:25 +02:00
Julien Le Coupanec 020b3fc0f6 Merge pull request #81 from HemendraKhatik/master
Update html5.html
2019-04-13 12:06:20 +02:00
HemendraKhatik 461ae708cc Update html5.html 2019-04-13 04:19:28 +05:30
Julien Le Coupanec dfd1be5c7a Merge pull request #80 from sodrooome/master
updated django-admin command
2019-04-11 10:07:47 +02:00
Ryan Febriansyah 4e10d483d3 updated django-admin command 2019-04-11 04:15:52 +07:00
Julien Le Coupanec 949563b81e Merge pull request #78 from neo-0224/patch-1
Doctype description added
2019-04-10 18:09:06 +02:00
Manoj Tyagi e5d1451172 Doctype description added 2019-04-10 16:23:33 +05:30
Julien 29e2ad39ad docs(laravel): add sections 2019-04-08 09:24:15 +02:00
Julien 94fe7a0acf docs(vscode): add phpdoc-comment-vscode-plugin 2019-03-07 11:17:51 +01:00
Sherry Yang a54791651f XML cheat sheet
Add first part of XML cheat sheet to the repository
2019-03-05 15:25:54 +01:00
Julien 08338adb42 docs(readme): remove contribution companies 2019-02-24 23:38:39 +01:00
Julien c93d3ba9f8 docs(vscode): add PHP CS Fixer 2019-02-19 21:34:33 +01:00
Julien bb2465e318 docs(vscode): add Better PHPUnit 2019-02-19 21:26:39 +01:00
Julien afad9d57c6 docs(vscode): Laravel Artisan 2019-02-19 21:21:28 +01:00
Julien 4476c4c068 docs(vscode): add PHP IntelliSense 2019-02-19 20:35:41 +01:00
Julien 4bf211eca5 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2019-02-19 18:01:25 +01:00
Julien dbb804db47 docs(vscode): add File Utils 2019-02-19 18:01:23 +01:00
Julien Le Coupanec f0b8bfd000 Merge pull request #74 from davidbonachera/patch-1
Update README.md
2019-02-18 11:45:45 +01:00
David Bonachera 692d02541c Update README.md
...
2019-02-18 09:46:21 +08:00
Julien 21a257f4cf docs(laravel): CLI commands 2019-02-15 19:23:18 +01:00
Julien 29819a501c docs(laravel): initialize cheatsheet 2019-02-11 15:15:57 +01:00
Julien 9760107f15 docs(vscode): add vue peek 2019-02-01 10:01:03 +01:00
Julien 792127225d docs(vscode): reorder extensions alphabetically 2019-01-30 20:57:37 +01:00
Julien b8cc65da79 docs(vscode): add project manager extension 2019-01-30 20:57:07 +01:00
Julien 0efbdbbf90 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2019-01-30 20:30:36 +01:00
Julien 5f47884190 docs(vscode): rework settings 2019-01-30 20:30:34 +01:00
Julien Le Coupanec f12fe74e26 Merge pull request #70 from hoangtrongphuc/patch-1
Add docker-compose run command.
2019-01-21 11:33:54 +01:00
Hoàng Phúc e9242e41d1 Add docker-compose run command. 2019-01-21 16:44:32 +07:00
Julien 6d47c4b9e2 docs(sails): add updateOne, destroyOne and archiveOne 2018-11-24 10:31:01 +01:00
Julien Le Coupanec 2db929607b Merge pull request #66 from ccalamos/CCalamos
#18 Additions to Visual Mode
2018-10-15 07:21:35 +01:00
Cole J Calamos 8d89aa9bbc #18 Additions to Visual Mode 2018-10-12 15:36:24 -04:00
Julien bff426a62f docs(readme): update with new website 2018-09-10 01:21:51 +02:00
Julien 63b0213e57 build(.gitignore): don't push .DS_Store files 2018-09-09 16:02:59 +02:00
Julien ac8c757aa7 docs(website): remove the docs folder 2018-09-09 15:59:28 +02:00
Julien b7f89c8d79 docs(website): initialize the docs folder 2018-09-09 15:49:51 +02:00
Julien LE COUPANEC 746afa5649 VSCODE: update plugins 2018-09-04 11:56:52 +01:00
Julien LE COUPANEC 0d757dc98d Fix issue with C# 2018-08-08 16:59:41 +01:00
Julien LE COUPANEC 14832b1be4 Add C C# to README.md 2018-08-08 16:58:17 +01:00
Julien LE COUPANEC d02b880d4a Move C# to languages 2018-08-08 16:57:15 +01:00
Julien Le Coupanec 41c2ad6117 Merge pull request #63 from raulvillora/master
Create C#.txt
2018-08-08 11:10:41 +01:00
Raúl Villora Valencia f1eaddaa1e Create C#.txt
Created a new cheatsheet about the C# language.
2018-08-06 19:22:04 +02:00
Julien Le Coupanec 177ff62007 Merge pull request #59 from AyoubEd/patch-1
Update redis.sh
2018-07-27 20:11:51 +01:00
AyoubED a990a380c9 Update redis.sh 2018-07-27 12:09:23 +01:00
Julien Le Coupanec 8019c0b96f Merge pull request #58 from nighcrawl/master
Fix meaning of HTML <em></em> tag
2018-07-14 16:40:33 +02:00
Ange Chierchia 0983d1723a Fix meaning of HTML <em></em> tag 2018-07-14 08:38:05 +00:00
Julien LE COUPANEC 0e2d63f30b Sails: Web sockets 2018-06-30 17:13:15 +01:00
Julien LE COUPANEC 559363f740 Sails - Waterline ORM 2018-06-29 21:38:40 +01:00
Julien LE COUPANEC 4aad09caaa Sails.js - Response methods 2018-06-28 21:25:13 +01:00
Julien LE COUPANEC 38550db0c3 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2018-06-28 17:06:54 +01:00
Julien LE COUPANEC 25d27efdc9 Sails.js - Request object 2018-06-28 16:41:30 +01:00
Julien Le Coupanec 7c78a91d7f Merge pull request #39 from raulvillora/master
Create C.txt
2018-06-28 13:09:55 +01:00
Julien Le Coupanec e560ca4a1c Merge pull request #49 from kobus1998/master
Update PHP
2018-06-28 13:04:42 +01:00
Julien LE COUPANEC b0ddf7b1c9 Update README.md 2018-06-28 13:02:27 +01:00
Julien LE COUPANEC 9a9efdd665 Add Sails.js to JavaScript backends 2018-06-28 11:05:10 +01:00
Julien LE COUPANEC 0c5250d320 Update README.md 2018-06-28 11:04:32 +01:00
Julien LE COUPANEC 57bb08b828 Sails: configuration object 2018-06-28 10:53:33 +01:00
Julien LE COUPANEC b9c6d28445 Link back to the Angular Cheatsheet 2018-06-27 22:30:08 +01:00
Julien LE COUPANEC 9ab6a07d5b Sails: Command-line interface 2018-06-27 13:20:17 +01:00
Julien LE COUPANEC 2c2b2fe384 Sails: Update blueprint API 2018-06-27 11:35:27 +01:00
Julien LE COUPANEC 87df4a5bff Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2018-06-27 11:02:54 +01:00
Julien LE COUPANEC 59496b6a36 Sails - Blueprint API 2018-06-27 11:02:49 +01:00
Julien Le Coupanec 1eb798ba5c Merge pull request #57 from chenyang1992/chen_format_docker_cheatsheet
Format docker cheatsheet in last section
2018-06-26 23:26:14 +01:00
Julien LE COUPANEC 56cb46a209 Sails.js (application) 2018-06-26 22:55:07 +01:00
Chen Yang 787b086ff5 reformat the docker cheatsheet 2018-06-26 10:43:26 -07:00
chenyang1992 66a85f340b Merge pull request #1 from LeCoupa/master
Update from original repo
2018-06-26 10:24:22 -07:00
Julien LE COUPANEC 83a91ce2d3 Update Angular (2+) cheatsheet 2018-06-26 09:51:58 +01:00
Julien LE COUPANEC a3b9824c4c Angular: clarify meaning of @Injectable decorator thanks to @benelliott 2018-06-26 09:50:13 +01:00
Julien LE COUPANEC 0b2dbf425c Merge branch 'angular-injectable' of https://github.com/benelliott/awesome-cheatsheets 2018-06-26 09:18:23 +01:00
Julien LE COUPANEC 743e49ff6c Update angularjs.js link for README.md 2018-06-26 09:10:13 +01:00
Julien LE COUPANEC 122d5eed2d Rename link to avoid breaking Reddit 2018-06-26 09:06:55 +01:00
Ben Elliott b539d713b7 Angular: clarify meaning of @Injectable decorator 2018-06-25 23:38:03 +01:00
Julien LE COUPANEC 9ceff1bca6 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2018-06-25 23:01:17 +01:00
Julien LE COUPANEC e0e1c82dde Rename files for angular cheatsheets 2018-06-25 23:01:12 +01:00
Julien Le Coupanec ab5f2e7290 Merge pull request #55 from lethalwire/master
Lines longer than 100 characters are formatted to have fewer than 100…
2018-06-25 22:57:44 +01:00
CSTom e999e91942 Lines longer than 100 characters are formatted to have fewer than 100 characters. 2018-06-25 15:08:17 -05:00
Julien LE COUPANEC faaebc08c9 Improve Angular cheatsheet 2018-06-25 19:24:34 +01:00
Julien LE COUPANEC 5c895d9d08 Add AngularJS 2018-06-25 19:12:22 +01:00
Julien Le Coupanec a0782c770a Merge pull request #50 from yohanmishkin/master
Ember cheatsheet
2018-06-14 18:10:34 +00:00
Julien Le Coupanec b6a3aa4d0b Merge branch 'master' into master 2018-06-14 18:10:24 +00:00
Julien Le Coupanec a19dfeb523 Merge pull request #54 from HaifaUniversity/angular-cheatsheet
Angular 2/4/5/6 cheatsheet
2018-06-06 19:23:25 +00:00
Alik Chebotar 7e12b71adb documentation(readme): angular cheatsheet added to frontend 2018-06-06 14:44:02 +03:00
Alik Chebotar 2dbd8cced5 Angular 2/4/5/6 cheatsheet 2018-06-06 14:35:22 +03:00
Tom Jebb 65619d86e8 Merge branch 'master' into master 2018-05-10 14:20:18 -04:00
Julien Le Coupanec 6dc05a7733 Merge pull request #53 from ashgupta1489/patch-1
Fixed "enctype" description.
2018-05-01 17:59:21 +02:00
Julien Le Coupanec 1b3101926b Merge pull request #52 from vnguyen94/patch-1
fix typo
2018-05-01 17:58:58 +02:00
Ashish Gupta 20e8f9c9b1 Fixed "enctype" description.
Enctype does encoding and not encryption.
2018-04-30 15:14:49 -04:00
Van Nguyen 689efabdcd fix typo 2018-04-30 10:51:31 -07:00
Julien Le Coupanec 0fc96efd89 Merge pull request #46 from stmoreau/master
JavaScript language Objects section creation
2018-04-20 22:53:15 +01:00
Yohan Mishkin 7a0defd436 A couple revisions 2018-04-20 14:31:38 -04:00
kobus 38957bd2be Merge branch 'master' of https://github.com/LeCoupa/awesome-cheatsheets
Merge
2018-04-20 10:00:58 +02:00
kobus 69684835b3 Spelling 2018-04-20 09:59:53 +02:00
kobus 44e9641f78 Die at start of file 2018-04-20 09:59:34 +02:00
kobus 6482a577f5 Printing 2018-04-20 09:58:57 +02:00
kobus d97ae72eba Ways of looping 2018-04-20 09:58:36 +02:00
kobus cc19e07269 Add link 2018-04-20 09:34:02 +02:00
kobus 5429e1d64a PHP Globals 2018-04-20 09:32:20 +02:00
Yohan Mishkin 46f33f030e Finished up first pass 2018-04-20 00:29:01 -04:00
Stephane Moreau 93264ac0e9 typo 2018-04-20 00:08:03 +01:00
Stephane Moreau d5fc4fceb5 keep the javascript cheatsheet into one single file 2018-04-20 00:05:42 +01:00
Julien Le Coupanec 5ce0c7a9ab Merge pull request #48 from jeremychauvet/master
Add clean command for Docker
2018-04-17 10:05:46 +01:00
Jérémy Chauvet 90a3cec714 Add clean command for Docker 2018-04-17 10:52:16 +02:00
Stephane Moreau 40ea7c3283 typo 2018-04-14 01:22:33 +01:00
Stephane Moreau 65bbc18233 update readme 2018-04-14 01:21:36 +01:00
Stephane Moreau 98fe3cd912 objects addition in js language 2018-04-14 01:11:26 +01:00
Stephane Moreau 0bc06946bb change file structure and edit readme 2018-04-14 00:09:02 +01:00
Julien LE COUPANEC db7b569476 README: move contributions to the bottom 2018-04-07 17:50:42 +02:00
Julien LE COUPANEC 9f9e769d85 Move everything to _design 2018-04-07 17:45:03 +02:00
Julien LE COUPANEC 04469e3842 Update README.md with new cover 2018-04-07 17:43:53 +02:00
Julien LE COUPANEC a04bda35d4 Reorganize images 2018-04-07 17:35:33 +02:00
Julien LE COUPANEC 5991111e75 Add Sketch 2018-04-07 17:35:23 +02:00
Julien LE COUPANEC 14051c5e7b Update README.md 2018-04-04 22:22:34 +02:00
Julien LE COUPANEC 21ceaa7fea AngularJS: Ng Module, Filters 2018-04-01 08:59:00 +02:00
Julien LE COUPANEC ddd96eab4c AngularJS: Directives 2018-03-31 12:17:09 +02:00
Julien LE COUPANEC d812620767 AngularJS: NG Module -> Functions 2018-03-28 15:57:26 -07:00
Julien LE COUPANEC e39a88b6f1 Sketch for coming static website 2018-03-25 00:29:27 -07:00
Julien LE COUPANEC e0312bbd19 New Awesome Cheatsheets Logos 2018-03-25 00:29:10 -07:00
Julien Le Coupanec 741a0c73bf Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2018-03-22 23:03:43 -07:00
Julien Le Coupanec 50acfb734e Initializing AngularJS cheatsheet 2018-03-22 23:03:40 -07:00
Julien Le Coupanec 6480be44b2 Merge pull request #40 from emyarod/master
Remove duplicate defaultProps explanation
2018-03-21 15:24:04 -07:00
emyarod e27ba13f0a Remove duplicate defaultProps explanation 2018-03-21 18:00:50 -04:00
Julien Le Coupanec 6bfa05d8ae React Final Cheatsheet 2018-03-19 22:46:48 -07:00
Julien Le Coupanec c31f42ef9b Add React to README.md 2018-03-19 22:12:09 -07:00
Julien Le Coupanec a7c584d8d5 React: react.dom library 2018-03-19 17:33:20 -07:00
Julien Le Coupanec e5209dbd7e React: react.component methods and properties 2018-03-18 22:38:17 -07:00
Julien Le Coupanec 54b0413a0b React: API top level 2018-03-18 19:45:29 -07:00
Julien Le Coupanec e9bbc71cfc React: Typechecking with proptypes 2018-03-15 20:08:09 -07:00
Julien Le Coupanec 5644030132 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2018-03-14 13:18:56 -07:00
Julien Le Coupanec 491be5a8dc Feathers.js: remove bash from comments 2018-03-14 13:18:13 -07:00
raulvillora 164c13f813 Create C.txt
Brief summary of C
2018-03-14 15:39:28 +01:00
Julien Le Coupanec dfa30d8776 Merge pull request #37 from keith/patch-1
Fix bash flag typo
2018-03-11 17:30:12 -07:00
Keith Smiley 6265188ee4 Fix bash flag typo
This had `-r` twice, but this one should be `-s`
2018-03-10 18:16:31 -08:00
Julien Le Coupanec 387d6c3d48 Moleculer.js updates 2018-03-10 17:11:24 -08:00
Julien Le Coupanec 6ac16cc7e2 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2018-03-10 17:09:10 -08:00
Julien Le Coupanec 6bae53f688 Update README.md 2018-03-10 17:09:05 -08:00
Julien Le Coupanec e76a374d90 Add React.js 2018-03-10 17:08:57 -08:00
Julien Le Coupanec 4aa2700721 Merge pull request #36 from icebob/master
Add Moleculer cheatsheet
2018-03-10 17:05:01 -08:00
Icebob f1fcc20a94 Add moleculer cheatsheet to backend 2018-03-10 19:43:53 +01:00
Icebob 9eb7d05caf Add moleculer cheatsheet to backend 2018-03-10 19:42:52 +01:00
Julien Le Coupanec 9a1caa363a Kubernetes: PDF version 2018-03-01 17:34:49 -08:00
Julien Le Coupanec 1c42d02878 Kubernetes: Improve header 2018-03-01 16:06:37 -08:00
Julien Le Coupanec 3c963586cf Kubernetes: improve cheatsheet formatting 2018-03-01 16:05:49 -08:00
Julien Le Coupanec 712903ad4e Merge pull request #30 from learnk8s/master
Cheatsheet for Kubernetes
2018-03-01 15:58:34 -08:00
Julien Le Coupanec 4c8bb1752b Merge branch 'master' into master 2018-03-01 15:58:25 -08:00
Julien Le Coupanec f5da645f6e README.md 2018-02-28 18:11:34 -08:00
Julien Le Coupanec 8cc75917df README: add HTML5 2018-02-28 10:49:54 -08:00
Julien Le Coupanec 54f4bb9e1f HTML: improve formatting 2018-02-28 10:47:10 -08:00
Julien Le Coupanec a724efd0b5 Merge pull request #31 from rajatpatel2113/master
HTML5 Cheatsheet
2018-02-28 10:40:50 -08:00
Rajat Patel 41afb9ce31 ADD HTML5 cheatsheet by Hackr.io 2018-02-28 11:28:43 +05:30
Rajat Patel 07ddc8414a ADD New HTML5 Cheatsheet 2018-02-28 11:14:10 +05:30
Daniele Polencic eeb4ab5b23 cheatsheet for Kubernetes 2018-02-24 17:53:43 +00:00
Julien Le Coupanec 8e872d4d93 Feathers: application architecture mistake 2018-02-21 20:41:58 -08:00
Julien Le Coupanec 6c299e00ec Feathers: application architecture 2018-02-21 20:41:58 -08:00
Julien Le Coupanec 4c880cf48e Discard last commit 2018-02-21 20:41:58 -08:00
Julien Le Coupanec 2625199e02 Xcode: switch from .txt to .md 2018-02-21 20:41:58 -08:00
Julien Le Coupanec 674fc5d190 VSCode Cheatsheet 2018-02-21 20:41:58 -08:00
Julien Le Coupanec e3f84cd5dd Merge pull request #29 from koppor/patch-1
Add awesome ALT commands
2018-02-20 23:36:06 +01:00
Oliver Kopp ab0940a4bf Add awesome ALT commands 2018-02-20 11:05:28 +01:00
Julien Le Coupanec c456873b44 Merge pull request #27 from manimax3/master
Vim: window resizing
2018-02-15 14:47:55 +01:00
manimax3 714d8233d0 Vim: window resizing 2018-02-15 14:41:22 +01:00
Julien Le Coupanec c68eb1439b Merge pull request #25 from Palivonas/patch-1
Minor typo fixes
2018-02-15 01:20:25 +01:00
Andrius Palivonas 488e7a7460 Minor typo fixes 2018-02-15 00:14:03 +00:00
Julien Le Coupanec 47e2960126 Feathers: Database - Common API & Querying 2018-02-15 00:17:26 +01:00
Julien Le Coupanec fcc980ddc6 Feathers: Authentication methods (Server, Client, Local, OAuth1, OAuth2) 2018-02-13 22:43:45 +01:00
Julien Le Coupanec 49e8d23425 Update README.md 2018-02-13 22:43:21 +01:00
Julien Le Coupanec 0d408416b8 Update README.md 2018-02-11 20:43:59 +01:00
Julien Le Coupanec abc1512346 Merge pull request #12 from snwfdhmp/patch-1
Update bash.sh
2018-02-11 20:37:31 +01:00
Julien Le Coupanec 5615c4ca85 Merge branch 'master' into patch-1 2018-02-11 20:34:08 +01:00
Julien Le Coupanec 8de7573c16 Merge pull request #24 from veber88/patch-1
Update bash.sh
2018-02-11 20:20:51 +01:00
Vitaly Bagno 2ef26d3c39 Update bash.sh 2018-02-11 21:02:37 +02:00
Julien Le Coupanec 3e7c440853 README: Fix typo 2018-02-11 19:42:30 +01:00
Julien Le Coupanec 514d5a1823 README.md: fix typo 2018-02-11 19:42:04 +01:00
Julien Le Coupanec 7399f975c8 README: add PHP cheatsheet 2018-02-11 19:41:42 +01:00
Julien Le Coupanec 9a6984369d PHP: improve formating 2018-02-11 19:39:44 +01:00
Julien Le Coupanec 16619f2e28 Merge pull request #17 from kobus1998/master
A start for PHP
2018-02-11 19:36:53 +01:00
Julien Le Coupanec 23877a3c82 Merge pull request #21 from 59023g/patch-1
BUG: bash.sh: array(val val val) -> array=(val val val)
2018-02-11 19:35:32 +01:00
Julien Le Coupanec 889cd60ac1 Docker: add comments for docker-compose methods 2018-02-11 19:33:47 +01:00
Julien Le Coupanec 1dcb38b883 Docker: improve formating 2018-02-11 19:32:13 +01:00
Julien Le Coupanec 8dbf559bdb Merge pull request #22 from amirarsalan/tools/docker
update docker-compose and add docker service command
2018-02-11 19:31:27 +01:00
Julien Le Coupanec 97f4043e86 Xcode: improve formatting 2018-02-11 19:29:21 +01:00
Julien Le Coupanec 08179d5961 Update README.md 2018-02-11 19:25:19 +01:00
Julien Le Coupanec 80f89ad98c Merge pull request #20 from congnd/master
Add Xcode Cheat Sheet
2018-02-11 19:19:17 +01:00
Julien Le Coupanec 394f046e77 Update README.md 2018-02-11 19:17:56 +01:00
Julien Le Coupanec dca4f0d99a Update README.md 2018-02-11 19:12:10 +01:00
Julien Le Coupanec 945738c992 Update README.md 2018-02-11 19:09:22 +01:00
Julien Le Coupanec 86e5c7e10e Merge pull request #11 from cristijora/patch-1
Make readme more appealing
2018-02-11 19:05:24 +01:00
Julien Le Coupanec b370cc0400 Django: update django-admin 2018-02-11 19:02:39 +01:00
Julien Le Coupanec 4458bf3822 Merge pull request #10 from shrivatsahosabettu/master
django-admin
2018-02-11 19:00:33 +01:00
Julien Le Coupanec 032f698f2d Merge pull request #9 from waqashsn/addition-to-language-javascript
Added Array.prototype in languages/javascript.js
2018-02-11 18:59:26 +01:00
Julien Le Coupanec a538a5dfdd Feathers: Client methods 2018-02-11 00:27:03 +01:00
Amir Arsalan 90ee1fbdf7 update docker-compose and add docker service command 2018-02-11 02:30:08 +03:30
Michael Pierce 9a04ba0ef4 bash.sh: array(val val val) -> array=(val val val) 2018-02-10 12:22:42 -08:00
congnd 71645edf5f [ADD] Xcode Cheat Sheet 2018-02-11 01:37:40 +09:00
Julien Le Coupanec 3877873002 Feathers - Primus transport 2018-02-10 03:32:51 +01:00
Julien Le Coupanec 4e4d66405d Feathers: Socket.io transport 2018-02-10 03:24:42 +01:00
Julien Le Coupanec 1564a59aa2 Feathers: Express transport 2018-02-10 03:08:55 +01:00
Julien Le Coupanec 12fbb4bdce Change badge position 2018-02-10 01:27:00 +01:00
Julien Le Coupanec 48390e96fe Add awesome badge 2018-02-10 01:26:12 +01:00
Julien Le Coupanec ba0c6df3c1 FeathersJS - Updates 2018-02-10 01:12:32 +01:00
Julien Le Coupanec 70a3fa3ebd Update README.md 2018-02-10 01:12:32 +01:00
Cristi Jora 21583aa127 Merge branch 'master' into patch-1 2018-02-08 15:04:35 +02:00
Julien Le Coupanec 16acbfdfa4 Merge pull request #16 from vimeitor/patch-1
Use C instead of c$ to change to end of the line
2018-02-08 12:56:18 +00:00
Kobus 17520bae35 Merge branch 'master' of https://github.com/LeCoupa/awesome-cheatsheets 2018-02-07 22:54:22 +01:00
Kobus 928f739577 php oop 2018-02-07 22:53:08 +01:00
Adrià Farrés ef808c91de Use C instead of c$ to change to end of the line 2018-02-07 18:01:27 +01:00
Julien Le Coupanec 5791c29ab6 Update README.md 2018-02-07 00:29:34 +00:00
Julien Le Coupanec ad661bbb3d Update README.md 2018-02-07 00:24:20 +00:00
Julien Le Coupanec 528b6d3e93 Update README.md with companies who contributed 2018-02-07 00:21:06 +00:00
Martin Joly f31fdaaf1b Update bash.sh 2018-02-06 15:16:09 +01:00
Cristi Jora 1b9a0ce80c Make readme more appealing
Tackle first point of #7 
Inspired by [30 seconds of code reamde](https://github.com/Chalarangelo/30-seconds-of-code)
2018-02-06 12:50:57 +02:00
shrivatsahosabettu 0422661584 django-admin
Added the django-admin commands
2018-02-06 14:45:44 +05:30
WH ba3551ccf1 Added Array.prototype in languages/javascript.js 2018-02-06 12:32:07 +05:00
Julien Le Coupanec 0853046c3c Update README.md 2018-02-06 04:39:11 +00:00
Julien Le Coupanec 3f6c5c757b Update README.md 2018-02-06 04:34:43 +00:00
Julien Le Coupanec c618bf1fe5 Update README.md 2018-02-06 04:25:56 +00:00
Julien Le Coupanec 0c397e5cf4 Update README.md 2018-02-06 04:24:49 +00:00
Julien Le Coupanec d2680863a6 Update README.md 2018-02-06 04:22:00 +00:00
Julien Le Coupanec d4f57e56d1 Update README.md 2018-02-06 04:21:12 +00:00
Julien Le Coupanec 888638b885 Update README.md 2018-02-06 03:48:55 +00:00
Julien Le Coupanec e33f0611ab Update README.md 2018-02-06 03:48:22 +00:00
Julien Le Coupanec 166b1c54cf Update README.md 2018-02-06 03:36:15 +00:00
Julien Le Coupanec 2607ae1339 Update README.md 2018-02-06 03:29:24 +00:00
Julien Le Coupanec 9156790867 Update README.md 2018-02-06 03:23:29 +00:00
Julien Le Coupanec 71e8218423 Update README.md 2018-02-06 03:02:48 +00:00
Julien Le Coupanec 55ab00dc43 Update README.md 2018-02-06 02:54:34 +00:00
Julien Le Coupanec 21d69febf4 Update README.md 2018-02-06 02:52:24 +00:00
Julien Le Coupanec f54d9905d1 Update README.md 2018-02-06 02:49:52 +00:00
Julien Le Coupanec 0178e87d76 Vim: Update header 2018-02-06 02:22:09 +00:00
Julien Le Coupanec 069057de7e Update README.md 2018-02-06 02:20:16 +00:00
Julien Le Coupanec 4152fc728a Update README.md 2018-02-06 02:17:55 +00:00
Julien Le Coupanec eab3159fbb Update README.md 2018-02-06 02:16:36 +00:00
Julien Le Coupanec 6bfd78f5e5 Update README.md 2018-02-06 02:12:16 +00:00
Julien Le Coupanec 22613b2185 Fix issue with folders 2018-02-06 02:10:51 +00:00
Julien Le Coupanec 34124c1731 Reorganizing the repository 2018-02-06 02:09:12 +00:00
Julien Le Coupanec 450f2db40b Merge pull request #8 from LeCoupa/add-license-1
Create LICENSE
2018-02-06 01:55:36 +00:00
Julien Le Coupanec 0f941d5534 Create LICENSE 2018-02-06 01:55:21 +00:00
Julien Le Coupanec d20f3f8118 Update README.md 2018-02-06 01:52:11 +00:00
Julien Le Coupanec 278aa31c11 Vim: Update cheatsheet 2018-02-06 01:48:56 +00:00
Julien Le Coupanec 54a5df7c84 Vim: cheatsheet reorganization 2018-02-06 01:43:12 +00:00
Julien Le Coupanec 9014e77b04 Update README.md 2018-02-05 23:49:49 +00:00
Julien Le Coupanec 5ca2ac5b5d Merge pull request #5 from lucifer069/patch-1
Cheatsheet for Vim
2018-02-05 23:35:03 +00:00
Prateek Kalra 3b95bd4319 Rename vim.js to vim.txt 2018-02-06 00:43:25 +05:30
Julien Le Coupanec 0d8e5eb628 Merge pull request #6 from ckreusser/master
Updated contributions grammar for easy reading.
2018-02-05 17:51:59 +00:00
Calvin Kreusser 365c219df2 Updated contributions grammar for easy reading. 2018-02-05 09:56:17 -07:00
Prateek Kalra 66fafbcf09 Cheatsheet for Vim 2018-02-05 19:23:56 +05:30
Julien Le Coupanec 1b35284c09 Update README.md 2018-02-04 23:05:00 +00:00
Julien Le Coupanec aed6bb63b6 Feathers: methods for channels 2018-02-04 20:01:13 +00:00
Julien Le Coupanec 0bd368ff75 Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets 2018-02-04 17:45:20 +00:00
Julien Le Coupanec a27ab16eb9 Feathers: event listeners 2018-02-04 17:45:17 +00:00
Julien Le Coupanec 0f21201295 Merge pull request #4 from beardedtim/patch-1
Modify description of `utils.promisify`
2018-02-04 17:30:17 +00:00
Tim Roberts 27c5b74667 Modify description of utils.promisify
This PR modifies the description of `utils.promisify` in order to more clearly explain what this function takes as an argument.
2018-02-04 11:00:57 -06:00
Julien Le Coupanec 1b7838f0e6 Merge pull request #3 from ss18/awesome-changes
Awesome changes
2018-02-04 16:29:36 +00:00
Semen Zhydenko bdde87d6af occured -> occurred 2018-02-04 17:20:34 +01:00
Semen Zhydenko 22e0b5b399 occurence -> occurrence 2018-02-04 17:20:06 +01:00
Semen Zhydenko 71d9b7be01 occurences -> occurrences 2018-02-04 17:19:44 +01:00
Semen Zhydenko 00697934e9 interupt -> interrupt 2018-02-04 17:19:09 +01:00
Semen Zhydenko 5db2e1fd4d funtion -> function 2018-02-04 17:18:44 +01:00
Julien Le Coupanec 2cd1e38b0e Feathers.js: Hook functions 2018-02-04 16:09:52 +00:00
Julien Le Coupanec caaa62d139 Node: add util.promisify 2018-02-04 15:44:46 +00:00
Julien Le Coupanec dc306a3364 Bash: Fix issue with $websites 2018-02-04 14:12:03 +00:00
Julien Le Coupanec c368ad3b06 Bash: updates 2018-02-04 13:08:13 +00:00
Julien Le Coupanec 1c56375806 Merge pull request #2 from 004413/patch-1
Bash: Fix a typo
2018-02-04 02:18:07 +00:00
Ray Hua Wu cec31441e7 fix a typo 2018-02-03 20:35:26 -05:00
Julien Le Coupanec 0892c8d365 Bash: fix mistake with for in 2018-02-03 20:24:28 +00:00
Julien Le Coupanec d05ed80faa Bash: use vim instead of emacs 2018-02-03 20:14:25 +00:00
Julien Le Coupanec 745643557b Node: buffer.from() instead of new Buffer(array) 2018-02-03 20:11:29 +00:00
Julien Le Coupanec 18d68e86a3 NodeJS: replace with Math.PI instead of 3.14 2018-02-03 20:06:39 +00:00
Julien Le Coupanec a4e4b2fff5 Bash: operators need spaces around them 2018-02-03 20:02:01 +00:00
Julien Le Coupanec 1b63ec86e7 Update README.md 2018-02-03 16:57:56 +00:00
Julien Le Coupanec 012b11138a Feathers: Service API 2018-02-03 15:47:02 +00:00
Julien Le Coupanec 892f04f1ab Feathers: application object api methods 2018-02-03 14:40:18 +00:00
Julien Le Coupanec 88879d285c Update README.md 2018-02-03 02:13:56 +00:00
Julien Le Coupanec de879e3f10 Initializing FeatherJS cheatsheet 2018-02-03 02:13:16 +00:00
Julien Le Coupanec 87657c1c4b Merge pull request #1 from stephan-nordnes-eriksen/patch-1
incorrect GETRANGE description
2018-01-27 00:07:03 +00:00
Stephan Nordnes Eriksen 360b734404 incorrect GETRANGE description
https://redis.io/commands/getrange

It seems the GETRANGE description is incorrect. Updated for correctness.

Perhaps the longer description is better; `# get substring of the value stored in key, determined by the offsets start and end (both are inclusive).`
2018-01-26 08:51:10 +01:00
Julien Le Coupanec fd83adda70 Final VueJS Cheatsheet 2017-12-02 00:46:12 +01:00
Julien Le Coupanec 9b88a9d406 Vue: options misc 2017-12-02 00:36:30 +01:00
Julien Le Coupanec d31a41c683 Vue: options / assets 2017-12-01 23:51:23 +01:00
Julien Le Coupanec d43e737e1b Vue: special attributes 2017-12-01 23:18:02 +01:00
Julien Le Coupanec 848911f5bc Vue: directives 2017-12-01 15:36:30 +01:00
Julien Le Coupanec 4b0da67c73 Vue: lifecycle instance methods 2017-12-01 13:48:35 +01:00
Julien Le Coupanec b04042f56a Vue: instance methods events 2017-12-01 13:38:05 +01:00
Julien Le Coupanec e49a31edf8 Vue: Instance Methods / Data 2017-12-01 13:28:16 +01:00
Julien Le Coupanec 708173004a Vue: instance properties 2017-12-01 13:04:37 +01:00
Julien Le Coupanec d3c1292b09 Vue: lifecycle hooks 2017-11-29 01:35:18 +01:00
Julien Le Coupanec 909378aa3e Vue: options > dom 2017-11-29 00:41:46 +01:00
Julien Le Coupanec 6c98441553 Vue.js: options data 2017-11-21 20:15:36 +00:00
Julien Le Coupanec 0206d6f099 Vue: global API 2017-11-20 22:35:29 +00:00
Julien Le Coupanec 575c1bc653 Vue.js: global config 2017-11-20 21:12:42 +00:00
Julien Le Coupanec 25c104915d Update README.md 2017-11-18 17:32:02 +00:00
Julien Le Coupanec a6c52438bd Update cheatsheets 2017-11-18 17:22:37 +00:00
Julien Le Coupanec 5c488dab02 Vue cheatsheet 2017-11-18 17:22:28 +00:00
Julien Le Coupanec f4ec8cd116 Django cheatsheet 2017-11-18 17:22:05 +00:00
Julien Le Coupanec 80b7301534 Add Redis cheatsheet 2017-11-12 01:06:57 +00:00
Julien Le Coupanec 4cd93d84f8 Add Docker cheatsheet 2017-11-11 23:28:02 +00:00
Julien Le Coupanec f912b540b8 Update Readme.md 2017-11-11 23:19:02 +00:00
Julien Le Coupanec 84fe55ed6b Add Bash cheatsheet 2017-11-11 23:17:07 +00:00
Julien Le Coupanec 35ac733b20 Add Node.js cheatsheet 2017-11-11 19:01:08 +00:00
Julien Le Coupanec d80605ac6b Update README.md 2017-11-09 15:57:32 +00:00
Julien Le Coupanec 6f663cc828 Update Nanobox cheatsheet 2017-11-09 12:56:44 +00:00
Julien Le Coupanec ec5e178ec6 Update README.md 2017-11-09 04:12:05 +00:00
Julien Le Coupanec ac36666864 Update README.md 2017-11-09 04:11:43 +00:00
Julien Le Coupanec 48c8cd1d58 Update README.md 2017-11-09 04:10:47 +00:00
Julien Le Coupanec 3ecdf8a4f8 Update README.md 2017-11-09 04:09:26 +00:00
Julien Le Coupanec c352686998 Update README.md 2017-11-09 04:07:11 +00:00
Julien Le Coupanec 213feaef6d Update README.md 2017-11-09 04:03:20 +00:00
Julien Le Coupanec f557653039 Add README.md 2017-11-09 04:02:29 +00:00
Julien Le Coupanec 234241a6cf Tools: add Nanobox 2017-11-09 03:50:33 +00:00
Julien Le Coupanec ccb9f907d5 Move to languages folder 2017-11-09 02:50:31 +00:00
Julien Le Coupanec 2b43adf72c JavaScript: global objects > array 2017-11-09 02:49:11 +00:00
109 changed files with 18112 additions and 177 deletions
+8
View File
@@ -0,0 +1,8 @@
# Miscelleaneous
.DS_Store
# Editors
.vscode/
# Vim
*.swp
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no -- commitlint --edit ""
View File
-9
View File
@@ -1,9 +0,0 @@
<!DOCTYPE html>
<html data-n-head="">
<head>
<meta data-n-head="true" charset="utf-8"/><meta data-n-head="true" name="viewport" content="width=device-width, initial-scale=1"/><meta data-n-head="true" data-hid="description" name="description" content="Designed for the ones who enjoy dark interfaces as much as we do. Using the best UX practices for great conversion rates."/><title data-n-head="true">Awesome Cheatsheets</title><link data-n-head="true" rel="icon" type="image/x-icon" href="/favicon.ico"/><link rel="preload" href="/awesome-cheatsheets/_nuxt/manifest.3418ea614aef952d91e6.js" as="script" /><link rel="preload" href="/awesome-cheatsheets/_nuxt/vendor.8c8c4b8e213271f210af.js" as="script" /><link rel="preload" href="/awesome-cheatsheets/_nuxt/app.b7fbba3d0b8c9da004ba.js" as="script" /><link rel="prefetch" href="/awesome-cheatsheets/_nuxt/layouts/default.2179d0657b6bc059b4b8.js" /><link rel="prefetch" href="/awesome-cheatsheets/_nuxt/pages/index.c123f450264aa4af335d.js" />
</head>
<body data-n-head="">
<div id="__nuxt"><style>body, html, #__nuxt { background-color: white; width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; margin: 0; padding: 0;}.spinner { width: 40px; height: 40px; margin: 100px auto; background-color: #dbe1ec; border-radius: 100%; -webkit-animation: sk-scaleout 1.0s infinite ease-in-out; animation: sk-scaleout 1.0s infinite ease-in-out;}@-webkit-keyframes sk-scaleout { 0% { -webkit-transform: scale(0) } 100% { -webkit-transform: scale(1.0); opacity: 0; }}@keyframes sk-scaleout { 0% { -webkit-transform: scale(0); transform: scale(0); } 100% { -webkit-transform: scale(1.0); transform: scale(1.0); opacity: 0; }}</style><div class="spinner"> <div class="double-bounce1"></div> <div class="double-bounce2"></div></div><!-- http://tobiasahlin.com/spinkit --></div>
<script type="text/javascript" src="/awesome-cheatsheets/_nuxt/manifest.3418ea614aef952d91e6.js"></script><script type="text/javascript" src="/awesome-cheatsheets/_nuxt/vendor.8c8c4b8e213271f210af.js"></script><script type="text/javascript" src="/awesome-cheatsheets/_nuxt/app.b7fbba3d0b8c9da004ba.js"></script></body>
</html>
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Julien Le Coupanec
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+139
View File
@@ -0,0 +1,139 @@
[![AWESOME CHEATSHEETS LOGO](_design/cover_github@2x.png)](https://lecoupa.github.io/awesome-cheatsheets/)
[![Awesome](https://awesome.re/badge.svg)](https://awesome.re) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/LeCoupa/awesome-cheatsheets/blob/master/LICENSE)
**WEBSITE DIRECTORY**: [Available here](https://lecoupa.github.io/awesome-cheatsheets/).
> 📚 Awesome cheatsheets for popular programming languages, frameworks and development tools. They include everything you should know in one single file.
## 🤔 Why Awesome-Cheatsheets?
I usually make a cheat sheet when I want to improve my skills in a programming language, a framework or a development tool. [I started doing these kinds of things a long time ago on Gist](https://gist.github.com/LeCoupa). To better keep track of the history and to let people contribute, I re-organized all of them into this single repository. Most of the content is coming from official documentation and some books I have read.
Feel free to take a look. You might learn new things. They have been designed to provide a quick way to assess your knowledge and to save you time.
## 📚 Table of Contents
### 📃 Languages
<details>
<summary>View cheatsheets</summary>
#### Command line interface
- [Bash](languages/bash.sh)
#### Imperative
- [C](languages/C.txt)
- [C#](languages/C%23.txt)
- [Go](languages/golang.md)
- [Java](languages/java.md)
- [PHP](languages/php.php)
- [Python](languages/python.md)
#### Functional
- [JavaScript](languages/javascript.js)
</details>
### 📦 Backend
<details>
<summary>View cheatsheets</summary>
#### PHP
- [Laravel](backend/laravel.php)
#### Python
- [Django](backend/django.py)
#### Javascript
- [Adonis.js](backend/adonis.js)
- [Express.js](backend/express.js)
- [Feathers.js](backend/feathers.js)
- [Moleculer](backend/moleculer.js)
- [Node.js](backend/node.js)
- [Sails.js](backend/sails.js)
</details>
### 🌐 Frontend
<details>
<summary>View cheatsheets</summary>
#### Basics
- [HTML5](frontend/html5.html)
- [CSS3](frontend/css3.css)
#### Frameworks
- [React.js](frontend/react.js)
- [Vue.js](frontend/vue.js)
- [Tailwind.css](frontend/tailwind.css)
- [Ember.js](frontend/ember.js)
- [Angular (2+)](frontend/angular.js)
- [AngularJS](frontend/angularjs.js)
</details>
### 🗃️ Databases
<details>
<summary>View cheatsheets</summary>
#### SQL
- [MySQL](databases/mysql.sh)
#### NoSQL
- [Redis](databases/redis.sh)
</details>
### 🔧 Tools
<details>
<summary>View cheatsheets</summary>
#### Development
- [cURL](tools/curl.sh)
- [Drush](tools/drush.sh)
- [Elasticsearch](tools/elasticsearch.js)
- [Emmet](tools/emmet.md)
- [Git](tools/git.sh)
- [Puppeteer](tools/puppeteer.js)
- [Sublime Text](tools/sublime_text.md)
- [VIM](tools/vim.txt)
- [Visual Studio Code](tools/vscode.md)
- [Xcode](tools/xcode.txt)
- [Pieces](https://pieces.app/)
#### Infrastructure
- [AWS CLI](tools/aws.sh)
- [Docker](tools/docker.sh)
- [Heroku CLI](tools/heroku.sh)
- [Kubernetes](tools/kubernetes.md)
- [Nanobox Boxfile](tools/nanobox_boxfile.yml)
- [Nanobox CLI](tools/nanobox_cli.sh)
- [Nginx](tools/nginx.sh)
- [PM2](tools/pm2.sh)
- [Ubuntu](tools/ubuntu.sh)
- [Firebase CLI](tools/firebase_cli.md)
</details>
## 🙌🏼 How to Contribute?
You are more than welcome to contribute and build your own cheat sheet for your favorite programming language, framework or development tool. Just submit changes via pull request and I will review them before merging.
## 👩‍💻👨‍💻 Our valuable Contributors
<p align="center"><a href="https://github.com/LeCoupa/awesome-cheatsheets/graphs/contributors">
<img src="https://contributors-img.web.app/image?repo=LeCoupa/awesome-cheatsheets" />
</a></p>
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

-25
View File
@@ -1,25 +0,0 @@
/*!
* Vue.js v2.5.17
* (c) 2014-2018 Evan You
* Released under the MIT License.
*/
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version v4.2.4+314e4831
*/
/**
* vue-meta v1.5.3
* (c) 2018 Declan de Wet & Sébastien Chopin (@Atinux)
* @license MIT
*/
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
!function(e){var n=window.webpackJsonp;window.webpackJsonp=function(t,a,c){for(var u,i,f,s=0,l=[];s<t.length;s++)i=t[s],r[i]&&l.push(r[i][0]),r[i]=0;for(u in a)Object.prototype.hasOwnProperty.call(a,u)&&(e[u]=a[u]);for(n&&n(t,a,c);l.length;)l.shift()();if(c)for(s=0;s<c.length;s++)f=o(o.s=c[s]);return f};var t={},r={4:0};function o(n){if(t[n])return t[n].exports;var r=t[n]={i:n,l:!1,exports:{}};return e[n].call(r.exports,r,r.exports,o),r.l=!0,r.exports}o.e=function(e){var n=r[e];if(0===n)return new Promise(function(e){e()});if(n)return n[2];var t=new Promise(function(t,o){n=r[e]=[t,o]});n[2]=t;var a=document.getElementsByTagName("head")[0],c=document.createElement("script");c.type="text/javascript",c.charset="utf-8",c.async=!0,c.timeout=12e4,o.nc&&c.setAttribute("nonce",o.nc),c.src=o.p+""+({0:"layouts/default",1:"pages/index"}[e]||e)+"."+{0:"2179d0657b6bc059b4b8",1:"c123f450264aa4af335d"}[e]+".js";var u=setTimeout(i,12e4);function i(){c.onerror=c.onload=null,clearTimeout(u);var n=r[e];0!==n&&(n&&n[1](new Error("Loading chunk "+e+" failed.")),r[e]=void 0)}return c.onerror=c.onload=i,a.appendChild(c),t},o.m=e,o.c=t,o.d=function(e,n,t){o.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:t})},o.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(n,"a",n),n},o.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},o.p="/awesome-cheatsheets/_nuxt/",o.oe=function(e){throw console.error(e),e}}([]);
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+474
View File
@@ -0,0 +1,474 @@
/********************************************************************************************
* ADONIS CHEATSHEET
* https://adonisjs.com/
********************************************************************************************/
/********************************************************************************************
* AVAILABLE CLI COMMANDS
* https://adonisjs.com/docs/ace
********************************************************************************************/
build // Compile typescript code to Javascript. Optionally watch for file changes.
invoke // Invoke post install instructions on a given AdonisJs package.
serve // Compile typescript code to Javascript and start the HTTP server.
// Dump
dump:rcfile // Dump contents of .adonisrc.json file along with defaults.
// Generate
generate:key // Generate a new APP_KEY secret.
generate:manifest // Generate manifest file to execute ace commands.
// List
list:routes // List application routes.
// Make
make:command // Make a new ace command.
make:controller // Make a new HTTP controller.
make:middleware // Make a new middleware.
make:migration // Make a new migration.
make:provider // Make a new IoC container provider.
make:validator // Make a new validator.
make:view // Make a new view template.
// Migrations
migration:run // Run all pending migrations.
migration:rollback // Rollback last set of migrations.
migration:refresh // Rollback all migrations to the 0 batch then re-run them from the start.
migration:reset // Rollback all migrations to the 0 batch.
migration:status // Get the status of all the migrations.
/********************************************************************************************
* REQUEST
* https://adonisjs.com/docs/request
********************************************************************************************/
request.all() // Returns an object containing all request data (merges query params and request body data).
request.get() // Returns an object containing query params data.
request.post() // Returns an object containing request body data.
request.raw() // Returns raw body data as a string.
request.only(['username', 'age']) // Returns an object with only the specified keys.
request.collect(['username', 'age']) // Formats so its ready to save to the database.
request.except(['csrf_token', 'submit']) // Returns an object with everything except the specified keys (opposite of only).
request.input('drink', 'coffee') // Get the value of a given key (if it doesnt exist, return the default value).
request.headers() // Returns an object of all header data.
request.header('some-other-header', 'default') // The header value for a given key (optionally with default value).
request.cookies() // Returns an object of all cookie data.
request.cookie('cart_total', 0) // Returns the cookie value for a given key (optionally with default value).
request.plainCookies() // Returns an object of all raw cookie data.
request.plainCookie('cart_total', 0) // Returns the raw cookie value for a given key (optionally with default value).
request.accepts(['json', 'html']) // Reads the Accept header to help determine the response format.
request.language(['en', 'fr']) // Language can also be negotiated based upon the Accept-Language header.
request.url() // Returns the current request url.
request.originalUrl() // Returns the full current request url with query strings.
request.method() // Returns the HTTP request method.
request.intended() // Returns the intended request HTTP method.
request.ip() // Returns the most trusted ip address for the user.
request.ips() // Returns an array of ips from most to the least trusted (removes the default ip address, which can be accessed via the ip method).
request.subdomains() // Returns a list of request subdomains (removes www from the list).
request.ajax() // Checks for X-Requested-With header to determine if the request is ajax or not.
request.pjax() // This methods looks for the X-PJAX header to identify if a request is pjax or not.
request.hostname() // Returns the request hostname.
request.protocol() // Return the request protocol.
request.match(['posts/:id']) // Returns whether the passed set of expressions match the current request URL.
request.hasBody() // A boolean indicating if the request has a post body (mainly used by the BodyParser to determine whether or not to parse the body).
request.is(['json', 'html']) // The is method returns the best matching content type for the current request. The check is entirely based upon the content-type header.
/********************************************************************************************
* RESPONSE
* https://adonisjs.com/docs/response
********************************************************************************************/
response.header("Content-type", "application/json"); // Set a header value.
response.safeHeader("Content-type", "application/json"); // Only set a header value if it does not already exist.
response.removeHeader("Content-type"); // Remove an existing header.
response.type("application/json"); // Set the Content-Type header.
response.cookie("cartTotal", 20); // Set a cookie value.
response.clearCookie("cartTotal"); // Remove an existing cookie value (by setting its expiry in the past).
response.plainCookie("cartTotal", 20); // Set a plain cookie.
response.redirect(url, [(sendParams = false)], [(status = 302)]); // Redirect request to a different url (by default it will set the status as 302).
response.route(route, [data], [domain], [(sendParams = false)], [(status = 302)]); // Redirect to a route (via route name or controller method).
response.download(filePath); // Stream the file to the client.
response.attachment(filePath, [name], [disposition]); // Force download the file.
response.continue(); // 100 status code
response.switchingProtocols(); // 101 status code
response.ok(); // 200 status code
response.created(); // 201 status code
response.accepted(); // 202 status code
response.nonAuthoritativeInformation(); // 203 status code
response.noContent(); // 204 status code
response.resetContent(); // 205 status code
response.partialContent(); // 206 status code
response.multipleChoices(); // 300 status code
response.movedPermanently(); // 301 status code
response.found(); // 302 status code
response.seeOther(); // 303 status code
response.notModified(); // 304 status code
response.useProxy(); // 305 status code
response.temporaryRedirect(); // 307 status code
response.badRequest(); // 400 status code
response.unauthorized(); // 401 status code
response.paymentRequired(); // 402 status code
response.forbidden(); // 403 status code
response.notFound(); // 404 status code
response.methodNotAllowed(); // 405 status code
response.notAcceptable(); // 406 status code
response.proxyAuthenticationRequired(); // 407 status code
response.requestTimeout(); // 408 status code
response.conflict(); // 409 status code
response.gone(); // 410 status code
response.lengthRequired(); // 411 status code
response.preconditionFailed(); // 412 status code
response.requestEntityTooLarge(); // 413 status code
response.requestUriTooLong(); // 414 status code
response.unsupportedMediaType(); // 415 status code
response.requestedRangeNotSatisfiable(); // 416 status code
response.expectationFailed(); // 417 status code
response.unprocessableEntity(); // 422 status code
response.tooManyRequests(); // 429 status code
response.internalServerError(); // 500 status code
response.notImplemented(); // 501 status code
response.badGateway(); // 502 status code
response.serviceUnavailable(); // 503 status code
response.gatewayTimeout(); // 504 status code
response.httpVersionNotSupported(); // 505 status code
/********************************************************************************************
* ROUTING
* https://adonisjs.com/docs/routing
********************************************************************************************/
Route.get(url, closure) // Register route for GET verb.
Route.post(url, closure) // Register route for POST verb.
Route.put(url, closure) // Register route for PUT verb.
Route.patch(url, closure) // Register route for PATCH verb.
Route.delete(url, closure) // Register route for DELETED verb.
Route.any(url, closure) // Register route for all HTTP verbs.
Route.on('/').render('welcome') // Render a view directly.
Route.route('/', () => {}, ['GET', 'POST', 'PUT']) // Register route for multiple verbs.
Route.get('users', closure).as('users.index') // Assign a unique name to the route.
Route.get('users', closure).formats(['json', 'html'], true) // Force client to define the route format.
Route.resource('users', 'UserController') // Define a resource route for CRUD operations.
Route.resource('users', 'UserController').apiOnly() // Remove create and edit routes.
Route.resource('users', 'UserController').only(['index']) // Keeps only the passed routes.
Route.resource('users', 'UserController').except(['index']) //Keeps all routes except the passed routes.
Route.group(() => {}) // Define a group of routes.
Route.group(() => {}).middleware(['auth']) // Attach a middleware.
Route.group(() => {}).formats(['json']) // Define response formats.
Route.group(() => {}).prefix('api/v1') // Define a prefix for a group of routes.
Route.group(() => {}).namespace('Admin') // Prefix the namespace of the bound controller.
Route.group(() => {}).domain('blog.sthg.com') // Specify which domain goup routes belong to.
/********************************************************************************************
* VALIDATOR
* https://indicative-v5.adonisjs.com/
********************************************************************************************/
const indicative = require("indicative");
const rules = {
email: "required|email|unique:users",
password: "required|min:6|max:30",
};
// Indivative methods
indicative.validate(data, rules); // Validate data with defined rules.
indicative.validateAll(data, rules); // Same as validate but continues to validate all fields, whereas the validate method stops on first error.
indicative.is.email(emailAddress); // Raw validator.
indicative.extend("exists", existsFn); // Add your own rules.
indicative.sanitize(data, rules); // Returns a new object with sanitized data:.
indicative.sanitizor.normalizeEmail(emailAddress); // Raw sanitizor.
// Validations
above // Makes sure the value provided by the end user is above the expected value.
accepted // Ensures that the field under validation is accepted.
after // Ensures the value of the field is after the expected date.
afterOffsetOf // Ensures the date is after a given offset of a given time period.
alpha // Makes sure the field under validation is alpha only.
alphaNumeric // Makes sure the field under validation is alpha numeric only.
array // Ensure the value is a valid array. Also this validation will never validate the size of array.
before // Ensures the value of field under validation is before a given date.
beforeOffsetOf // Ensures the date is before a given offset of a given time period.
boolean // Ensures the value of a field is a boolean.
confirmed // Ensures a field value as confirmed using a _confirmation convention. This is mainly used for password confirmation field.
date // Ensures the field under validation is a valid date. The value can be a date object or a valid date string.
dateFormat // Ensures the date or date time is valid as the one of the defined formats.
different // Ensures the value of the field under validation is always different from the targeted field value.
email // Ensures the field under validation is a valid email format.
endsWith // Ensure the value of field under validation ends with a certain substr. This validation will also trim whitespaces before making the check.
equals // Ensures 2 values are lossely same. This validation will not check for the same type, but instead checks for the same value.
in // Ensures the value of a given field matches one of expected values.
includes // Ensures the value of field under validation contains a given substring.
integer // Ensures the value is a valid integer. Also string representation of a number will return true.
ip // Ensures the value is a valid ip address as per ipv4 and ipv6 specs.
ipv4 // Ensures the value is a valid ip address as per ipv4 spec only.
ipv6 // Ensures the value is a valid ip address as per ipv6 spec only.
json // Ensures the value of field under validation is safe to be parsed using JSON.parse method.
max // Ensures the length of a string or array is not greater than the defined length.
min // Ensures the length of a string or array is not is not less than the expected length
notEquals // Makes sure that the value of field under validation is not same as the defined value.
notIn // Makes sure that the value of field under validation is not from one of the defined values.
number // Makes sure that the value of field under validation is a valid number. The validation will pass for floats too, since it uses typeof internally.
object // Ensures the value of field under validation is a valid Javascript object. The validation will fail for Arrays, though they are objects too in Javascript.
range // Ensures the value of field under validation is under a given range. The values will be cased to Number automatically.
regex // Ensures the value of field under validation, passes the regex test. The regex can be defined as a string or a RegExp object.
required // Ensures the value of field under validation is not empty (i.e. not an empty object, empty array, empty string, null or undefined).
requiredIf // The field is checked for required validation, when expected field exists.
requiredWhen // The field is checked for required validation, when expected field value is same as the expected value.
requiredWithAll // Ensures the field is required when all other fields have non-empty values.
requiredWithAny // Ensures the field is required when any of the other fields have non-empty values.
requiredWithoutAll // Ensures the field is required when all of the other fields has empty values.
requiredWithoutAny // Ensures the field is required when any of the other fields has empty values.
same // Ensures the value of 2 fields are same.
startsWith // Ensure the value of field under validation starts with a certain substr. This validation will also trim whitespaces before making the check.
string // Ensures the value is a string.
under // Ensures the value of a field is under a certain value. All values will be casted to Number.
url // Ensures the value is a valid URL format.
/********************************************************************************************
* LUCID
* https://adonisjs.com/docs/lucid
********************************************************************************************/
Model.find() // Find a record using the primary key (always returns one record).
Model.findOrFail() // Similar to find, but instead throws a ModelNotFoundException when unable to find a record.
Model.findBy() // Find a record using a key/value pair (returns the first matching record).
Model.findByOrFail() // Similar to findBy, but instead throws a ModelNotFoundException when unable to find a record.
Model.first() // Find the first row from the database.
Model.firstOrFail() // Similar to first, but instead throws a ModelNotFoundException when unable to find a record.
Model.last() // Find the latest row from the database.
Model.findOrCreate(whereAttributes, values) // Find a record, if not found a new record will be created and returned.
Model.pick(rows = 1) // Pick x number of rows from the database table (defaults to 1 row).
Model.pickInverse(rows = 1) // Pick x number of rows from the database table from last (defaults to 1 row).
Model.ids() // Return an array of primary keys.
Model.pair(lhs, rhs) // Returns an object of key/value pairs (lhs is the key, rhs is the value).
Model.all() // Select all rows.
Model.truncate() // Delete all rows (truncate table).
Model.getCount() // Return a count of records in a given result set.
Model.create(jsonAttributes) // Return model instance after saving it into the database.
Model.createMany(arrayAttributes) // Return an array of model instances after saving them into the database.
Model.toJSON() // Converts a serializable instance to a plain array/object.
Model.query().setHidden(['password']) // Define hidden fields.
Model.query().setVisible(['title', 'body']) // Define visible fields.
Model.query().paginate() // Returns an object with metadata and data property that has a list of model results.
instance.fill(jsonAttributes) // Remove all existing values, only set the specified attributes.
instance.merge(jsonAttributes) // Modifies the specified attributes.
instance.save() // Save the instance to the database.
instance.delete() // Delete model instance from the database.
instance.associate(id) // Exclusive to belongsTo relationship, where it associates two model instances together.
instance.dissociate(id) // The opposite of associate, where you just drop the relationship
instance.attach(arrayOfIds, callback) // Works with the belongsToMany relationship to attach a relationship inside the pivot table. The attach method accepts an optional callback receiving the pivotModel instance, allowing you to set extra properties on a pivot table if required:
instance.detach(arrayOfIds) // The opposite of the attach method, and it removes the relationship from the pivot table only.
/********************************************************************************************
* QUERY BUILDER
* https://adonisjs.com/docs/query-builder
* http://knexjs.org/
********************************************************************************************/
const Database = use('Database')
// Available where clauses
where(~mixed~)
orWhere(~mixed~)
whereNot(~mixed~)
orWhereNot(~mixed~)
whereIn(column|columns, array|callback|builder)
orWhereIn(column | columns, array | callback | builder)
whereNotIn(column, array|callback|builder)
orWhereNotIn(column, array | callback | builder)
whereNull(column)
orWhereNull(column)
whereNotNull(column)
orWhereNotNull(column)
whereExists(builder | callback)
orWhereExists(builder | callback)
whereNotExists(builder | callback)
orWhereNotExists(builder | callback)
whereBetween(column, range)
orWhereBetween(column, range)
whereNotBetween(column, range)
orWhereNotBetween(column, range)
whereRaw(query, [bindings])
/********************************************************************************************
* DATABASE HOOKS
* https://adonisjs.com/docs/database-hooks
********************************************************************************************/
beforeCreate // Before creating a new record.
afterCreate // After a new record is created.
beforeUpdate // Before updating a record.
afterUpdate // After a record has been updated.
beforeSave // Before creating or updating a new record.
afterSave // After a new record has been created or updated.
beforeDelete // Before removing a record.
afterDelete // After a record is removed.
afterFind // After a single record is fetched from the database.
afterFetch // After the fetch method is executed.The hook method receives an array of model instances.
afterPaginate // After the paginate method is executed.The hook method receives two arguments: an array of model instances and the pagination metadata.
/********************************************************************************************
* EVENTS
* https://adonisjs.com/docs/events
********************************************************************************************/
Event.on(event, listener) // Bind single or multiple listeners for a given event. The listener can be a closure function or reference to one (or many) IoC container bindings.
Event.when(event, listener) // The when method aliases the on method.
Event.once(event, listener) // Same as on, but only called one time.
Event.onAny(listener) // Bind listener for any event
Event.times(number) // The times method is chained with on or when to limit the number of times the listener should be fired.
Event.emit(event, data) // Emit an event with optional data.
Event.fire(event, data) // The fire method aliases the emit method.
Event.removeListener(event, listener) // Remove listener(s) for a given event.
Event.off(event, listener) // The off method aliases the removeListener method.
Event.removeAllListeners(event) // Remove all listeners for a given event.
Event.listenersCount(event) // Return the number of listeners for a given event.
Event.getListeners(event) // Return an array of listeners for a given event.
Event.hasListeners(event) // Return a boolean indicating whether there are any listeners for a given event.
/********************************************************************************************
* LOGGER
* https://adonisjs.com/docs/sessions
********************************************************************************************/
const Logger = use('Logger')
Logger.level = 'debug' // Sed default config level
Logger.emerg(msg[, data]) // Print an emergency log (level 0).
Logger.alert(msg[, data]) // Print an alert log (level 1).
Logger.crit(msg[, data]) // Print a critical log (level 2).
Logger.error(msg[, data]) // Print an error log (level 3).
Logger.warning(msg[, data]) // Print a warning log (level 4).
Logger.notice(msg[, data]) // Print a notice log (level 5).
Logger.info(msg[, data]) // Print an info log (level 6).
Logger.debug(msg[, data]) // Print a debug log (level 7).
Logger.transport(transport) // Switch transport on the fly.
/********************************************************************************************
* ENCRYPTION AND HASHING
* https://adonisjs.com/docs/encryption-and-hashing
********************************************************************************************/
const Encryption = use('Encryption')
Encryption.encrypt(string) // Encrypt a given value.
Encryption.decrypt(string) // Decrypt an encrypted value.
const Hash = use('Hash')
await Hash.make(string[, config]) // Hash a plain string value.
await Hash.verify(string, hashedString) // Since you cannot decrypt a hash, you can verify the user input against the previously hashed value.
/********************************************************************************************
* SESSIONS
* https://adonisjs.com/docs/sessions
********************************************************************************************/
session.put(key, value); // Add a key/value pair to the session store.
session.get(key, [defaultValue]); // Return the value for a given key (accepts an optional default value).
session.all(); // Get everything back as an object from the session store.
session.increment(key, [steps]); // Increment the value for a given key (ensure the previous value is a number).
session.decrement(key, [steps]); // Decrement the value for a given key (ensure the previous value is a number).
session.forget(key); // Remove a key/value pair from the session store.
session.pull(key, [defaultValue]); // Return (and then remove) a key/value pair from the session store.
session.clear(); // Empty the session store.
session.flashAll() // Flash the request form data.
session.flashOnly() // Flash only the selected fields.
session.flashExcept() // Flash the request form data except the selected fields.
session.withErrors() // Flash with an array of errors.
session.flash() // Flash a custom object.
/********************************************************************************************
* FILE STORAGE
* https://adonisjs.com/docs/file-system
********************************************************************************************/
const Drive = use('Drive')
Drive.exists(relativePath) // Find if a file/directory exists or not.
Drive.get(relativePath, encoding = utf-8) // Get file contents as a buffer or string.
Drive.getStream(relativePath) // Get file as a stream.
Drive.put(relativePath, content, options = {}) // Create a new file with given contents (creates any missing directories).
Drive.prepend(relativePath, content, options = {}) // Prepend content to a file (creates a new file if path doesnt exist).
Drive.append(relativePath, content, options = {}) // Append content to a file (creates a new file if path doesnt exist).
Drive.delete(relativePath) // Remove existing file.
Drive.move(src, dest, options = {}) // Move file from one directory to another.
Drive.copy(src, dest, options = {}) // Copy file from one directory to another.
// For S3 & Spaces drivers
Drive.getObject(location, params) // Get S3 object for a given file (for params info, see S3 params).
Drive.getUrl(location, [bucket]) // Get url for a given file (accepts optional alternative bucket param).
Drive.getSignedUrl(location, expiry = 900, params) // Get signed url for a given file (expiry set to 15mins by default).
/********************************************************************************************
* HELPERS
* https://adonisjs.com/docs/helpers
********************************************************************************************/
const Helpers = use('Helpers')
Helpers.appRoot() // Returns path to the application root.
Helpers.publicPath([toFile]) // Returns path to the public directory or file inside the directory.
Helpers.configPath([toFile]) // Returns path to the config directory or file inside the directory.
Helpers.resourcesPath([toFile]) // Returns path to the resources directory or file inside the directory.
Helpers.migrationsPath([toFile]) // Returns path to the migrations directory or file inside the directory.
Helpers.seedsPath([toFile]) // Returns path to the seeds directory or file inside the directory.
Helpers.databasePath([toFile]) // Returns path to the database directory or file inside the directory.
Helpers.viewsPath([toFile]) // Returns path to the views directory or file inside the directory.
Helpers.tmpPath([toFile]) // Returns path to the tmp directory or file inside the directory.
Helpers.promisify() // Returns promisified callback functions.
Helpers.isAceCommand() // Returns whether the process was started as the ace command or not.
/********************************************************************************************
* SOCIAL AUTHENTICATION
* https://adonisjs.com/docs/social-auth
********************************************************************************************/
// Drivers: Facebook, Github, Google, Instagram, Linkedin, Twitter, Foursquare.
ally.redirect() // Redirect user to the 3rd party website.
ally.getRedirectUrl() // Get redirect URL back as a string.
ally.scope(scopesArray) // Define runtime scopes before redirecting the user.
ally.fields(fieldsArray) // Fields to be fetched when getting the authenticated user profile.
ally.getUser() // Get the user profile of an authenticated user (returns an AllyUser instance).
ally.getUserByToken(accessToken, [accessSecret]) // Returns the user details using the accessToken.
user.getId() // Returns the user id.
user.getName() // Returns the user name.
user.getEmail() // Returns the user email.
user.getNickname() // Returns the nickname / display name of the user.
user.getAvatar() // Returns public URL to the users profile picture.
user.getAccessToken() // Returns the access token which may be used later to update the user profile.
user.getRefreshToken() // Refresh token to be used when access token expires.
user.getExpires() // Access token expiry data.
user.getTokenSecret() // Returns token secret.
user.getOriginal() // Original payload returned by the 3rd party provider.
+120
View File
@@ -0,0 +1,120 @@
# *****************************************************************************
# CODING STYLE > MAKING YOUR CODE READABLE
# *****************************************************************************
# 1. Avoid abbreviating variable names.
# 2. Write out your function argument names.
# 3. Document your classes and methods.
# 4. Comment your code.
# 5. Refactor repeated lines of code into reusable functions or methods.
# 6. Keep functions and methods short. A good rule of thumb is that scrolling
# should not be necessary to read an entire function or method.
# TIP: Use Flake8 for Checking Code Quality.
# *****************************************************************************
# CODING STYLE > THE WORD ON IMPORTS
# *****************************************************************************
# Imports should be grouped in the following order:
# 1. Standard library imports.
# 2. Core Django imports.
# 3. Third-party app imports.
# 4. Imports from your apps.
# Use explicit relative imports.
# Avoid using import *
# *****************************************************************************
# CODING STYLE > OTHERS
# *****************************************************************************
# Use underscores in URL pattern names rather than dashes.
# *****************************************************************************
# CODING STYLE > DATABASE
# *****************************************************************************
# 1.Register your app in admin file in your app folder to use admin panel in django
# 2.Create a superuser using command python manage.py createsuperuser
# 3.Remember to migrate after you change anything in your models.py file
# 4.Use /admin/ page to add data in your tables for testing purpose
# *****************************************************************************
# Deployment
# *****************************************************************************
# add your media, database, venv, __pycache__ to the .gitignore (there is a compelete list that you can find here: https://github.com/jpadilla/django-project-template/blob/master/.gitignore)
# keep migration files in the git (you will need to migrate them in target server)
# don't run "makemigrations" in the target server (you will need to just run "migrate")
# $ pip freeze > requirements.txt
# make appropriate changes in your project settings.py file (change DEBUG to False and etc)
# push your code to your git-server
# pull your code in your target server
# give right permissions to the web-server (e.g. $ chown www-data:www-data -R /var/www/myproject)
# make a new venv in the target server and activate it
# $ sudo pip install -r requirements.txt
# sudo ./venv/bin/python3 manage.py migrate
# restart your web-server (in case of apache: $ sudo service apache2 restart)
# *****************************************************************************
# DJANGO-ADMIN
# *****************************************************************************
django-admin check # Checks the entire django project for potential problems
django-admin changepassword <username> # Allows changing a users password. It prompts you to enter a new password twice for the given user.
django-admin clearsessions # Can be run as a cron job or directly to clean out expired sessions.
django-admin collectstatic # Helps to collect all the static files in the one mentioned directory
django-admin createsuperuser # Creates a superuser account (a user who has all permissions).
django-admin compilemessages # Compiles .po files to .mo files for use with builtin gettext support
django-admin createcachetable # Creates the tables needed to use the SQL cache backend.
django-admin dbshell # Runs the command-line client for specified database, or the default database if none is provided.
django-admin diffsettings # Displays differences between the current settings.py and Django's default settings.
django-admin dumpdata # Output the contents of the database as a fixture of the given format (using each model's default manager unless --all is specified).
django-admin flush # Removes ALL DATA from the database, including data added during migrations. Does not achieve a "fresh install" state.
django-admin inspectdb # Introspects the database tables in the given database and outputs a Django model module.
django-admin loaddata # Installs the named fixture(s) in the database.
django-admin makemessages # Runs over the entire source tree of the current directory and pulls out all strings marked for translation. It creates (or updates) a message file in the conf/locale (in the django tree) or locale (for projects and applications) directory. You must run this command with one of either the --locale, --exclude, or --all options.
django-admin help # display usage information and a list of the commands provided by each application
django-admin makemigrations # create new migrations to the database based on the changes detected in the models
django-admin migrate # synchronize the database state with your current state project models and migrations
django-admin remove_stale_contenttypes # Deletes stale content types (from deleted models) in your database.y.
django-admin runserver <port> # start the development webserver at 127.0.0.1 with the port <port> default 8000
django-admin sendtestemail # Sends a test email to the email addresses specified as arguments.
django-admin shell # Runs a Python interactive interpreter. Tries to use IPython or bpython, if one of them is available. Any standard input is executed as code.
django-admin showmigrations # Shows all available migrations for the current project.
django-admin sqlflush # Returns a list of the SQL statements required to return all tables in the database to the state they were in just after they were installed.
django-admin sqlmigrate # Prints the SQL statements for the named migration.
django-admin sqlsequencereset # Prints the SQL statements for resetting sequences for the given app name(s).
django-admin squashmigrations # Squashes an existing set of migrations (from first until specified) into a single new one.
django-admin startapp <Appname> # create a new django application with the specified name
django-admin startproject <ProjectName> # create a new project directory structure
django-admin testserver # Runs a development server with data from the given fixture(s).
django-admin version # display the current django version
# *****************************************************************************
# Starting a django project in python3
# *****************************************************************************
# 1. $ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py; python3 get-pip.py
# 2. $ pip install virtualenv
# 3. $ mkdir django-projects
# 4. $ cd django-projects
# 5. $ virtualenv venv
# 6. $ source venv/bin/activate
# 7. $ pip install django
# 8. $ django-admin startproject myproject
# 9. $ django-admin startapp myapp
# 10. $ python manage.py runserver
+226
View File
@@ -0,0 +1,226 @@
/* *******************************************************************************************
* API
* http://expressjs.com/en/api.html
* ******************************************************************************************* */
`npm i express --save` or`yarn add -D express``(-D saves it as a dev dependency)`
`yarn add -D @types/express``(Installing for TS)`
const express = require("express"); // Importing the express library.
const app = express(); // Intializing the imported express application
/* *******************************************************************************************
* GLOBAL OBJECTS
* http://expressjs.com/en/api.html#express.json
* ******************************************************************************************* */
```Methods```;
`express.json([options]);`
options: `
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
reviver // It is passed directly to JSON.parse as an second argument
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
`express.raw([options]);`
options: `
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
`express.Router([options]);`
options: `
caseSensitive //Enables case sensitivity
mergeParams //if param names of child and parent are conflicted then the child takes the precedence
strict // Enables Strict routing
`;
`express.static(root, [options]);`
options: `
dotfiles // determines how dotfiles are used
etag // Operates etag generation
extensions // Operates file extension fallback
fallthrough // Enable or disable the immutable directive in the Cache-Control response header
index // sends the specified directory index file
LastModified // sets the Last-Modified header to the last modified date
setHeaders // Function for setting HTTP headers to serve with the file
`;
`express.text([options]);`
options: `
defaultCharset // Sets the default charset for the text context.
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
`express.urlencoded([options]);`
options: `
extended // it allows to choose between parsing the URL-encoded data or the qs library
parameterLimit // It controls the no of params.
inflate // to manage the deflated bodies like enabling and disabling
limit // Controls the maximum request body size.
type // This is used to determine the type of middleware will parse
verify // It is an undefined function which used to verify the middleware parsing.
`;
```Application`````;
Properties```app.local`;
`app.locals.title = "My Cheatsheet";
console.dir(app.locals.title)`; `// Creating objects with local variables`
app.mountpath`
``app.mountpath``const admin = express()
admin.get('/', function(req,res){
console.log(admin.mountpath)
res.send('Admin Homepage')
})
app.use('<admin dir>', admin)`; `// Mounting a sub - app`
``Event``
`admin.on('mount', (parent){
console.log('Admin Mounted')
})` `// Mounting on a parent app`
``Methods``
`app.get('/', function(req, res){
res.send('GET request to message')
})` `// get requests to the specified path`
`app.post('/', function(req,res){
res.send('POST request to a webpage')
})` `// post request to the specified path`
`app.put('/', function(req,res){
res.send('PUT request to a webpage')
})` `// post request to the specified path`
`app.delete('/', function(req,res){
res.send('DELETE request to a webpage')
})` `// delete request to the specified path`
`app.all('/', function(req,res,next){
console.log('Accessing the secret section....')
next()
})` `// Routing all types of HTTP request`
`app.param('user', function(req,res,next){
User.find(id, function(err, user){
if(err){
next(err)
} else if (user){
req.user = user
next()
} else {
next(new Error('Failed to load user'))
}
})
})` `// Adding callback trigger to route parameters`
`app.use(function(req,res,next){
res.send('Hey There!')
})` `// To Invoke the middleware layer that you want to add`
```Request```
``Methods``
`req.get('content-type')` `// Returns the specified HTTP req header`
`req.accepts('html')` `// Checks if the specified content types are available or not`
`req.is('json')` `// Requests the matching content-type`
`var range = req.range(1000)
if (range.type === 'bytes'){
range.forEach(function(r){
// Your code
})
}` `// Range header parser`
``Properties``
`req.param('name')` `// Requests the param name when present`
`app.post('/', function (req, res, next) {
console.log(req.body)
res.json(req.body)
})` `// Data submitted in the request body`
`console.dir(req.cookies.name)` `// Contains cookies sent by the request`
`console.dir(req.query.q)` `// Query string parameter in the route`
`console.log(req.route)
res.send('GET')` `// Outputs all the layer, methods, path`
`console.dir(req.signedCookies.user)` `// Logs all the signed cookies sent by the request`
```Response```
``Methods``
`res.redirect('https://google.com')` `// Redirects to the intended page`
`res.send({message: 'Awesome Stuffs'})` `// Response to the webpage`
`res.json({alert: 'awesomecheatsheets'})` `// Response in JSON type`
`const file = req.params.name;
res.sendFile(file, options, function(err){
if(err){
next(err)
}else{
console.log('Sent:', file)
}
})` `// Sends file to the intended path`
`res.render('index')` `// Rendering the intended file`
```BodyParser```
`const BodyParser = require('body-parser')
app.use(BodyParser.json())
app.use(BodyParser.urlencoded({
extended: true
}))` `// Parses incoming request bodies`
+578
View File
@@ -0,0 +1,578 @@
/* *******************************************************************************************
* FEATHERS.JS CHEATSHEET
* https://docs.feathersjs.com/api/readme.html
*
* 1. CORE: Feathers core functionality.
* 2. TRANSPORT: Expose a Feathers application as an API server.
* 3. CLIENT: More details on how to use Feathers on the client.
* 4. AUTHENTICATION: Feathers authentication mechanism.
* 5. DATABASE: Feathers common database adapter API and querying mechanism.
* ******************************************************************************************* */
/* *******************************************************************************************
* 1. CORE: Feathers core functionality.
* ******************************************************************************************* */
```
# Provides the ability to initialize new application instances
npm install @feathersjs/feathers --save
# Provides a set of standard error classes used by all other Feathers modules
npm install @feathersjs/errors --save
```
// --> APPLICATION <--
// https://docs.feathersjs.com/api/application.html
const feathers = require('@feathersjs/feathers');
const app = feathers(); // application initialization
app.mixins // contains a list of service mixins
app.use(path, service) // allows registering a service object on a given path
app.service(path) // returns the wrapped service object for the given path
app.hooks(hooks) // allows registration of application-level hooks
app.publish([event,], publisher) // registers a global event publisher
app.configure(callback) // runs a callback function that gets passed the application object
app.listen(port) // starts the application on the given port
app.setup([server]) // used to initialize all services by calling each services .setup(app, path) method (if available)
app.set(name, value) // assigns setting name to value
app.get(name) // retrieves the setting name
app.on(eventname, listener) // registers a listener method for the given eventname
app.emit(eventname, data) // emits the event eventname to all event listeners
app.removeListener(eventname, [ listener ]) // removes all or the given listener for eventname
// --> SERVICES <--
// https://docs.feathersjs.com/api/services.html
// "Services" are the heart of every Feathers application.
// Services are JavaScript objects (or instances of ES6 classes) that implement certain methods.
// Feathers itself will also add some additional methods and functionality to its services.
class MyService {
// Retrieves a list of all resources from the service.
// Provider parameters will be passed as params.query.
async find(params) {
return [];
}
// Retrieves a single resource with the given id from the service.
async get(id, params) {}
// Creates a new resource with data.
// The method should return the newly created data. data may also be an array.
async create(data, params) {}
// Replaces the resource identified by id with data.
// The method should return the complete, updated resource data.
// id can also be null when updating multiple records, with params.query containing the query criteria.
async update(id, data, params) {}
// Merges the existing data of the resource identified by id with the new data.
// id can also be null indicating that multiple resources should be patched with params.query containing the query criteria.
async patch(id, data, params) {}
// Removes the resource with id.
// The method should return the removed resource.
// id can also be null, which indicates the deletion of multiple resources, with params.query containing the query criteria.
async remove(id, params) {}
// A special method that initializes the service, passing an instance of the Feathers application
// and the path it has been registered on.
// For services registered before app.listen is invoked, the setup function of each registered service
// is called on invoking app.listen. For services registered after app.listen is invoked, setup is
// called automatically by Feathers when a service is registered.
setup(app, path) {}
}
params.query // contains the URL query parameters sent from the client
params.provider // for any service method call made through REST params.provider will be set to rest
app.use('/my-service', new MyService());
// Important: Always use the service returned by app.service(path)
const myService = app.service('my-service');
myService.hooks(hooks) // register hooks for this service
myService.publish([event,], publisher) // register an event publishing callback
myService.mixin(mixin) // extends the functionality of a service
myService.on(eventname, listener) // registers a listener method for the given eventname
myService.once(eventname, listener) // registers a listener method for the given eventname that will be triggered only one time
myService.emit(eventname, data) // emits the event eventname to all event listeners
myService.removeListener(eventname, [ listener ]) // removes all listeners (or the given listener) for eventname
// --> HOOKS <--
// https://docs.feathersjs.com/api/hooks.html
// Hooks are pluggable middleware functions that can be registered
// before, after or on errors of a service method. You can register a
// single hook function or create a chain of them to create complex work-flows.
app.service('my-service').hooks({
before: {
all: [
// Use normal functions
async function(context) { console.log('before all hook ran'); }
],
find: [
// Use ES6 arrow functions
context => console.log('before find hook 1 ran'),
async context => console.log('before find hook 2 ran')
],
async create (context) {
return context
},
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: []
},
// Here is an example for a very useful application hook that logs every service method error
// with the service and method name as well as the error stack
error(context) {
console.error(`Error in ${context.path} calling ${context.method} method`, context.error);
}
});
context.app // [read only] contains the Feathers application object
context.service // [read only] contains the service this hook currently runs on
context.path // [read only] contains the service name (or path) without leading or trailing slashes
context.method // [read only] contains the name of the service method (find, get, create, update...)
context.type // [read only] contains the hook type (one of before, after or error)
context.params // [writable] contains the service method parameters (including params.query)
context.id // [writable] contains the id for a get, remove, update and patch service method call
context.data // [writable] contains the data of a create, update and patch service method call
context.error // [writable] contains the error object that was thrown in a failed method call (only available in error hooks)
context.result // [writable] contains the result of the successful service method call (only available in after hooks)
context.dispatch // [writable and optional] contains a "safe" version of the data that should be sent to any client
// --> CHANNELS <--
// https://docs.feathersjs.com/api/channels.html
// A channel is an object that contains a number of connections.
// It can be created via app.channel and allows a connection to join or leave it.
app.channel(name) // when given a single name, returns an existing or new named channel
app.channel(name1, name2, ... nameN) // when given multiples names, will return a combined channel.
app.channels // returns a list of all existing channel names
channel.join(connection) // adds a connection to this channel
channel.leave(connection|fn) // removes a connection from this channel
channel.filter(fn) // returns a new channel filtered by a given function which gets passed the connection
channel.send(data) // returns a copy of this channel with customized data that should be sent for this event
channel.connections // contains a list of all connections in this channel
channel.length // returns the total number of connections in this channel
service.publish([event,] fn) // registers a publishing function for a specific service for a specific event or all events if no event name was given
app.publish([event,] fn) // registers an event publishing callback
app.on('connection', connection => {}) // fired every time a new real-time connection is established
app.on('disconnection', connection => {})
app.on('login', (authenticationResult, params, context) => {}) // sent by the authentication module and also contains the connection in the info object that is passed as the second parameter
/* *******************************************************************************************
* 2. TRANSPORT: Expose a Feathers application as an API server.
* ******************************************************************************************* */
```
# Contains Express framework integrations
npm install @feathersjs/express --save
# Allows to call service methods and receive real-time events
npm install @feathersjs/socketio --save
# Allows to call service methods and receive real-time events via Primus
npm install @feathersjs/primus --save
```
// --> EXPRESS <--
// https://docs.feathersjs.com/api/express.html
const feathers = require('@feathersjs/feathers');
const express = require('@feathersjs/express');
// Create an app that is a Feathers AND Express application
const app = express(feathers());
// If no Feathers application is passed, express() returns a plain Express application
// just like a normal call to Express would
const app = express();
app.use(path, service|mw) // registers either a service object or an Express middleware on the given path
app.listen(port) // will first call Express app.listen and then internally also call the Feathers app.setup(server)
app.setup(server) // usually called internally by app.listen but in the cases described below needs to be called explicitly
express.rest() // registers a Feathers transport mechanism that allows you to expose and consume services through a RESTful API.
app.configure(express.rest()) // configures the transport provider with a standard formatter sending JSON response via res.json
express.notFound() // returns middleware that returns a NotFound (404) Feathers error
express.errorHandler() // middleware that formats any error response to a REST call as JSON and sets the appropriate error code
app.use(express.errorHandler()) // set up the error handler with the default configuration
// --> SOCKET.IO <--
// https://docs.feathersjs.com/api/client/socketio.html
const feathers = require('@feathersjs/feathers');
const socketio = require('@feathersjs/socketio');
const app = feathers();
app.configure(socketio()); // sets up the Socket.io transport with the default configuration using either the server provided by app.listen or passed in app.setup(server)
app.configure(socketio(callback)) // sets up the Socket.io transport with the default configuration and call callback with the Socket.io server object
app.configure(socketio(options [, callback])) // sets up the Socket.io transport with the given Socket.io options object and optionally calls the callback
app.configure(socketio(port, [options], [callback])) // creates a new Socket.io server on a separate port. Options and a callback are optional
// --> PRIMUS <--
// https://docs.feathersjs.com/api/client/primus.html
app.configure(primus(options)) // sets up the Primus transport with the given Primus options
app.configure(primus(options, callback)) // sets up the Primus transport with the given Primus options and calls the callback with the Primus server instance
/* *******************************************************************************************
* 3. CLIENT: More details on how to use Feathers on the client.
* ******************************************************************************************* */
```
# Bundles the separate Feathers client side modules into one providing the code as ES5 (compatible with modern browsers)
# You do not have to install or load any of the other modules listed below
npm install @feathersjs/client --save
# Allows to connect to services through REST HTTP
npm install @feathersjs/rest-client --save
# Allows to connect to services through Socket.io
npm install @feathersjs/socketio-client --save
# Allows to connect to services through Primus
npm install @feathersjs/primus-client --save
# Allows you to easily authenticate against a Feathers server
npm install @feathersjs/authentication-client --save
```
// --> REST CLIENT <--
// https://docs.feathersjs.com/api/client/rest.html
rest([baseUrl]) // Initialize a client object with a base URL
app.configure(restClient.jquery(window.jQuery)); // connect to a service using jQuery
app.configure(restClient.request(requestClient)); // connect to a service using request
app.configure(restClient.superagent(superagent)); // connect to a service using Superagent
app.configure(restClient.axios(axios)); // connect to a service using Axios
app.configure(restClient.fetch(window.fetch)); // connect to a service using Fetch
// --> SOCKET.IO <--
// https://docs.feathersjs.com/api/client/socketio.html
socketio(socket) // initialize the Socket.io client using a given socket and the default options
socketio(socket, options) // initialize the Socket.io client using a given socket and the given options
// --> PRIMUS <--
// https://docs.feathersjs.com/api/client/primus.html
primus(socket) // initialize the Primus client using a given socket and the default options
primus(socket, options) // initialize the Primus client using a given socket and the given options
/* *******************************************************************************************
* 4. AUTHENTICATION: Feathers authentication mechanism.
* ******************************************************************************************* */
```
# Assists in using JWT for authentication
npm install @feathersjs/authentication --save
# Wraps the passport-local authentication strategy (username and password)
npm install @feathersjs/authentication-local --save
# Allows to use 180+ oAuth providers (Facebook, Google, Twitter etc.)
npm install @feathersjs/authentication-oauth --save
```
// --> SERVER <--
// https://docs.feathersjs.com/api/authentication/server.html
const options = {
"authentication": {
"secret": "CHANGE_ME", // The token signing secret
"entity": "user", // the entity that will be added to the request, socket, and context.params. (ie. req.user, socket.user, context.params.user)
"service": "users", // the service to look up the entity
"authStrategies": [ "jwt", "local" ], // The authentication strategies to allow to create a token
"jwtOptions": {
"header": { "typ": "access" }, // by default is an access token but can be any type
"audience": "https://yourdomain.com", // The resource server where the token is processed
"issuer": "feathers", // The issuing server, application or resource
"algorithm": "HS256", // the algorithm to use
"expiresIn": "1d" // the access token expiry
}
}
}
const { AuthenticationService, JWTStrategy } = require('@feathersjs/authentication');
let authService = new AuthenticationService(app);
service.register('jwt', new JWTStrategy());
app.use('/authentication', authService);
app.configure(expressOauth());
app.get('defaultAuthentication') // The name of the default authentication service
authService = app.service('authentication') // service for creating JWT (implements only the create and remove methods)
authService.hooks({ before }) // registers hooks for this service
authService.hooks({ after }) // registers hooks for this service
new AuthenticationService(app) // Create a new authentication service
class MyAuthenticationService extends AuthenticationService {} // Customize the authentication service
authService.authenticate(data, params, ...strategies) // Authenticate with strategies
authService.create(data, params) // Authenticate with data and params
authService.create({ // Authenticate and create a JWT using the local strategy email/password
strategy: 'local',
email: 'hello@feathersjs.com',
password: 'supersecret'
});
authService.remove(id, params) // removes the JWT token (mostly exists for the logout process)
authService.configuration // The current configuration
authService.register(name, strategy) // Register a new authentication strategy
authService.createAccessToken(payload) // Create a new access token with payload
authService.verifyAccessToken(accessToken) // Verify an existing access token
authService.getTokenOptions(authResult, params) // Get the options for a token
authService.getPayload(authResult, params) // Return the payload for an authentication result
authService.parse(req, res, ...strategies) // Parse an HTTP request and response with using a list of strategies
app.on('login', callback)) // emits an event whenever a client successfully authenticates
app.on('logout', callback)) // emits an event whenever a client successfully logout
// --> CLIENT <--
// https://docs.feathersjs.com/api/authentication/client.html
const options = {
storage: window.localStorage, // The storage to store the access token
path: '/authentication', // The path of the authentication service
locationKey: 'access_token', // The name of the window hash parameter to parse for an access token from the window.location. Usually used by the oAuth flow.
locationErrorKey: 'error', // The name of the window hash parameter to parse for authentication errors. Usually used by the oAuth flow.
jwtStrategy: 'jwt', // The access token authentication strategy
storageKey: 'feathers-jwt', // Key for storing the token in e.g. localStorage
header: 'Authorization', // Name of the accessToken header
scheme: 'Bearer', // The HTTP header scheme
Authentication: AuthenticationClient // Allows to provide a customized authentication client class
}
app.configure(auth(options)) // configure the authentication plugin with the given options
app.reAuthenticate() // authenticates using the JWT from the storage
app.authenticate(options) // authenticate with a Feathers server by passing a strategy and other properties as credentials
app.logout() // removes the JWT accessToken from storage on the client
const authenticationInfo = await app.get('authentication'); // The authenticatoin information (like the user)
app.on('login', callback) // emits an event whenever the client successfully authenticates
app.on('logout', callback) // emits an event whenever the client successfully authenticates
// --> LOCAL (EMAIL & PASSWORD) <--
// https://docs.feathersjs.com/api/authentication/local.html
const { LocalStrategy } = require('@feathersjs/authentication-local');
const options = {
usernameField: 'email', // Name of the username field in the (e.g. 'email')
passwordField: 'password', // Name of the password field (e.g. 'password')
hashSize: 10, // The BCrypt hash size
errorMessage: 'Invalid login', // The error message to return on errors
entityUsernameField: usernameField, // Name of the username field on the entity if authentication request data and entity field names are different
entityPasswordField: passwordField // Name of the password field on the entity if authentication request data and entity field names are different
}
authService.register('local', new LocalStrategy());
local.hooks.hashPassword() // hashes plain text passwords before they are saved to the database
local.hooks.protect('password') // makes sure that protected fields don't get sent to a client
// --> OAUTH <--
// https://docs.feathersjs.com/api/authentication/oauth.html
const { expressOauth, OAuthStrategy } = require('@feathersjs/authentication-oauth');
class GitHubStrategy extends OAuthStrategy {
async getEntityData(profile) {
const baseData = await super.getEntityData(profile);
return {
...baseData,
email: profile.email
};
}
}
authService.register('github', new MyGitHubStrategy());
const options = {
authentication: {
oauth: {
redirect: '/', // The redirect after a successful login
github: { // The per-strategy configuration
key: '<Client ID>',
secret: '<Client secret>'
}
}
}
}
app.configure(expressOauth(options));
/* *******************************************************************************************
* 5. DATABASE: Feathers common database adapter API and querying mechanism.
* ******************************************************************************************* */
```
# [MEMORY/FILESYSTEM] In-memory database adapter
npm install feathers-memory --save
# [MEMORY/FILESYSTEM] Database adapter for NeDB an in-memory or file system based standalone database
npm install feathers-nedb --save
# [MEMORY/FILESYSTEM] Adapter for Client side Feathers that can use the browsers LocalStorage or ReactNative's AsyncStorage
npm install feathers-localstorage --save
# [SQL] Adapter for KnexJS, an SQL query builder for NodeJS supporting PostgreSQL, MySQL, SQLite and MSSQL
npm install feathers-knex --save
# [SQL] Adapter for Sequelize an ORM for NodeJS supporting PostgreSQL, MySQL, SQLite and MSSQL
npm install feathers-sequelize --save
# [NOSSQL] Database adapter for MongoDB using the official NodeJS database driver
npm install feathers-mongodb --save
# [NOSSQL] Database adapter for Mongoose an Object Modelling library for NodeJS and MongoDB
npm install feathers-mongoose --save
# [NOSSQL] Database adapter for Elasticsearch
npm install feathers-elasticsearch --save
# [NOSSQL] Database adapter for RethinkDB a real-time database.
npm install feathers-rethinkdb --save
```
// --> COMMON API <--
// https://docs.feathersjs.com/api/databases/common.html
const service = require('feathers-<adaptername>');
app.use('/messages', service({
id: undefined, // (optional) name of the id field property (usually set by default to id or _id)
events: undefined, // (optional) list of custom service events sent by this service
paginate: { // (optional) a pagination object containing a default and max page size
default: undefined, // sets the default number of items when $limit is not set
max: undefined // sets the maximum allowed number of items per page (even if the $limit query parameter is set higher)
},
whitelist: [], // A list of additional non-standard query parameters to allow (e.g [ '$regex', '$populate' ])
multi: true // Allow create with arrays and update and remove with id null to change multiple items
}));
adapter.find() // returns a list of all records matching the query in params.query using the common querying mechanism
adapter.get(id, params) // retrieves a single record by its unique identifier (the field set in the id option during initialization)
adapter.create(data, params) // creates a new record with data. data can also be an array to create multiple records
adapter.update(id, data, params) // completely replaces a single record identified by id with data. Does not allow replacing multiple records (id can't be null). id can not be changed.
adapter.patch(id, data, params) // merges a record identified by id with data. id can be null to allow replacing multiple records (all records that match params.query the same as in .find). id can not be changed
adapter.remove(id, params) // removes a record identified by id. id can be null to allow removing multiple records (all records that match params.query the same as in .find)
// Hook-less
adapter._find()
adapter._get(id, params)
adapter._create(data, params)
adapter._update(id, data, params)
adapter._patch(id, data, params)
adapter._remove(id, params)
// --> QUERYING <--
// https://docs.feathersjs.com/api/databases/querying.html
app.service('messages').find({
query: {
$limit: 2, // will return only the number of results you specify
$select: [ 'text', 'userId' ], // allows to pick which fields to include in the result
$skip: 2, // will skip the specified number of results
$sort: { // will sort based on the object you provide. It can contain a list of properties by which to sort mapped to the order
createdAt: -1
},
$or: [ // find all records that match any of the given criteria
{ archived: { $ne: true } },
{ roomId: 2 }
],
read: false, // compared directly for equality
roomId: {
$in: [ 2, 5 ], // find all records where the property does match any of the given values
$nin: [ 1, 3 ] // find all records where the property does not match any of the given values
},
createdAt: {
$lt: new Date().getTime(), // find all records where the value is less to a given value
$lte: new Date().getTime(), // find all records where the value is less and equal to a given value
$gt: new Date().getTime(), // find all records where the value is more to a given value
$gte: new Date().getTime(), // find all records where the value is more and equal to a given value
},
archived: {
$ne: true // find all records that do not equal the given property value
}
}
});
// With pagination enabled, to just get the number of available records set $limit to 0.
// This will only run a (fast) counting query against the database and return a page object with
// the total and an empty data array.
/* *******************************************************************************************
* 5. APPLICATION ARCHITECTURE
* ******************************************************************************************* */
// .
// ├── config/ # contains the configuration files for the app
// │ ├── default.json # default configuration variables
// │ ├── production.json # override default configurations variables when NODE_ENV=production
// │ └── ...
// │
// ├── node_modules/ # project dependencies using NPM or Yarn
// │ └── ...
// │
// ├── public/ # contains static files to be served
// │ └── ...
// │
// ├── src/ # contains the Feathers server code
// │ ├── hooks/ # contains our custom hooks
// │ │ └── ...
// │ ├── middleware/ # contains our Express middlewares
// │ │ └── ...
// │ ├── services/ # contains our services
// │ │ └── ...
// │ │
// │ ├── index.js # is used to load and start the application
// │ ├── app.js # configures our Feathers application
// │ ├── app.hooks.js # contains hooks which that run for all services
// │ └── channels.js # set up Feathers event channels
// ├── tests/ # contains Mocha test files for the app, hooks and services
// │ └── ...
// ├── .editorconfig # helps developers define and maintain consistent coding styles
// ├── .eslintrc.json # eslint configuration
// └── package.json # express server for production
+624
View File
@@ -0,0 +1,624 @@
<?php
/********************************************************************************************
* CLI AVAILABLE COMMANDS FOR ARTISAN
* https://laravel.com/docs/5.8/artisan
********************************************************************************************/
// MAIN.
php artisan clear-compiled // Remove the compiled class file
php artisan db // Start a new database CLI session
php artisan docs // Access the Laravel documentation
php artisan down // Put the application into maintenance mode
php artisan dump-server // Start the dump server to collect dump information.
php artisan env // Display the current framework environment
php artisan help // Displays help for a command
php artisan inspire // Display an inspiring quote
php artisan list // Lists commands
php artisan migrate // Run the database migrations
php artisan optimize // Cache the framework bootstrap files
php artisan preset // Swap the front-end scaffolding for the application
php artisan serve // Serve the application on the PHP development server
php artisan tinker // Interact with your application
php artisan up // Bring the application out of maintenance mode
// APP.
php artisan app:name // Set the application namespace
// AUTH
php artisan auth:clear-resets // Flush expired password reset tokens
// CACHE
php artisan cache:clear // Flush the application cache
php artisan cache:forget // Remove an item from the cache
php artisan cache:table // Create a migration for the cache database table
// CONFIG
php artisan config:cache // Create a cache file for faster configuration loading
php artisan config:clear // Remove the configuration cache file
// DB
php artisan db:seed // Seed the database with records
php artisan db:show // Display information about the given database
php artisan db:table // Display information about the given database table
php artisan db:wipe // Drop all tables, views, and types
// EVENT
php artisan event:generate // Generate the missing events and listeners based on registration
// KEY
php artisan key:generate // Set the application key
// MAKE
php artisan make:cast // Create a new custom Eloquent cast class
php artisan make:channel // Create a new channel class
php artisan make:command // Create a new Artisan command
php artisan make:component // Create a new view component class
php artisan make:controller // Create a new controller class
php artisan make:event // Create a new event class
php artisan make:exception // Create a new custom exception class
php artisan make:factory // Create a new model factory
php artisan make:job // Create a new job class
php artisan make:listener // Create a new event listener class
php artisan make:mail // Create a new email class
php artisan make:middleware // Create a new middleware class
php artisan make:migration // Create a new migration file
php artisan make:model // Create a new Eloquent model class
php artisan make:notification // Create a new notification class
php artisan make:observer // Create a new observer class
php artisan make:policy // Create a new policy class
php artisan make:provider // Create a new service provider class
php artisan make:request // Create a new form request class
php artisan make:resource // Create a new resource
php artisan make:rule // Create a new validation rule
php artisan make:scope // Create a new scope class
php artisan make:seeder // Create a new seeder class
php artisan make:test // Create a new test class
// MIGRATE
php artisan migrate:fresh // Drop all tables and re-run all migrations
php artisan migrate:install // Create the migration repository
php artisan migrate:refresh // Reset and re-run all migrations
php artisan migrate:reset // Rollback all database migrations
php artisan migrate:rollback // Rollback the last database migration
php artisan migrate:status // Show the status of each migration
// MODEL
php artisan model:prune // Prune models that are no longer needed
php artisan model:show // Show information about an Eloquent model
// NOTIFICATIONS
php artisan notifications:table // Create a migration for the notifications table
// OPTIMIZE
php artisan optimize:clear // Remove the cached bootstrap files
// PACKAGE
php artisan package:discover // Rebuild the cached package manifest
// QUEUE
php artisan queue:batches-table // Create a migration for the batches database table
php artisan queue:clear // Delete all of the jobs from the specified queue
php artisan queue:failed // List all of the failed queue jobs
php artisan queue:failed-table // Create a migration for the failed queue jobs database table
php artisan queue:flush // Flush all of the failed queue jobs
php artisan queue:forget // Delete a failed queue job
php artisan queue:listen // Listen to a given queue
php artisan queue:monitor // Monitor the size of the specified queues
php artisan queue:prune-batches // Prune stale entries from the batches database
php artisan queue:prune-failed // Prune stale entries from the failed jobs table
php artisan queue:restart // Restart queue worker daemons after their current job
php artisan queue:retry // Retry a failed queue job
php artisan queue:retry-batch // Retry the failed jobs for a batch
php artisan queue:table // Create a migration for the queue jobs database table
php artisan queue:work // Start processing jobs on the queue as a daemon
// ROUTE
php artisan route:cache // Create a route cache file for faster route registration
php artisan route:clear // Remove the route cache file
php artisan route:list // List all registered routes
// SAIL
php artisan sail:install // Install Laravel Sail's default Docker Compose file
php artisan sail:publish // Publish the Laravel Sail Docker files
// SANCTUM
php artisan sanctum:prune-expired // Prune tokens expired for more than specified number of hours.
// SCHEDULE
php artisan schedule:clear-cache // Delete the cached mutex files created by scheduler
php artisan schedule:list // List the scheduled commands
php artisan schedule:run // Run the scheduled commands
php artisan schedule:test // Run a scheduled command
php artisan schedule:work // Start the schedule worker
// SCHEMA
php artisan schema:dump // Dump the given database schema
// SESSION
php artisan session:table // Create a migration for the session database table
// STORAGE
php artisan storage:link // Create a symbolic link from "public/storage" to "storage/app/public"
// STUD
php artisan stub:publish // Publish all stubs that are available for customization
// VENDOR
php artisan vendor:publish // Publish any publishable assets from vendor packages
// VIEW
php artisan view:cache // Compile all of the application's Blade templates
php artisan view:clear // Clear all compiled view files
/********************************************************************************************
* REQUEST
* https://laravel.com/api/5.8/Illuminate/Http/Request.html
* https://laravel.com/docs/5.8/requests
********************************************************************************************/
/********************************************************************************************
* RESPONSE
* https://laravel.com/api/5.8/Illuminate/Http/Response.html
* https://laravel.com/docs/5.8/responses
********************************************************************************************/
/********************************************************************************************
* ROUTING
* https://laravel.com/docs/5.8/routing
********************************************************************************************/
/********************************************************************************************
* MIDDLEWARE
* https://laravel.com/docs/5.8/middleware
********************************************************************************************/
/********************************************************************************************
* CONTROLLERS
* https://laravel.com/docs/5.8/controllers
********************************************************************************************/
/********************************************************************************************
* SESSION
* https://laravel.com/docs/5.8/session
********************************************************************************************/
/********************************************************************************************
* URL GENERATION
* https://laravel.com/docs/5.8/urls
********************************************************************************************/
/********************************************************************************************
* VALIDATION
* https://laravel.com/docs/5.8/validation
********************************************************************************************/
accepted // The field under validation must be yes, on, 1, or true.
active_url // The field under validation must have a valid A or AAAA record according to the dns_get_record PHP function.
after:date // The field under validation must be a value after a given date.
after_or_equal:date // The field under validation must be a value after or equal to the given date.
alpha // The field under validation must be entirely alphabetic characters.
alpha_dash // The field under validation may have alpha-numeric characters, as well as dashes and underscores.
alpha_num // The field under validation must be entirely alpha-numeric characters.
array // The field under validation must be a PHP array.
bail // Stop running validation rules after the first validation failure.
before:date // The field under validation must be a value preceding the given date.
before_or_equal:date // The field under validation must be a value preceding or equal to the given date.
between:min,max // The field under validation must have a size between the given min and max.
boolean // The field under validation must be able to be cast as a boolean. Accepted input are true, false, 1, 0, "1", and "0".
confirmed // The field under validation must have a matching field of foo_confirmation.
date // The field under validation must be a valid, non-relative date according to the strtotime PHP function.
date_equals:date // The field under validation must be equal to the given date.
date_format:format // The field under validation must match the given format.
different:field // The field under validation must have a different value than field.
digits:value // The field under validation must be numeric and must have an exact length of value.
digits_between:min,max // The field under validation must have a length between the given min and max.
dimensions // The file under validation must be an image meeting the dimension constraints as specified by the rule's parameters.
distinct // When working with arrays, the field under validation must not have any duplicate values.
email // The field under validation must be formatted as an e-mail address.
ends_with:foo,bar,... // The field under validation must end with one of the given values.
exists:table,column // The field under validation must exist on a given database table.
file // The field under validation must be a successfully uploaded file.
filled // The field under validation must not be empty when it is present.
gt:field // The field under validation must be greater than the given field.
gte:field // The field under validation must be greater than or equal to the given field.
image // The file under validation must be an image (jpeg, png, bmp, gif, svg, or webp)
in:foo,bar,... // The field under validation must be included in the given list of values.
in_array:anotherfield.* // The field under validation must exist in anotherfield's values.
integer // The field under validation must be an integer.
ip // The field under validation must be an IP address.
ipv4 // The field under validation must be an IPv4 address.
ipv6 // The field under validation must be an IPv6 address.
json // The field under validation must be a valid JSON string.
lt:field // The field under validation must be less than the given field.
lte:field // The field under validation must be less than or equal to the given field.
max:value // The field under validation must be less than or equal to a maximum value.
mimetypes:text/plain,... // The file under validation must match one of the given MIME types:
mimes:foo,bar,... // The file under validation must have a MIME type corresponding to one of the listed extensions.
min:value // The field under validation must have a minimum value.
not_in:foo,bar,... // The field under validation must not be included in the given list of values.
not_regex:pattern // The field under validation must not match the given regular expression.
nullable // The field under validation may be null.
numeric // The field under validation must be numeric.
present // The field under validation must be present in the input data but can be empty.
regex:pattern // The field under validation must match the given regular expression.
required // The field under validation must be present in the input data and not empty.
required_if:anotherfield,value,... // The field under validation must be present and not empty if the anotherfield field is equal to any value.
required_unless:anotherfield,value,... // The field under validation must be present and not empty unless the anotherfield field is equal to any value.
required_with:foo,bar,... // The field under validation must be present and not empty only if any of the other specified fields are present.
required_with_all:foo,bar,... // The field under validation must be present and not empty only if all of the other specified fields are present.
required_without:foo,bar,... // The field under validation must be present and not empty only when any of the other specified fields are not present.
required_without_all:foo,bar,... // The field under validation must be present and not empty only when all of the other specified fields are not present.
same:field // The given field must match the field under validation.
size:value // The field under validation must have a size matching the given value.
starts_with:foo,bar,... // The field under validation must start with one of the given values.
string // The field under validation must be a string.
timezone // The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.
unique:table,column,except,idColumn // The field under validation must not exist within the given database table.
url // The field under validation must be a valid URL.
uuid // The field under validation must be a valid RFC 4122 (version 1, 3, 4, or 5) universally unique identifier (UUID).
/********************************************************************************************
* ERROR HANDLING
* https://laravel.com/docs/5.8/errors
********************************************************************************************/
/********************************************************************************************
* MIGRATION COMMANDS
* https://laravel.com/docs/5.8/migrations
********************************************************************************************/
// TABLE OPTIONS
$table->engine = 'InnoDB'; // Specify the table storage engine (MySQL).
$table->charset = 'utf8'; // Specify a default character set for the table (MySQL).
$table->collation = 'utf8_unicode_ci'; // Specify a default collation for the table (MySQL).
$table->temporary(); // Create a temporary table (except SQL Server).
// COLUMN TYPES
$table->bigIncrements('id'); // Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column.
$table->bigInteger('votes'); // BIGINT equivalent column.
$table->binary('data'); // BLOB equivalent column.
$table->boolean('confirmed'); // BOOLEAN equivalent column.
$table->char('name', 100); // CHAR equivalent column with an optional length.
$table->date('created_at'); // DATE equivalent column.
$table->dateTime('created_at'); // DATETIME equivalent column.
$table->dateTimeTz('created_at'); // DATETIME (with timezone) equivalent column.
$table->decimal('amount', 8, 2); // DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->double('amount', 8, 2); // DOUBLE equivalent column with a precision (total digits) and scale (decimal digits).
$table->enum('level', ['easy', 'hard']); // ENUM equivalent column.
$table->float('amount', 8, 2); // FLOAT equivalent column with a precision (total digits) and scale (decimal digits).
$table->geometry('positions'); // GEOMETRY equivalent column.
$table->geometryCollection('positions'); // GEOMETRYCOLLECTION equivalent column.
$table->increments('id'); // Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column.
$table->integer('votes'); // INTEGER equivalent column.
$table->ipAddress('visitor'); // IP address equivalent column.
$table->json('options'); // JSON equivalent column.
$table->jsonb('options'); // JSONB equivalent column.
$table->lineString('positions'); // LINESTRING equivalent column.
$table->longText('description'); // LONGTEXT equivalent column.
$table->macAddress('device'); // MAC address equivalent column.
$table->mediumIncrements('id'); // Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column.
$table->mediumInteger('votes'); // MEDIUMINT equivalent column.
$table->mediumText('description'); // MEDIUMTEXT equivalent column.
$table->morphs('taggable'); // Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns.
$table->uuidMorphs('taggable'); // Adds taggable_id CHAR(36) and taggable_type VARCHAR(255) UUID equivalent columns.
$table->multiLineString('positions'); // MULTILINESTRING equivalent column.
$table->multiPoint('positions'); // MULTIPOINT equivalent column.
$table->multiPolygon('positions'); // MULTIPOLYGON equivalent column.
$table->nullableMorphs('taggable'); // Adds nullable versions of morphs() columns.
$table->nullableUuidMorphs('taggable'); // Adds nullable versions of uuidMorphs() columns.
$table->nullableTimestamps(); // Alias of timestamps() method.
$table->point('position'); // POINT equivalent column.
$table->polygon('positions'); // POLYGON equivalent column.
$table->rememberToken(); // Adds a nullable remember_token VARCHAR(100) equivalent column.
$table->set('flavors', ['strawberry', 'vanilla']); // SET equivalent column.
$table->smallIncrements('id'); // Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column.
$table->smallInteger('votes'); // SMALLINT equivalent column.
$table->softDeletes(); // Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes.
$table->softDeletesTz(); // Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes.
$table->string('name', 100); // VARCHAR equivalent column with a optional length.
$table->text('description'); // TEXT equivalent column.
$table->time('sunrise'); // TIME equivalent column.
$table->timeTz('sunrise'); // TIME (with timezone) equivalent column.
$table->timestamp('added_on'); // TIMESTAMP equivalent column.
$table->timestampTz('added_on'); // TIMESTAMP (with timezone) equivalent column.
$table->timestamps(); // Adds nullable created_at and updated_at TIMESTAMP equivalent columns.
$table->timestampsTz(); // Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns.
$table->tinyIncrements('id'); // Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column.
$table->tinyInteger('votes'); // TINYINT equivalent column.
$table->unsignedBigInteger('votes'); // UNSIGNED BIGINT equivalent column.
$table->unsignedDecimal('amount', 8, 2); // UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
$table->unsignedInteger('votes'); // UNSIGNED INTEGER equivalent column.
$table->unsignedMediumInteger('votes'); // UNSIGNED MEDIUMINT equivalent column.
$table->unsignedSmallInteger('votes'); // UNSIGNED SMALLINT equivalent column.
$table->unsignedTinyInteger('votes'); // UNSIGNED TINYINT equivalent column.
$table->uuid('id'); // UUID equivalent column.
$table->year('birth_year'); // YEAR equivalent column.
// COLUMN MODIFIERS
$table->someType()->after('column'); // Place the column "after" another column (MySQL)
$table->someType()->autoIncrement(); // Set INTEGER columns as auto-increment (primary key)
$table->someType()->charset('utf8'); // Specify a character set for the column (MySQL)
$table->someType()->collation('utf8_unicode_ci'); // Specify a collation for the column (MySQL/SQL Server)
$table->someType()->comment('my comment'); // Add a comment to a column (MySQL/PostgreSQL)
$table->someType()->default($value); // Specify a "default" value for the column
$table->someType()->first(); // Place the column "first" in the table (MySQL)
$table->someType()->nullable($value = true); // Allows (by default) NULL values to be inserted into the column
$table->someType()->storedAs($expression); // Create a stored generated column (MySQL)
$table->someType()->unsigned(); // Set INTEGER columns as UNSIGNED (MySQL)
$table->someType()->useCurrent(); // Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value
$table->someType()->virtualAs($expression); // Create a virtual generated column (MySQL)
$table->someType()->generatedAs($expression); // Create an identity column with specified sequence options (PostgreSQL)
$table->someType()->always(); // Defines the precedence of sequence values over input for an identity column (PostgreSQL)
// UPDATING COLUMNS
$table->someType()->change(); // Allows you to modify some existing column types to a new type or modify the column's attributes.
$table->renameColumn('from', 'to'); // Rename a column
$table->dropColumn('column'); // Drop a given column (accepts an array of columns).
$table->dropRememberToken(); // Drop the remember_token column.
$table->dropSoftDeletes(); // Drop the deleted_at column.
$table->dropSoftDeletesTz(); // Alias of dropSoftDeletes() method.
$table->dropTimestamps(); // Drop the created_at and updated_at columns.
$table->dropTimestampsTz(); // Alias of dropTimestamps() method.
// INDEXES
$table->primary('id'); // Adds a primary key.
$table->primary(['id', 'parent_id']); // Adds composite keys.
$table->unique('email'); // Adds a unique index.
$table->index('state'); // Adds a plain index.
$table->spatialIndex('location'); // Adds a spatial index. (except SQLite)
$table->dropPrimary('users_id_primary'); // Drop a primary key from the "users" table.
$table->dropUnique('users_email_unique'); // Drop a unique index from the "users" table.
$table->dropIndex('geo_state_index'); // Drop a basic index from the "geo" table.
$table->dropSpatialIndex('geo_location_spatialindex'); // Drop a spatial index from the "geo" table (except SQLite).
// FOREIGN KEY CONSTRAINTS
$table->foreign('user_id')->references('id')->on('users'); // Create foreign key constraints.
$table->dropForeign('posts_user_id_foreign'); // Drop foreign key (accepts an array of strings).
Schema::enableForeignKeyConstraints(); // Enable foreign key constraints within your migrations.
Schema::disableForeignKeyConstraints(); // Disable foreign key constraints within your migrations.
/********************************************************************************************
* COLLECTION ELOQUENT METHODS
* https://laravel.com/docs/5.7/collections
********************************************************************************************/
all
average
avg
chunk
collapse
combine
concat
contains
containsStrict
count
crossJoin
dd
diff
diffAssoc
diffKeys
dump
each
eachSpread
every
except
filter
first
firstWhere
flatMap
flatten
flip
forget
forPage
get
groupBy
has
implode
intersect
intersectByKeys
isEmpty
isNotEmpty
keyBy
keys
last
macro
make
map
mapInto
mapSpread
mapToGroups
mapWithKeys
max
median
merge
min
mode
nth
only
pad
partition
pipe
pluck
pop
prepend
pull
push
put
random
reduce
reject
reverse
search
shift
shuffle
slice
some
sort
sortBy
sortByDesc
sortKeys
sortKeysDesc
splice
split
sum
take
tap
times
toArray
toJson
transform
union
unique
uniqueStrict
unless
unlessEmpty
unlessNotEmpty
unwrap
values
when
whenEmpty
whenNotEmpty
where
whereStrict
whereBetween
whereIn
whereInStrict
whereInstanceOf
whereNotBetween
whereNotIn
whereNotInStrict
wrap
zip
/********************************************************************************************
* HTTP TESTS
* https://laravel.com/docs/5.7/http-tests
********************************************************************************************/
$response->assertStatus($code); // Assert that the response has a given code.
$response->assertForbidden(); // Assert that the response has a forbidden status code.
$response->assertNotFound(); // Assert that the response has a not found status code.
$response->assertOk(); // Assert that the response has a 200 status code.
$response->assertSuccessful(); // Assert that the response has a successful status code.
$response->assertRedirect($uri); // Assert that the response is a redirect to a given URI.
$response->assertHeader($headerName, $value = null); // Assert that the given header is present on the response.
$response->assertHeaderMissing($headerName); // Assert that the given header is not present on the response.
$response->assertExactJson(array $data); // Assert that the response contains an exact match of the given JSON data.
$response->assertJson(array $data); // Assert that the response contains the given JSON data.
$response->assertJsonCount($count, $key = null); // Assert that the response JSON has an array with the expected number of items at the given key.
$response->assertJsonFragment(array $data); // Assert that the response contains the given JSON fragment.
$response->assertJsonMissing(array $data); // Assert that the response does not contain the given JSON fragment.
$response->assertJsonMissingExact(array $data); // Assert that the response does not contain the exact JSON fragment.
$response->assertJsonMissingValidationErrors($keys); // Assert that the response has no JSON validation errors for the given keys.
$response->assertJsonStructure(array $structure); // Assert that the response has a given JSON structure.
$response->assertJsonValidationErrors($keys); // Assert that the response has the given JSON validation errors for the given keys.
$response->assertDontSee($value); // Assert that the given string is not contained within the response.
$response->assertDontSeeText($value); // Assert that the given string is not contained within the response text.
$response->assertSee($value); // Assert that the given string is contained within the response.
$response->assertSeeInOrder(array $values); // Assert that the given strings are contained in order within the response.
$response->assertSeeText($value); // Assert that the given string is contained within the response text.
$response->assertSeeTextInOrder(array $values); // Assert that the given strings are contained in order within the response text.
$response->assertCookie($cookieName, $value = null); // Assert that the response contains the given cookie.
$response->assertCookieExpired($cookieName); // Assert that the response contains the given cookie and it is expired.
$response->assertCookieNotExpired($cookieName); // Assert that the response contains the given cookie and it is not expired.
$response->assertCookieMissing($cookieName); // Assert that the response does not contains the given cookie.
$response->assertPlainCookie($cookieName, $value = null); // Assert that the response contains the given cookie (unencrypted).
$response->assertSessionHas($key, $value = null); // Assert that the session contains the given piece of data.
$response->assertSessionHasAll(array $data); // Assert that the session has a given list of values.
$response->assertSessionHasErrors(array $keys, $format = null, $errorBag = 'default'); // Assert that the session contains an error for the given field.
$response->assertSessionHasErrorsIn($errorBag, $keys = [], $format = null); // Assert that the session has the given errors.
$response->assertSessionHasNoErrors(); // Assert that the session has no errors.
$response->assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default'); // Assert that the session has no errors for the given keys.
$response->assertSessionMissing($key); // Assert that the session does not contain the given key.
$response->assertViewHas($key, $value = null); // Assert that the response view was given a piece of data.
$response->assertViewHasAll(array $data); // Assert that the response view has a given list of data.
$response->assertViewIs($value); // Assert that the given view was returned by the route.
$response->assertViewMissing($key); // Assert that the response view is missing a piece of bound data.
$this->assertAuthenticated($guard = null); // Assert that the user is authenticated.
$this->assertGuest($guard = null); // Assert that the user is not authenticated.
$this->assertAuthenticatedAs($user, $guard = null); // Assert that the given user is authenticated.
$this->assertCredentials(array $credentials, $guard = null); // $this->assertCredentials(array $credentials, $guard = null).
$this->assertInvalidCredentials(array $credentials, $guard = null); // Assert that the given credentials are invalid.
/********************************************************************************************
* LARAVEL VALET COMMANDS
* https://laravel.com/docs/6.0/valet
********************************************************************************************/
valet install // Install the Valet daemon.
valet uninstall // Uninstall the Valet daemon.
valet use php@7.2 // Allows you to switch between php versions.
valet start // Start the Valet daemon.
valet stop // Stop the Valet daemon.
valet restart // Restart the Valet daemon.
valet park // Register your current working directory as a path which Valet should search for sites.
valet forget // Run this command from a "parked" directory to remove it from the parked directory list.
valet paths // View all of your "parked" paths.
valet link <name> // Link a single site in the current directory and not the entire directory.
valet unlink <name> // Unlink a single site in the current directory
valet links // View all of your "linked" paths.
valet secure // Serve site into https
valet unsecure // Revert back to http
valet log // View a list of logs which are written by Valet's services.
valet trust // Add sudoers files for Brew and Valet to allow Valet commands to be run without prompting for passwords.
valet tld <suffix> // Update tld for your domains (default to test).
valet share // Share your site with the world.
+747
View File
@@ -0,0 +1,747 @@
/* *******************************************************************************************
* MOLECULER MICROSERVICES FRAMEWORK - CORE CHEATSHEET
* http://moleculer.services/0.12/docs/
*
* Version: 0.12.x
* ******************************************************************************************* */
/* *******************************************************************************************
* Install Moleculer
* ******************************************************************************************* */
```bash
npm i moleculer
```
/* *******************************************************************************************
* SERVICE BROKER OPTIONS
* ******************************************************************************************* */
// All ServiceBroker options with default values
const broker = new ServiceBroker({
namespace: "", // Namespace for node segmentation
nodeID: null, // NodeID. Default value is generated from hostname and PID
logger: null, // Logger instance.
logLevel: null, // Log level
logFormatter: "default", // Log formatter. Options: "default", "simple"
transporter: null, // Transporter config
requestTimeout: 0 * 1000, // Timeout of requests
requestRetry: 0, // Retries for requests
maxCallLevel: 0, // Maximum calling level.
heartbeatInterval: 5, // Heartbeat sending interval in seconds
heartbeatTimeout: 15, // Heartbeat timeout in seconds
disableBalancer: false, // Disable the built-in Moleculer balancer
registry: { // Service Registry options
strategy: "RoundRobin", // Invocation strategy
strategyOptions: null, // Strategy options
preferLocal: true // Prefer local invocations
},
circuitBreaker: { // Circuit-breaker options
enabled: false, // Enable circuit-breaker
maxFailures: 3, // Maximum failures
halfOpenTime: 10 * 1000, // Half-open time interval
failureOnTimeout: true, // Failure on timeouts
failureOnReject: true // Failure on rejects
},
transit: { // Transit options
maxQueueSize: 50 * 1000 // Max items in outgoing queue
},
cacher: null, // Cacher config
serializer: null, // Serializer config
validation: true, // Enable params validation
validator: null, // Validator instance
metrics: false, // Enable metrics
metricsRate: 1, // Metrics rate
statistics: false, // Enable statistics
internalServices: true, // Load internal ($node) services
hotReload: false, // Hot-reload services
middlewares: null, // List of middlewares
replCommands: null, // Custom REPL commands
ServiceFactory: null, // Custom Service factory class
ContextFactory: null // Custom Context factory class
});
/* *******************************************************************************************
* SERVICE BROKER METHODS
* ******************************************************************************************* */
// Broker properties
broker.Promise // Pointer to Bluebird Promise lib
broker.namespace // Namespace from options
broker.nodeID // Local NodeID
broker.logger // Logger instance
broker.cacher // Cacher instance
broker.serializer // Serializer instance
broker.validator // Validator instance
// Broker methods
broker.start(); // Start broker & all services. Returns a Promise
broker.stop(); // Stop broker & all services. Returns a Promise
broker.fatal(message, err, needExit = true); // Fired a fatal error.
broker.repl(); // Switch broker to REPL mode.
broker.getLogger(module, service, version); // Create a custom logger instance for modules
broker.loadServices(folder, fileMask); // Load all services from directory
broker.loadService(filePath); // Load a service from a file
broker.createService(schema, schemaMods); // Create a local service from schema
broker.destroyService(service); // Destroy a local service
broker.getLocalService(name, version); // Get a local service instance by name
// Wait for services. Returns a Promise
await broker.waitForServices(serviceNames, timeout, interval);
await broker.waitForServices(["posts", "users"], 5000);
await broker.waitForServices({
name: "posts", version: 2,
name: "users", version: 1
}, 5000);
broker.use(...middlewares); // Register middlewares
broker.call(actionName, params, opts); // Call a service
broker.mcall(def); // Multiple service calls
broker.emit(eventName, payload, groups); // Emit a balanced event
broker.broadcast(eventName, payload, groups = null) // Broadcast an event
broker.broadcastLocal(eventName, payload, groups = null) // Broadcast an event to local services
broker.sendPing(nodeID); // Ping a remote node
broker.MOLECULER_VERSION // Version number of Moleculer lib
broker.PROTOCOL_VERSION // Version number of Moleculer protocol
/* *******************************************************************************************
* BROKER SERVICE CALLS
* ******************************************************************************************* */
// Call the "users.get" service with params
broker.call("users.get", { id: 150 }).then(user => console.log(user));
// Call with async/await
const user = await broker.call("users.get", { id: 150});
// Call with calling options
const user = await broker.call("users.get", { id: 150}, { timeout: 5000, retryCount: 3 });
// Direct call to a remote node
const info = await broker.call("$node.services", null, { nodeID: "node-123" });
// Multiple calls with array def
const [posts, users] = await broker.mcall([
{ action: "posts.find", params: { limit: 5, offset: 0 } },
{ action: "users.find", params: { limit: 5, sort: "username" }, opts: { timeout: 500 } }
]);
// Multip calls with object def
const res = await broker.mcall({
posts: { action: "posts.find", params: { limit: 5, offset: 0 } },
users: { action: "users.find", params: { limit: 5, sort: "username" }, opts: { timeout: 500 } }
});
console.log(res.posts, res.users);
/* *******************************************************************************************
* BROKER EVENTS
* ******************************************************************************************* */
// Send a balanced event with payload
broker.emit("user.created", { user: user });
// Send a balanced event only for "mail" and "payment" service (only one instance)
broker.emit("user.created", { user: user }, ["mail", "payment"]);
// Send a broadcast event (for all service instances)
broker.broadcast("user.created", { user: user });
// Send a broadcast event only for "mail" and "payment" services (all instances)
broker.broadcast("user.created", { user: user }, ["mail", "payment"]);
/* *******************************************************************************************
* NATS TRANSPORTER
* Requirement: `npm i nats`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "NATS"
});
// With URI
const broker = new ServiceBroker({
transporter: "nats://localhost:4222"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "NATS",
options: {
url: "nats://localhost:4222",
user: "admin",
pass: "1234"
}
}
});
// With TLS (https://github.com/nats-io/node-nats#tls)
const broker = new ServiceBroker({
transporter: {
type: "NATS",
options: {
url: "nats://localhost:4222",
tls: {
key: fs.readFileSync('./client-key.pem'),
cert: fs.readFileSync('./client-cert.pem'),
ca: [ fs.readFileSync('./ca.pem') ]
}
}
}
});
/* *******************************************************************************************
* REDIS TRANSPORTER
* Requirement: `npm i ioredis`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "Redis"
});
// With URI
const broker = new ServiceBroker({
transporter: "redis://redis-server:6379"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "Redis",
options: {
port: 6379, // Redis port
host: 'redis-server', // Redis host
family: 4, // 4 (IPv4) or 6 (IPv6)
password: 'auth', // Password
db: 0 // Database index
}
}
});
/* *******************************************************************************************
* MQTT TRANSPORTER
* Requirement: `npm i mqtt`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "MQTT"
});
// With URI
const broker = new ServiceBroker({
transporter: "mqtt://mqtt-server:1883"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "MQTT",
options: {
host: "mqtt-server",
port: 1883,
username: "admin",
password: "1234"
}
}
});
/* *******************************************************************************************
* AMQP TRANSPORTER
* Requirement: `npm i amqplib`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "AMQP"
});
// With URI
const broker = new ServiceBroker({
transporter: "amqp://rabbitmq-server:5672"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "AMQP",
options: {
url: "amqp://user:pass@rabbitmq-server:5672",
eventTimeToLive: 5000,
prefetch: 1
}
}
});
/* *******************************************************************************************
* KAFKA TRANSPORTER
* Requirement: `npm i kafka-node`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "Kafka"
});
// With URI
const broker = new ServiceBroker({
transporter: "kafka://192.168.51.29:2181"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "kafka",
options: {
host: "192.168.51.29:2181",
// KafkaClient options. More info: https://github.com/SOHU-Co/kafka-node#clientconnectionstring-clientid-zkoptions-noackbatchoptions-ssloptions
client: {
zkOptions: undefined,
noAckBatchOptions: undefined,
sslOptions: undefined
},
// KafkaProducer options. More info: https://github.com/SOHU-Co/kafka-node#producerclient-options-custompartitioner
producer: {},
customPartitioner: undefined,
// ConsumerGroup options. More info: https://github.com/SOHU-Co/kafka-node#consumergroupoptions-topics
consumer: {
},
// Advanced options for `send`. More info: https://github.com/SOHU-Co/kafka-node#sendpayloads-cb
publish: {
partition: 0,
attributes: 0
}
}
}
});
/* *******************************************************************************************
* NATS STREAMING TRANSPORTER
* Requirement: `npm i node-nats-streaming`
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "STAN"
});
// With URI
const broker = new ServiceBroker({
transporter: "stan://192.168.0.120:4222"
});
// With options
const broker = new ServiceBroker({
transporter: {
type: "STAN",
options: {
url: "stan://127.0.0.1:4222",
clusterID: "my-cluster"
}
}
});
/* *******************************************************************************************
* TCP STREAMING TRANSPORTER
* No requirements
* ******************************************************************************************* */
// Default options
const broker = new ServiceBroker({
transporter: "TCP"
});
// With static node list
const broker = new ServiceBroker({
transporter: "tcp://172.17.0.1:6000/node-1,172.17.0.2:6000/node-2"
});
const broker = new ServiceBroker({
nodeID: "node-1",
transporter: {
type: "TCP",
options: {
udpDiscovery: false,
urls: [
"172.17.0.1:6000/node-1",
"172.17.0.2:6000/node-2",
"172.17.0.3:6000/node-3"
]
}
}
});
// With full options
const broker = new ServiceBroker({
logger: true,
transporter: {
type: "TCP",
options: {
// Enable UDP discovery
udpDiscovery: true,
// Reusing UDP server socket
udpReuseAddr: true,
// UDP port
udpPort: 4445,
// UDP bind address
udpBindAddress: null,
// UDP sending period
udpPeriod: 5,
// Multicast address.
udpMulticast: "239.0.0.0",
// Multicast TTL setting
udpMulticastTTL: 1,
// Send broadcast
udpBroadcast: false,
// TCP server port. Null or 0 means random port
port: null,
// Static remote nodes address list (when UDP discovery is not available)
urls: null,
// Use hostname as preffered connection address
useHostname: true,
// Gossip sending period in seconds
gossipPeriod: 2,
// Maximum enabled outgoing connections. If reach, close the old connections
maxConnections: 32,
// Maximum TCP packet size
maxPacketSize: 1 * 1024 * 1024
}
}
});
/* *******************************************************************************************
* CACHERS
* http://moleculer.services/docs/cachers.html
* ******************************************************************************************* */
// Memory cacher
const broker = new ServiceBroker({
cacher: "Memory"
});
// or
const broker = new ServiceBroker({
cacher: true
});
// Memory cacher with options
const broker = new ServiceBroker({
cacher: {
type: "Memory",
options: {
ttl: 30
}
}
});
// Redis cacher
const broker = new ServiceBroker({
cacher: "Redis"
});
// Redis cacher with URI
const broker = new ServiceBroker({
cacher: "redis://redis-server:6379"
});
// Redis cacher with options
const broker = new ServiceBroker({
cacher: {
type: "Redis",
options: {
prefix: "MOL",
redis: {
host: "redis",
port: 6379,
password: "1234",
db: 0
}
}
}
});
/* *******************************************************************************************
* Manual caching
* ******************************************************************************************* */
// Save to cache
broker.cacher.set("mykey.a", { a: 5 });
// Get from cache
const obj = await broker.cacher.get("mykey.a");
// Remove entry from cache
broker.cacher.del("mykey.a");
// Clean all 'mykey' entries
broker.cacher.clean("mykey.*");
// Clean all entries
broker.cacher.clean();
/* *******************************************************************************************
* SERIALIZER
* http://moleculer.services/docs/serializers.html
* ******************************************************************************************* */
// JSON serializer (default)
const broker = new ServiceBroker({
serializer: "JSON"
});
// Avro serializer (need `npm i avsc`)
const broker = new ServiceBroker({
serializer: "Avro"
});
// Protocol Buffer serializer (need `npm i protobufjs`)
const broker = new ServiceBroker({
serializer: "ProtoBuf"
});
// MsgPack serializer (need `npm i msgpack5`)
const broker = new ServiceBroker({
serializer: "MsgPack"
});
/* *******************************************************************************************
* STRATEGY
* ******************************************************************************************* */
// Round-robin strategy (default)
const broker = new ServiceBroker({
registry: {
strategy: "RoundRobin"
}
});
// Random strategy
const broker = new ServiceBroker({
registry: {
strategy: "Random"
}
});
// CPU usage-based strategy
const broker = new ServiceBroker({
registry: {
strategy: "CpuUsageStrategy"
}
});
// CPU usage-based strategy with options
const broker = new ServiceBroker({
registry: {
strategy: "CpuUsageStrategy",
strategyOptions: {
sampleCount: 3,
lowCpuUsage: 10
}
}
});
/* *******************************************************************************************
* LOGGER
* http://moleculer.services/docs/logger.html
* ******************************************************************************************* */
// Logger methods
broker.logger.fatal();
broker.logger.error();
broker.logger.warn();
broker.logger.info();
broker.logger.debug();
broker.logger.trace();
// Custom log formatter
const broker = new ServiceBroker({
logger: console,
logFormatter(level, args, bindings) {
return level.toUpperCase() + " " + bindings.nodeID + ": " + args.join(" ");
}
});
// External Pino logger
const pino = require("pino")({ level: "info" });
const broker = new ServiceBroker({
logger: bindings => pino.child(bindings)
});
// External Bunyan logger
const logger = require("bunyan").createLogger({ name: "moleculer", level: "info" });
const broker = new ServiceBroker({
logger: bindings => logger.child(bindings)
});
/* *******************************************************************************************
* SERVICE SCHEMA
* ******************************************************************************************* */
module.exports = {
// Name
name: "greeter",
// Version
version: 2,
// Settings
settings: {},
// Metadata
metadata: {},
// Dependencies
dependencies: [],
// Actions
actions: {
// Shorthand actions
hello() {
// Call a method
this.doSomething();
return "Hello Moleculer";
},
// With properties
welcome: {
// Cache options
cache: {
keys: ["name"]
},
// Validation options
params: {
name: "string"
},
// Action handler
handler(ctx) {
return `Welcome, ${ctx.params.name}`;
}
}
},
events: {
"user.created"(payload, sender) {
}
},
// Service methods
methods: {
doSomething() {}
},
// Lifecycle event handlers
created() {
console.log("Service created");
},
started() {
console.log("Service started");
return Promise.resolve();
},
stopped() {
console.log("Service stopped");
return Promise.resolve();
}
};
/* *******************************************************************************************
* SERVICE
* ******************************************************************************************* */
this.name // Name of service
this.version // Version of service
this.settings // Settings of service
this.schema // Schema definition of service
this.broker // Broker instance
this.Promise // Class of Promise (Bluebird)
this.logger // Logger instance
this.actions // Actions of service.
this.waitForServices // Pointer to broker.waitForServices method
/* *******************************************************************************************
* CONTEXT
* ******************************************************************************************* */
ctx.id // Context ID
ctx.broker // Broker instance
ctx.action // Action definition
ctx.nodeID // Node ID
ctx.requestID // Request ID
ctx.parentID // ID of parent context (in case of sub-calls).
ctx.params // Request params
ctx.meta // Request metadata
ctx.callerNodeID // Caller Node ID if it is requested from a remote node.
ctx.level // Request level (in case of sub-calls). The first level is 1.
// Make a sub-call
ctx.call(actionName, params, callingOptions)
// Emit an event
ctx.emit(eventName, payload, groups);
+565
View File
@@ -0,0 +1,565 @@
/* *******************************************************************************************
* SYNOPSIS
* http://nodejs.org/api/synopsis.html
* ******************************************************************************************* */
var http = require('http');
// An example of a web server written with Node which responds with 'Hello World'.
// To run the server, put the code into a file called example.js and execute it with the node program.
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
/* *******************************************************************************************
* GLOBAL OBJECTS
* http://nodejs.org/api/globals.html
* ******************************************************************************************* */
// In browsers, the top-level scope is the global scope.
// That means that in browsers if you're in the global scope var something will define a global variable.
// In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.
__filename; // The filename of the code being executed. (absolute path)
__dirname; // The name of the directory that the currently executing script resides in. (absolute path)
module; // A reference to the current module. In particular module.exports is used for defining what a module exports and makes available through require().
exports; // A reference to the module.exports that is shorter to type.
process; // The process object is a global object and can be accessed from anywhere. It is an instance of EventEmitter.
Buffer; // The Buffer class is a global type for dealing with binary data directly.
/* *******************************************************************************************
* CONSOLE
* http://nodejs.org/api/console.html
* ******************************************************************************************* */
console.log([data], [...]); // Prints to stdout with newline.
console.info([data], [...]); // Same as console.log.
console.error([data], [...]); // Same as console.log but prints to stderr.
console.warn([data], [...]); // Same as console.error.
console.dir(obj); // Uses util.inspect on obj and prints resulting string to stdout.
console.time(label); // Mark a time.
console.timeEnd(label); // Finish timer, record output.
console.trace(label); // Print a stack trace to stderr of the current position.
console.assert(expression, [message]); // Same as assert.ok() where if the expression evaluates as false throw an AssertionError with message.
/* *******************************************************************************************
* TIMERS
* http://nodejs.org/api/timers.html
* ******************************************************************************************* */
setTimeout(callback, delay, [arg], [...]); // To schedule execution of a one-time callback after delay milliseconds. Optionally you can also pass arguments to the callback.
clearTimeout(t); // Stop a timer that was previously created with setTimeout().
setInterval(callback, delay, [arg], [...]); // To schedule the repeated execution of callback every delay milliseconds. Optionally you can also pass arguments to the callback.
clearInterval(t); // Stop a timer that was previously created with setInterval().
setImmediate(callback, [arg], [...]); // To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval.
clearImmediate(immediateObject); // Stop a timer that was previously created with setImmediate().
unref(); // Allow you to create a timer that is active but if it is the only item left in the event loop, node won't keep the program running.
ref(); // If you had previously unref()d a timer you can call ref() to explicitly request the timer hold the program open.
/* *******************************************************************************************
* MODULES
* http://nodejs.org/api/modules.html
* ******************************************************************************************* */
var module = require('./module.js'); // Loads the module module.js in the same directory.
module.require('./another_module.js'); // load another_module as if require() was called from the module itself.
module.id; // The identifier for the module. Typically this is the fully resolved filename.
module.filename; // The fully resolved filename to the module.
module.loaded; // Whether or not the module is done loading, or is in the process of loading.
module.parent; // The module that required this one.
module.children; // The module objects required by this one.
exports.area = function (r) {
return Math.PI * r * r;
};
// If you want the root of your module's export to be a function (such as a constructor)
// or if you want to export a complete object in one assignment instead of building it one property at a time,
// assign it to module.exports instead of exports.
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
/* *******************************************************************************************
* PROCESS
* http://nodejs.org/api/process.html
* ******************************************************************************************* */
process.on('exit', function(code) {}); // Emitted when the process is about to exit
process.on('uncaughtException', function(err) {}); // Emitted when an exception bubbles all the way back to the event loop. (should not be used)
process.stdout; // A writable stream to stdout.
process.stderr; // A writable stream to stderr.
process.stdin; // A readable stream for stdin.
process.argv; // An array containing the command line arguments.
process.env; // An object containing the user environment.
process.execPath; // This is the absolute pathname of the executable that started the process.
process.execArgv; // This is the set of node-specific command line options from the executable that started the process.
process.arch; // What processor architecture you're running on: 'arm', 'ia32', or 'x64'.
process.config; // An Object containing the JavaScript representation of the configure options that were used to compile the current node executable.
process.pid; // The PID of the process.
process.platform; // What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'.
process.title; // Getter/setter to set what is displayed in 'ps'.
process.version; // A compiled-in property that exposes NODE_VERSION.
process.versions; // A property exposing version strings of node and its dependencies.
process.abort(); // This causes node to emit an abort. This will cause node to exit and generate a core file.
process.chdir(dir); // Changes the current working directory of the process or throws an exception if that fails.
process.cwd(); // Returns the current working directory of the process.
process.exit([code]); // Ends the process with the specified code. If omitted, exit uses the 'success' code 0.
process.getgid(); // Gets the group identity of the process.
process.setgid(id); // Sets the group identity of the process.
process.getuid(); // Gets the user identity of the process.
process.setuid(id); // Sets the user identity of the process.
process.getgroups(); // Returns an array with the supplementary group IDs.
process.setgroups(grps); // Sets the supplementary group IDs.
process.initgroups(user, extra_grp); // Reads /etc/group and initializes the group access list, using all groups of which the user is a member.
process.kill(pid, [signal]); // Send a signal to a process. pid is the process id and signal is the string describing the signal to send.
process.memoryUsage(); // Returns an object describing the memory usage of the Node process measured in bytes.
process.nextTick(callback); // On the next loop around the event loop call this callback.
process.maxTickDepth; // Callbacks passed to process.nextTick will usually be called at the end of the current flow of execution, and are thus approximately as fast as calling a function synchronously.
process.umask([mask]); // Sets or reads the process's file mode creation mask.
process.uptime(); // Number of seconds Node has been running.
process.hrtime(); // Returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array.
/* *******************************************************************************************
* CHILD PROCESS
* http://nodejs.org/api/child_process.html
* ******************************************************************************************* */
// Node provides a tri-directional popen facility through the child_process module.
// It is possible to stream data through a child's stdin, stdout, and stderr in a fully non-blocking way.
ChildProcess; // Class. ChildProcess is an EventEmitter.
child.stdin; // A Writable Stream that represents the child process's stdin
child.stdout; // A Readable Stream that represents the child process's stdout
child.stderr; // A Readable Stream that represents the child process's stderr.
child.pid; // The PID of the child process
child.connected; // If .connected is false, it is no longer possible to send messages
child.kill([signal]); // Send a signal to the child process
child.send(message, [sendHandle]); // When using child_process.fork() you can write to the child using child.send(message, [sendHandle]) and messages are received by a 'message' event on the child.
child.disconnect(); // Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive.
child_process.spawn(command, [args], [options]); // Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.
child_process.exec(command, [options], callback); // Runs a command in a shell and buffers the output.
child_process.execFile(file, [args], [options], [callback]); // Runs a command in a shell and buffers the output.
child_process.fork(modulePath, [args], [options]); // This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in.
/* *******************************************************************************************
* UTIL
* http://nodejs.org/api/util.html
* ******************************************************************************************* */
// These functions are in the module 'util'. Use require('util') to access them.
util.format(format, [...]); // Returns a formatted string using the first argument as a printf-like format. (%s, %d, %j)
util.debug(string); // A synchronous output function. Will block the process and output string immediately to stderr.
util.error([...]); // Same as util.debug() except this will output all arguments immediately to stderr.
util.puts([...]); // A synchronous output function. Will block the process and output all arguments to stdout with newlines after each argument.
util.print([...]); // A synchronous output function. Will block the process, cast each argument to a string then output to stdout. (no newlines)
util.log(string); // Output with timestamp on stdout.
util.inspect(object, [opts]); // Return a string representation of object, which is useful for debugging. (options: showHidden, depth, colors, customInspect)
util.isArray(object); // Returns true if the given "object" is an Array. false otherwise.
util.isRegExp(object); // Returns true if the given "object" is a RegExp. false otherwise.
util.isDate(object); // Returns true if the given "object" is a Date. false otherwise.
util.isError(object); // Returns true if the given "object" is an Error. false otherwise.
util.promisify(fn) // Takes a function whose last argument is a callback and returns a version that returns promises.
util.inherits(constructor, superConstructor); // Inherit the prototype methods from one constructor into another.
/* *******************************************************************************************
* EVENTS
* http://nodejs.org/api/events.html
* ******************************************************************************************* */
// All objects which emit events are instances of events.EventEmitter. You can access this module by doing: require("events");
// To access the EventEmitter class, require('events').EventEmitter.
// All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when a listener is removed.
emitter.addListener(event, listener); // Adds a listener to the end of the listeners array for the specified event.
emitter.on(event, listener); // Same as emitter.addListener().
emitter.once(event, listener); // Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.
emitter.removeListener(event, listener); // Remove a listener from the listener array for the specified event.
emitter.removeAllListeners([event]); // Removes all listeners, or those of the specified event.
emitter.setMaxListeners(n); // By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.
emitter.listeners(event); // Returns an array of listeners for the specified event.
emitter.emit(event, [arg1], [arg2], [...]); // Execute each of the listeners in order with the supplied arguments. Returns true if event had listeners, false otherwise.
EventEmitter.listenerCount(emitter, event); // Return the number of listeners for a given event.
/* *******************************************************************************************
* STREAM
* http://nodejs.org/api/stream.html
* ******************************************************************************************* */
// A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout.
// Streams are readable, writable, or both. All streams are instances of EventEmitter.
// The Readable stream interface is the abstraction for a source of data that you are reading from.
// In other words, data comes out of a Readable stream.
// A Readable stream will not start emitting data until you indicate that you are ready to receive it.
// Examples of readable streams include: http responses on the client, http requests on the server, fs read streams
// zlib streams, crypto streams, tcp sockets, child process stdout and stderr, process.stdin.
var readable = getReadableStreamSomehow();
readable.on('readable', function() {}); // When a chunk of data can be read from the stream, it will emit a 'readable' event.
readable.on('data', function(chunk) {}); // If you attach a data event listener, then it will switch the stream into flowing mode, and data will be passed to your handler as soon as it is available.
readable.on('end', function() {}); // This event fires when there will be no more data to read.
readable.on('close', function() {}); // Emitted when the underlying resource (for example, the backing file descriptor) has been closed. Not all streams will emit this.
readable.on('error', function() {}); // Emitted if there was an error receiving data.
// The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
// This method should only be called in non-flowing mode. In flowing-mode, this method is called automatically until the internal buffer is drained.
readable.read([size]);
readable.setEncoding(encoding); // Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
readable.resume(); // This method will cause the readable stream to resume emitting data events.
readable.pause(); // This method will cause a stream in flowing-mode to stop emitting data events.
readable.pipe(destination, [options]); // This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
readable.unpipe([destination]); // This method will remove the hooks set up for a previous pipe() call. If the destination is not specified, then all pipes are removed.
readable.unshift(chunk); // This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
// The Writable stream interface is an abstraction for a destination that you are writing data to.
// Examples of writable streams include: http requests on the client, http responses on the server, fs write streams,
// zlib streams, crypto streams, tcp sockets, child process stdin, process.stdout, process.stderr.
var writer = getWritableStreamSomehow();
writable.write(chunk, [encoding], [callback]); // This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.
writer.once('drain', write); // If a writable.write(chunk) call returns false, then the drain event will indicate when it is appropriate to begin writing more data to the stream.
writable.end([chunk], [encoding], [callback]); // Call this method when no more data will be written to the stream.
writer.on('finish', function() {}); // When the end() method has been called, and all data has been flushed to the underlying system, this event is emitted.
writer.on('pipe', function(src) {}); // This is emitted whenever the pipe() method is called on a readable stream, adding this writable to its set of destinations.
writer.on('unpipe', function(src) {}); // This is emitted whenever the unpipe() method is called on a readable stream, removing this writable from its set of destinations.
writer.on('error', function(src) {}); // Emitted if there was an error when writing or piping data.
// Duplex streams are streams that implement both the Readable and Writable interfaces. See above for usage.
// Examples of Duplex streams include: tcp sockets, zlib streams, crypto streams.
// Transform streams are Duplex streams where the output is in some way computed from the input. They implement both the Readable and Writable interfaces. See above for usage.
// Examples of Transform streams include: zlib streams, crypto streams.
/* *******************************************************************************************
* FILE SYSTEM
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
// To use this module do require('fs').
// All the methods have asynchronous and synchronous forms.
fs.rename(oldPath, newPath, callback); // Asynchronous rename. No arguments other than a possible exception are given to the completion callback.Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.renameSync(oldPath, newPath); // Synchronous rename.
fs.ftruncate(fd, len, callback); // Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.ftruncateSync(fd, len); // Synchronous ftruncate.
fs.truncate(path, len, callback); // Asynchronous truncate. No arguments other than a possible exception are given to the completion callback.
fs.truncateSync(path, len); // Synchronous truncate.
fs.chown(path, uid, gid, callback); // Asynchronous chown. No arguments other than a possible exception are given to the completion callback.
fs.chownSync(path, uid, gid); // Synchronous chown.
fs.fchown(fd, uid, gid, callback); // Asynchronous fchown. No arguments other than a possible exception are given to the completion callback.
fs.fchownSync(fd, uid, gid); // Synchronous fchown.
fs.lchown(path, uid, gid, callback); // Asynchronous lchown. No arguments other than a possible exception are given to the completion callback.
fs.lchownSync(path, uid, gid); // Synchronous lchown.
fs.chmod(path, mode, callback); // Asynchronous chmod. No arguments other than a possible exception are given to the completion callback.
fs.chmodSync(path, mode); // Synchronous chmod.
fs.fchmod(fd, mode, callback); // Asynchronous fchmod. No arguments other than a possible exception are given to the completion callback.
fs.fchmodSync(fd, mode); // Synchronous fchmod.
fs.lchmod(path, mode, callback); // Asynchronous lchmod. No arguments other than a possible exception are given to the completion callback.
fs.lchmodSync(path, mode); // Synchronous lchmod.
fs.stat(path, callback); // Asynchronous stat. The callback gets two arguments (err, stats) where stats is a fs.Stats object.
fs.statSync(path); // Synchronous stat. Returns an instance of fs.Stats.
fs.lstat(path, callback); // Asynchronous lstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
fs.lstatSync(path); // Synchronous lstat. Returns an instance of fs.Stats.
fs.fstat(fd, callback); // Asynchronous fstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.
fs.fstatSync(fd); // Synchronous fstat. Returns an instance of fs.Stats.
fs.link(srcpath, dstpath, callback); // Asynchronous link. No arguments other than a possible exception are given to the completion callback.
fs.linkSync(srcpath, dstpath); // Synchronous link.
fs.symlink(srcpath, dstpath, [type], callback); // Asynchronous symlink. No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms)
fs.symlinkSync(srcpath, dstpath, [type]); // Synchronous symlink.
fs.readlink(path, callback); // Asynchronous readlink. The callback gets two arguments (err, linkString).
fs.readlinkSync(path); // Synchronous readlink. Returns the symbolic link's string value.
fs.unlink(path, callback); // Asynchronous unlink. No arguments other than a possible exception are given to the completion callback.
fs.unlinkSync(path); // Synchronous unlink.
fs.realpath(path, [cache], callback); // Asynchronous realpath. The callback gets two arguments (err, resolvedPath).
fs.realpathSync(path, [cache]); // Synchronous realpath. Returns the resolved path.
fs.rmdir(path, callback); // Asynchronous rmdir. No arguments other than a possible exception are given to the completion callback.
fs.rmdirSync(path); // Synchronous rmdir.
fs.mkdir(path, [mode], callback); // Asynchronous mkdir. No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.
fs.mkdirSync(path, [mode]); // Synchronous mkdir.
fs.readdir(path, callback); // Asynchronous readdir. Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
fs.readdirSync(path); // Synchronous readdir. Returns an array of filenames excluding '.' and '..'.
fs.close(fd, callback); // Asynchronous close. No arguments other than a possible exception are given to the completion callback.
fs.closeSync(fd); // Synchronous close.
fs.open(path, flags, [mode], callback); // Asynchronous file open.
fs.openSync(path, flags, [mode]); // Synchronous version of fs.open().
fs.utimes(path, atime, mtime, callback); // Change file timestamps of the file referenced by the supplied path.
fs.utimesSync(path, atime, mtime); // Synchronous version of fs.utimes().
fs.futimes(fd, atime, mtime, callback); // Change the file timestamps of a file referenced by the supplied file descriptor.
fs.futimesSync(fd, atime, mtime); // Synchronous version of fs.futimes().
fs.fsync(fd, callback); // Asynchronous fsync. No arguments other than a possible exception are given to the completion callback.
fs.fsyncSync(fd); // Synchronous fsync.
fs.write(fd, buffer, offset, length, position, callback); // Write buffer to the file specified by fd.
fs.writeSync(fd, buffer, offset, length, position); // Synchronous version of fs.write(). Returns the number of bytes written.
fs.read(fd, buffer, offset, length, position, callback); // Read data from the file specified by fd.
fs.readSync(fd, buffer, offset, length, position); // Synchronous version of fs.read. Returns the number of bytesRead.
fs.readFile(filename, [options], callback); // Asynchronously reads the entire contents of a file.
fs.readFileSync(filename, [options]); // Synchronous version of fs.readFile. Returns the contents of the filename. If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
fs.writeFile(filename, data, [options], callback); // Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.
fs.writeFileSync(filename, data, [options]); // The synchronous version of fs.writeFile.
fs.appendFile(filename, data, [options], callback); // Asynchronously append data to a file, creating the file if it not yet exists. data can be a string or a buffer.
fs.appendFileSync(filename, data, [options]); // The synchronous version of fs.appendFile.
fs.watch(filename, [options], [listener]); // Watch for changes on filename, where filename is either a file or a directory. The returned object is a fs.FSWatcher. The listener callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename is the name of the file which triggered the event.
fs.exists(path, callback); // Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false. (should not be used)
fs.existsSync(path); // Synchronous version of fs.exists. (should not be used)
// fs.Stats: objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous counterparts are of this type.
stats.isFile();
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() // (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
fs.createReadStream(path, [options]); // Returns a new ReadStream object.
fs.createWriteStream(path, [options]); // Returns a new WriteStream object.
/* *******************************************************************************************
* PATH
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
// Use require('path') to use this module.
// This module contains utilities for handling and transforming file paths.
// Almost all these methods perform only string transformations.
// The file system is not consulted to check whether paths are valid.
path.normalize(p); // Normalize a string path, taking care of '..' and '.' parts.
path.join([path1], [path2], [...]); // Join all arguments together and normalize the resulting path.
path.resolve([from ...], to); // Resolves 'to' to an absolute path.
path.relative(from, to); // Solve the relative path from 'from' to 'to'.
path.dirname(p); // Return the directory name of a path. Similar to the Unix dirname command.
path.basename(p, [ext]); // Return the last portion of a path. Similar to the Unix basename command.
path.extname(p); // Return the extension of the path, from the last '.' to end of string in the last portion of the path.
path.sep; // The platform-specific file separator. '\\' or '/'.
path.delimiter; // The platform-specific path delimiter, ';' or ':'.
/* *******************************************************************************************
* HTTP
* http://nodejs.org/api/http.html
* ******************************************************************************************* */
// To use the HTTP server and client one must require('http').
http.STATUS_CODES; // A collection of all the standard HTTP response status codes, and the short description of each.
http.request(options, [callback]); // This function allows one to transparently issue requests.
http.get(options, [callback]); // Set the method to GET and calls req.end() automatically.
server = http.createServer([requestListener]); // Returns a new web server object. The requestListener is a function which is automatically added to the 'request' event.
server.listen(port, [hostname], [backlog], [callback]); // Begin accepting connections on the specified port and hostname.
server.listen(path, [callback]); // Start a UNIX socket server listening for connections on the given path.
server.listen(handle, [callback]); // The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.
server.close([callback]); // Stops the server from accepting new connections.
server.setTimeout(msecs, callback); // Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.
server.maxHeadersCount; // Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.
server.timeout; // The number of milliseconds of inactivity before a socket is presumed to have timed out.
server.on('request', function (request, response) { }); // Emitted each time there is a request.
server.on('connection', function (socket) { }); // When a new TCP stream is established.
server.on('close', function () { }); // Emitted when the server closes.
server.on('checkContinue', function (request, response) { }); // Emitted each time a request with an http Expect: 100-continue is received.
server.on('connect', function (request, socket, head) { }); // Emitted each time a client requests a http CONNECT method.
server.on('upgrade', function (request, socket, head) { }); // Emitted each time a client requests a http upgrade.
server.on('clientError', function (exception, socket) { }); // If a client connection emits an 'error' event - it will forwarded here.
request.write(chunk, [encoding]); // Sends a chunk of the body.
request.end([data], [encoding]); // Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream.
request.abort(); // Aborts a request.
request.setTimeout(timeout, [callback]); // Once a socket is assigned to this request and is connected socket.setTimeout() will be called.
request.setNoDelay([noDelay]); // Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.
request.setSocketKeepAlive([enable], [initialDelay]); // Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.
request.on('response', function(response) { }); // Emitted when a response is received to this request. This event is emitted only once.
request.on('socket', function(socket) { }); // Emitted after a socket is assigned to this request.
request.on('connect', function(response, socket, head) { }); // Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed.
request.on('upgrade', function(response, socket, head) { }); // Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.
request.on('continue', function() { }); // Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.
response.write(chunk, [encoding]); // This sends a chunk of the response body. If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.
response.writeContinue(); // Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent.
response.writeHead(statusCode, [reasonPhrase], [headers]); // Sends a response header to the request.
response.setTimeout(msecs, callback); // Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.
response.setHeader(name, value); // Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.
response.getHeader(name); // Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive.
response.removeHeader(name); // Removes a header that's queued for implicit sending.
response.addTrailers(headers); // This method adds HTTP trailing headers (a header but at the end of the message) to the response.
response.end([data], [encoding]); // This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.
response.statusCode; // When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.
response.headersSent; // Boolean (read-only). True if headers were sent, false otherwise.
response.sendDate; // When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.
response.on('close', function () { }); // Indicates that the underlying connection was terminated before response.end() was called or able to flush.
response.on('finish', function() { }); // Emitted when the response has been sent.
message.httpVersion; // In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server.
message.headers; // The request/response headers object.
message.trailers; // The request/response trailers object. Only populated after the 'end' event.
message.method; // The request method as a string. Read only. Example: 'GET', 'DELETE'.
message.url; // Request URL string. This contains only the URL that is present in the actual HTTP request.
message.statusCode; // The 3-digit HTTP response status code. E.G. 404.
message.socket; // The net.Socket object associated with the connection.
message.setTimeout(msecs, callback); // Calls message.connection.setTimeout(msecs, callback).
/* *******************************************************************************************
* URL
* http://nodejs.org/api/url.html
* ******************************************************************************************* */
// This module has utilities for URL resolution and parsing. Call require('url') to use it.
url.parse(urlStr, [parseQueryString], [slashesDenoteHost]); // Take a URL string, and return an object.
url.format(urlObj); // Take a parsed URL object, and return a formatted URL string.
url.resolve(from, to); // Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
/* *******************************************************************************************
* QUERY STRING
* http://nodejs.org/api/querystring.html
* ******************************************************************************************* */
// This module provides utilities for dealing with query strings. Call require('querystring') to use it.
querystring.stringify(obj, [sep], [eq]); // Serialize an object to a query string. Optionally override the default separator ('&') and assignment ('=') characters.
querystring.parse(str, [sep], [eq], [options]); // Deserialize a query string to an object. Optionally override the default separator ('&') and assignment ('=') characters.
/* *******************************************************************************************
* ASSERT
* http://nodejs.org/api/assert.html
* ******************************************************************************************* */
// This module is used for writing unit tests for your applications, you can access it with require('assert').
assert.fail(actual, expected, message, operator); // Throws an exception that displays the values for actual and expected separated by the provided operator.
assert(value, message); assert.ok(value, [message]); // Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);
assert.equal(actual, expected, [message]); // Tests shallow, coercive equality with the equal comparison operator ( == ).
assert.notEqual(actual, expected, [message]); // Tests shallow, coercive non-equality with the not equal comparison operator ( != ).
assert.deepEqual(actual, expected, [message]); // Tests for deep equality.
assert.notDeepEqual(actual, expected, [message]); // Tests for any deep inequality.
assert.strictEqual(actual, expected, [message]); // Tests strict equality, as determined by the strict equality operator ( === )
assert.notStrictEqual(actual, expected, [message]); // Tests strict non-equality, as determined by the strict not equal operator ( !== )
assert.throws(block, [error], [message]); // Expects block to throw an error. error can be constructor, RegExp or validation function.
assert.doesNotThrow(block, [message]); // Expects block not to throw an error, see assert.throws for details.
assert.ifError(value); // Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.
/* *******************************************************************************************
* OS
* http://nodejs.org/api/os.html
* ******************************************************************************************* */
// Provides a few basic operating-system related utility functions.
// Use require('os') to access this module.
os.tmpdir(); // Returns the operating system's default directory for temp files.
os.endianness(); // Returns the endianness of the CPU. Possible values are "BE" or "LE".
os.hostname(); // Returns the hostname of the operating system.
os.type(); // Returns the operating system name.
os.platform(); // Returns the operating system platform.
os.arch(); // Returns the operating system CPU architecture.
os.release(); // Returns the operating system release.
os.uptime(); // Returns the system uptime in seconds.
os.loadavg(); // Returns an array containing the 1, 5, and 15 minute load averages.
os.totalmem(); // Returns the total amount of system memory in bytes.
os.freemem(); // Returns the amount of free system memory in bytes.
os.cpus(); // Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).
os.networkInterfaces(); // Get a list of network interfaces.
os.EOL; // A constant defining the appropriate End-of-line marker for the operating system.
/* *******************************************************************************************
* BUFFER
* http://nodejs.org/api/buffer.html
* ******************************************************************************************* */
// Buffer is used to dealing with binary data
// Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap
Buffer.from(size); // Allocates a new buffer of size octets.
Buffer.from(array); // Allocates a new buffer using an array of octets.
Buffer.from(str, [encoding]); // Allocates a new buffer containing the given str. encoding defaults to 'utf8'.
Buffer.isEncoding(encoding); // Returns true if the encoding is a valid encoding argument, or false otherwise.
Buffer.isBuffer(obj); // Tests if obj is a Buffer
Buffer.concat(list, [totalLength]); // Returns a buffer which is the result of concatenating all the buffers in the list together.
Buffer.byteLength(string, [encoding]); // Gives the actual byte length of a string.
buf.write(string, [offset], [length], [encoding]); // Writes string to the buffer at offset using the given encoding
buf.toString([encoding], [start], [end]); // Decodes and returns a string from buffer data encoded with encoding (defaults to 'utf8') beginning at start (defaults to 0) and ending at end (defaults to buffer.length).
buf.toJSON(); // Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays
buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]); // Does copy between buffers. The source and target regions can be overlapped
buf.slice([start], [end]); // Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.
buf.fill(value, [offset], [end]); // Fills the buffer with the specified value
buf[index]; // Get and set the octet at index
buf.length; // The size of the buffer in bytes, Note that this is not necessarily the size of the contents
buffer.INSPECT_MAX_BYTES; // How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.
+734
View File
@@ -0,0 +1,734 @@
/********************************************************************************************
* SAILS.JS CHEATSHEET
* REFERENCE: https://sailsjs.com/documentation/reference
* CONCEPTS: https://sailsjs.com/documentation/concepts
* APP STRUCTURE: https://sailsjs.com/documentation/anatomy
*
* 1. APPLICATION
* 2. BLUEPRINT API
* 3. COMMAND-LINE INTERFACE
* 4. CONFIGURATION
* 5. REQUEST
* 6. RESPONSE
* 7. WATERLINE ORM
* 8. WEBSOCKETS
********************************************************************************************/
/********************************************************************************************
* 1. APPLICATION
* https://sailsjs.com/documentation/reference/application
********************************************************************************************/
// A dictionary of all loaded Sails models, indexed by their identity.
sails.models
// A dictionary of all accessible helpers, including organics.
sails.helpers
// A dictionary of all loaded Sails hooks, indexed by their identity.
sails.hooks
// The full set of configuration options for the Sails instance
// It is assembled automatically when Sails loads your app
// merging together command-line arguments, environment variables, your .sailsrc file,
// and the configuration objects exported from any and all modules in your app's config/ directory.
sails.config
// The runtime values of your app's custom configuration settings.
sails.config.custom
// A set of convenience methods for low - level interaction with connected websockets.
sails.sockets
// Talk to Socket.io directly.
sails.io
// A regular expression designed for use in identifying URL paths that seem like they are probably
// for a static asset of some kind (e.g. image, stylesheet, favicon.ico, robots.txt, etc).
sails.LOOKS_LIKE_ASSET_RX
// Return a dictionary of Sails actions.
sails.getActions()
// Look up the first route pointing at the specified target (e.g. MeController.login)
// and return a dictionary containing its method and URL.
sails.getRouteFor(target)
// Look up the first route pointing at the specified target (e.g. entrance/view-login)
// and return its URL.
sails.getUrlFor(target)
// Lift a Sails app programmatically.
// This does exactly what you might be used to seeing by now when you run sails lift.
sailsApp.lift(configOverrides, function(err) {})
// Load a Sails app into memory-- but without lifting an HTTP server.
// Useful for writing tests, command - line scripts, and scheduled jobs.
sailsApp.load(configOverrides, function(err) {})
// Shut down a lifted Sails app and have it cease listening for / responding to any future requests.
sails.lower(callback)
// Register a new Sails action that can then be bound to a route.
sails.registerAction(action, name)
// Register a new action middleware function that will be applied to actions
// with the specified identities.
sails.registerActionMiddleware(actionMiddlewareFns, actionIdentities)
// Flush and reload all Sails actions.
sails.reloadActions()
// Compile a view into an HTML template.
sails.renderView(pathToView, templateData)
// Make a virtual request to a running Sails instance.
sails.request(request)
sails.request(url, body)
sails.request(url, callback)
sails.request(url, body, callback)
// Access a particular datastore, or the default datastore.
sails.getDatastore(datastoreName)
// Log a message or some data at the "debug" log level using Sails' built-in logger.
sails.log(message)
/********************************************************************************************
* 2. BLUEPRINT API
* https://sailsjs.com/documentation/reference/blueprint-api
********************************************************************************************/
// Find a list of records that match the specified criteria
// and (if possible) subscribe to each of them.
GET /:model
// Look up the record with the specified id from the database
// and (if possible) subscribe to the record to hear about any future changes.
GET /:model/:id
// Populate and return foreign record(s) for the given association of this record.
GET /:model/:id/:association
// Create a new record in your database
// and notify subscribed sockets that a newly record is created
POST /:model
// Update an existing record in the database
// and notify subscribed sockets that it has changed.
PATCH /:model/:id
// Replace all of the foreign records in one of this record's collections
// and notify subscribed sockets to the parent record.
PUT /:model/:id/:association
// Add a foreign record to one of this record's collections
// and notify subscribed sockets to the parent record.
PUT /:model/:id/:association/:fk
// Delete the record specified by id from the database forever
// and notify subscribed sockets that a record has been deleted
DELETE /:model/:id
// Remove a foreign record from one of this record's collections
// and notify subscribed sockets about this removed child
DELETE /:model/:id/:association/:fk
/********************************************************************************************
* 3. COMMAND-LINE INTERFACE
* https://sailsjs.com/documentation/reference/command-line-interface
********************************************************************************************/
// Lift your Node.js/Sails.js app in interactive mode, and enter the REPL.
// Useful for trying out Waterline queries, quickly managing your data, and checking
// out your project's runtime configuration.
sails console [--dontLift]
// Generate api/models/Foo.js, including attributes with the specified types if provided.
sails generate model
// Generate a standalone action.
sails generate action
// Generate a helper at api/helpers/foo.js.
sails generate helper
// Generate api/controllers/FooController.js, including actions with the specified names if provided.
sails generate controller
// Generate a project hook in api/hooks/foo/.
sails generate hook
// Generate a foo folder containing the files necessary for building a new generator.
sails generate generator
// Generate a custom response at api/responses/foo.js
sails generate response
// Generate a api/adapters/foo/ folder containing the files necessary for building a new adapter.
sails generate adapter
// Generate a sails.io.js file at the specified location, overwriting the default sails.io.js if applicable.
sails generate sails.io.js
// Generate api/models/Foo.js and api/controllers/FooController.js.
sails generate api
// Alias for sails new.
sails generate new
// Experimental. Adds the following files to your app:
// .gitignore, .jshintrc, .editorconfig, .npmignore, .travis.yml, .appveyor.yml
sails generate etc
// Attach the node debugger and lift the sails app; similar to running node--inspect app.js.
// You can then use a tool like the Chrome DevTools to interactively debug your apps.
sails inspect
// Run the Sails app in the current dir
// (if node_modules/sails exists, it will be used instead of the globally installed Sails)
sails lift [--prod] [--port <portNum>] [--verbose] [--silly]
// Create a new sails project.
sails new <yourAppName> [--no-frontend] [--minimal] [--without=package,package,package]
// Get the version of your computer's globally installed Sails command-line tool
// (i.e. the version you installed with npm install -g sails).
sails version
/********************************************************************************************
* 4. CONFIGURATION
* https://sailsjs.com/documentation/reference/configuration
********************************************************************************************/
// Determines which TCP port your Sails app will use to listen for incoming requests.
sails.config.port
// Declare the host name of your Sails app (By default, Sails will assume localhost).
sails.config.explicitHost
// The runtime “environment” of your Sails app (usually either development or production).
sails.config.environment
// A time limit, in milliseconds, imposed on all hooks in your app (default to 20000)
sails.config.hookTimeout
// Configure SSL settings for HTTPs and WSS
sails.config.ssl
// These configurable settings allow you to configure the blueprint API in Sails.
sails.config.blueprints
// Asynchronous bootstrap function that runs before your Sails app gets lifted (i.e. starts up).
// Can be used for setting up baseline data, running sanity checks on the status of your database...
sails.config.bootstrap
// Custom configuration for your app (one-off settings specific to your application)
// Things like the domain to use when sending emails, or 3rd party API keys for Stripe, Mailgun...
sails.config.custom
// Datastore configurations(or simply datastores) are like "saved settings" for your adapters.
sails.config.datastores
// Configuration for the global variables that Sails exposes by default.
sails.config.globals
// Configuration for your app's underlying HTTP server.
sails.config.http
// Configuration for Sails' built-in internationalization & localization features.
sails.config.i18n
// Configuration for the logger in your Sails app.
sails.config.log
// Your default project-wide model settings.
sails.config.models
// Dictionary that maps policies to an apps actions.
sails.config.policies
// Configuration for custom (aka "explicit") routes.
sails.config.routes
// Configuration for your app's security settings.
sails.config.security
// Configuration for Sails's built-in session support.
sails.config.session
// Provide transparent access to Socket.io
sails.config.sockets
// Configuration for your app's server-side views.
sails.config.views
/********************************************************************************************
* 5. REQUEST
* https://sailsjs.com/documentation/reference/request-req
********************************************************************************************/
// The moment that Sails started processing the request, as a Javascript Date object.
req._startTime
// An object containing text parameters from the parsed request body, defaulting to {}.
// If a request contains one or more file uploads, only the text parameters sent before
// the first file parameter will be available in req.body.
req.body
// An object containing all of the unsigned cookies from this request (req).
req.cookies
// A flag indicating the user-agent sending this request (req) wants "fresh" data
// (as indicated by the "if-none-match", "cache-control", and/or "if-modified-since" request headers.)
req.fresh
// An object containing pre-defined/custom header given in the current request.
req.headers
// Returns the hostname supplied in the host HTTP header.
// This header may be set either by the client or by the proxy.
req.hostname
// The IP address of the client who sent this request (req).
req.ip
// Contains the IP addresses in this request's "X-Forwarded-For" header
// as an array of the IP address strings.
req.ips
// A flag indicating whether or not this request (req) originated from a Socket.io connection.
req.isSocket
// The request method (aka "verb".)
// All requests to a Sails server have a "method", even via WebSockets.
req.method
// Dictionary (plain JavaScript object) of request-agnostic settings available in your app's actions.
req.options
// Retains the original request URL allowing you to rewrite req.url freely for internal routing purposes.
// In almost all cases, youll want to use req.url instead.
req.originalUrl
// An object containing parameter values parsed from the URL path.
req.params
// The URL pathname from the request URL string of the current request (req).
req.path
// The protocol used to send this request (req).
req.protocol
// A dictionary containing the parsed query-string, defaulting to {}.
req.query
// Indicates whether or not the request was sent over a secure TLS connection (i.e. https:// or wss://).
req.secure
// A dictionary containing all of the signed cookies from this request (req).
req.signedCookies
// If the current Request (req) originated from a connected Socket.io client,
// req.socket refers to the raw Socket.io socket instance.
req.socket
// An array of all the subdomains in this request's URL.
req.subdomains
// Like req.path, but also includes the query string suffix.
req.url
// A flag indicating whether the requesting client would prefer a JSON response
// (as opposed to some other format, like XML or HTML.)
req.wantsJSON
// A flag indicating whether the current request (req) appears to be an AJAX request.
req.xhr
// Return whether this request (req) advertises that it understands the specified media type.
req.accepts(mediaType)
// Return whether this request (req) advertises that it is able to handle any of the specified
// character set(s), and if so, which one.
req.acceptsCharsets(charset1, charset2, )
// Return whether this request (req) advertises that it understands any of the specified
// language(s), and if so, which one.
req.acceptsLanguages(language1, language2, )
// Returns the value of all parameters sent in the request, merged together into a single dictionary
req.allParams()
// Build and return a Skipper Upstream representing an incoming multipart file upload from the specified field.
req.file(field)
// Returns the value of the specified header field in this request (req). Note that header names are case-insensitive.
req.get(header)
// Returns true if this request's declared "Content-Type" matches the specified media/mime type.
req.is(type)
// Returns the value of the parameter with the specified name.
req.param(name[, defaultValue])
// Override the inferred locale for this request.
req.setLocale(override)
// Time out this request if a response is not sent within the specified number of milliseconds.
req.setTimeout(numMilliseconds)
/********************************************************************************************
* 6. RESPONSE
* https://sailsjs.com/documentation/reference/response-res
********************************************************************************************/
// Indicate to a web browser or other user agent that an outgoing file download sent
// in this response should be "Saved as..." rather than "Opened", and optionally specify the
// name for the newly downloaded file on disk.
res.attachment([filename])
// This method is used to send a 200 ("OK") response back down to the client.
res.ok(data)
// This method is used to send a 400 ("Bad Request") response back down
// to the client indicating that the request is invalid.
res.badRequest(data)
// This method is used to send a 403 ("Forbidden") response back down
// to the client indicating that the request is not allowed.
res.forbidden()
// This method is used to send a 404 ("Not Found") response using either res.json() or res.view().
res.notFound()
// This method is used to send a 500 ("Server Error") response back down to the client indicating
// that some kind of server error occurred (i.e. the error is not the requesting user agent's fault).
res.serverError(err)
res.serverError()
// Sets a cookie with name (name) and value (value) to be sent along with the response.
res.cookie(name, value[, options])
// Clears cookie (name) in the response.
res.clearCookie(name[, options])
// Returns the current value of the specified response header (header).
res.get(header)
// Sets specified response header (header) to the specified value (value).
res.set(header, value)
res.set(headers)
// Sends a JSON response composed of a stringified version of the specified data.
res.json([statusCode,] data)
// Send a JSON or JSONP response.
res.jsonp()
// Sets the "Location" response header to the specified URL expression(url).
res.location(url)
// Redirect the requesting user-agent to the given absolute or relative url.
res.redirect(url)
res.redirect(statusCode, url)
// Send a string response in a format other than JSON (XML, CSV, plain text, etc.
// If you want to send a dictionary or JSON, use res.json().
// If you want to send a custom status code, call req.status() first.
res.send([string])
// Set the status code of this response.
res.status(statusCode)
// Sets the "Content-Type" response header to the specified type.
res.type(type)
// Respond with an HTML page.
res.view(pathToView, locals)
res.view(pathToView)
res.view(locals)
res.view()
/********************************************************************************************
* 7. WATERLINE ORM
* https://sailsjs.com/documentation/reference/waterline-orm
********************************************************************************************/
// --> DATASTORE <--
// Return the default datastore
var datastore = sails.getDatastore()
// The generic, stateless, low-level driver for this datastore (if the adapter supports it).
datastore.driver
// The live connection manager for this datastore.
datastore.manager
// Lease a new connection from the datastore for use in running multiple queries
// on the same connection (i.e. so that the logic provided in during can reuse the db connection).
await datastore.leaseConnection(during)
// Execute a raw SQL query using this datastore.
await datastore.sendNativeQuery(sql, valuesToEscape)
// Fetch a preconfigured deferred object hooked up to the sails-mysql or sails-postgresql adapter
// (and consequently the appropriate driver)
await datastore.transaction(during)
// --> MODELS <--
// Add one or more existing child records to the specified collection.
MyModel.addToCollection(parentId, association).members(childIds)
// Remove one or more members from the specified collection
MyModel.removeFromCollection()
// Replace all members of the specified collection
MyModel.replaceCollection()
// Archive ("soft-delete") records that match the specified criteria,
// saving them as new records in the built-in Archive model, then destroying the originals.
MyModel.archive(criteria)
// Archive ("soft-delete") the record that matches the specified criteria,
// saving it (if it exists) as a new record in the built-in Archive model, then destroying the original.
MyModel.archiveOne(criteria);
// Get the total number of records matching the specified criteria.
MyModel.count(criteria)
// Get the aggregate mean of the specified attribute across all matching records.
MyModel.avg(numericAttrName, criteria)
// Get the aggregate sum of the specified attribute across all matching records.
MyModel.sum(numericAttrName, criteria)
// Find records in your database that match the given criteria.
MyModel.find(criteria)
// Attempt to find a particular record in your database that matches the given criteria.
MyModel.findOne(criteria)
// Find the record matching the specified criteria.
// If no such record exists, create one using the provided initial values.
MyModel.findOrCreate(criteria, initialValues)
// Create a record in the database.
MyModel.create(initialValues)
MyModel.create(initialValues).fetch() // Created record will be returned
// Create a set of records in the database.
MyModel.createEach(initialValues)
MyModel.createEach(initialValues).fetch() // Created records will be returned
// Update all records matching criteria.
MyModel.update(criteria, valuesToSet)
MyModel.update(criteria, valuesToSet).fetch() // Updated records will be returned
// Update the record that matches the given criteria, if one exists.
MyModel.updateOne(criteria).set(valuesToSet);
// Destroy records in your database that match the given criteria.
MyModel.destroy(criteria)
MyModel.destroy(criteria).fetch() // Destroyed record will be returned
// Destroy the record in your database that matches the given criteria, if one exists.
MyModel.destroyOne(criteria);
// Access the datastore for a particular model.
MyModel.getDatastore()
// Stream records from your database one at a time or in batches,
// without first having to buffer the entire result set in memory.
MyModel.stream(criteria)
// Verify that a value would be valid for a given attribute, then return it, loosely coerced.
MyModel.validate(attrName, value)
// --> QUERIES <--
// Set the maximum number of records to retrieve when executing a query instance.
query.limit(maximum)
// Indicate a number of records to skip before returning the results from executing a query instance.
query.skip(numRecordsToSkip)
// Set the order in which retrieved records should be returned when executing a query instance.
query.sort(sortClause)
// Specify a where clause for filtering a query.
query.where(whereClause)
// Tell Waterline (and the underlying database adapter) to send back records that were
// updated/destroyed/created when performing an .update(), .create(), .createEach() or .destroy()
// query. Otherwise, no data will be returned (or if you are using callbacks, the second argument
// to the .exec() callback will be undefined.)
// This is just a shortcut for .meta({fetch: true})
// Warning: This is not recommended for update/destroy queries that affect large numbers of records.
query.fetch()
// Modify a query instance so that, when executed, it will populate child records for the
// specified collection, optionally filtering by subcriteria. Populate may be called more than
// once on the same query, as long as each call is for a different association.
query.populate()
// Decrypt any auto-encrypted attributes in the records returned for this particular query.
// This is just a shortcut for .meta({decrypt: true})
query.decrypt()
// Execute a Waterline query instance.
query.exec(function (err, result) {})
// Begin executing a Waterline query instance and return a promise.
// This is an alternative to .exec().
query.toPromise()
// Capture and intercept the specified error, automatically modifying and re-throwing it,
// or specifying a new Error to be thrown instead. (Still throws.)
query.intercept(filter, handler)
query.intercept(handler)
// Provide additional options to Waterline when executing a query instance.
query.meta(options)
// Execute a Waterline query instance using promises.
// Whenever possible, it is recommended that you use await instead of calling this method.
// This is an alternative to .exec(). When combined with .catch(), it provides the same functionality.
query.then(callback)
// Execute a Waterline query instance using promises.
// Whenever possible, it is recommended that you use await instead of calling this method.
// This is an alternative to .exec(). When combined with .then(), it provides the same functionality.
query.catch(callback)
// Tolerate (swallow) the specified error, and return a new result value (or undefined) instead. (Don't throw.)
query.tolerate(filter, handler)
query.tolerate(filter)
query.tolerate(handler)
// Specify an existing database connection to use for this query.
query.usingConnection(connection)
/********************************************************************************************
* 8. WEB SOCKETS
* https://sailsjs.com/documentation/reference/web-sockets
********************************************************************************************/
// --> RESOURCEFUL PUBSUB (HIGHER LEVEL ABSTRACTION WHICH ARE USED BY SAILS BLUEPRINT API) <--
// Retrieve the name of the PubSub “room” for a given record.
MyModel.getRoomName(id)
// Broadcast an arbitrary message to socket clients subscribed to one or more of this model's records.
// Be sure and check req.isSocket === true before passing in req to refer to the requesting socket.
// If used, the provided req must be from a socket request, not just any old HTTP request.
// Is like sails.sockets.broadcast()
MyModel.publish(ids, data, req)
// Subscribe the requesting client socket to changes/deletions of one or more database records.
// Is like sails.sockets.join()
MyModel.subscribe(req, ids)
// Unsubscribe the requesting client socket from one or more database records.
// Is like sails.sockets.leave()
MyModel.unsubscribe(req, ids)
// --> SAILS.SOCKETS <--
// Subscribe all members of a room to one or more additional rooms.
// In a multi-server environment, the callback function (cb) will be executed when the
// .addRoomMembersToRooms() call completes on the current server. This does not guarantee that
// other servers in the cluster have already finished running the operation.
sails.sockets.addRoomMembersToRooms(sourceRoom, destRooms, cb)
// Broadcast a message to all sockets connected to the server (or any server in the cluster,
// if you have a multi-server deployment using Redis).
sails.sockets.blast(data)
sails.sockets.blast(eventName, data)
sails.sockets.blast(data, socketToOmit)
sails.sockets.blast(eventName, data, socketToOmit)
// Broadcast a message to all sockets in a room (or to a particular socket).
sails.sockets.broadcast(roomNames, data)
sails.sockets.broadcast(roomNames, eventName, data)
sails.sockets.broadcast(roomNames, data, socketToOmit)
sails.sockets.broadcast(roomNames, eventName, data, socketToOmit)
// Parse the socket ID from an incoming socket request (req).
sails.sockets.getId(req)
// Subscribe a socket to a room.
sails.sockets.join(socket, roomName)
sails.sockets.join(socket, roomName, cb)
// Unsubscribe a socket from a room.
sails.sockets.leave(socket, roomName)
sails.sockets.leave(socket, roomName, cb)
// Unsubscribe all members of a room (e.g. chatroom7) from that room and every other room
// they are currently subscribed to; except the automatic room associated with their socket ID.
sails.sockets.leaveAll(roomName, cb)
// Unsubscribe all members of a room from one or more other rooms.
sails.sockets.removeRoomMembersFromRooms(sourceRoom, destRooms, cb)
// --> SOCKET CLIENT <--
// Home of global configuration options for the sails.io.js library, as well as any sockets it creates.
io.sails
// Wait one cycle of the event loop after loading and then attempt to create a new SailsSocket
// and connect it to the URL specified by io.sails.url.
io.sails.autoConnect
// Sockets will automatically (and continuously) attempt to reconnect to the server
// if they become disconnected unexpectedly.
io.sails.reconnection
// Dictionary of headers to be sent by default with every request from this socket.
// Can be overridden via the headers option in .request().
io.sails.headers
// Set an environment for sails.io.js, which affects how much information is logged to the console.
// Valid values are development (full logs) and production (minimal logs).
io.sails.environment
// The URL that the socket is connected to, or will attempt to connect to.
io.sails.url
// The transports that the socket will attempt to connect using.
io.sails.transports
// Used for creating new socket connections manually.
io.sails.connect([url], [options])
// Unbind the specified event handler (opposite of .on()).
// To force a client socket to stop receiving broadcasted messages, do not use this method.
// Instead, unsubscribe the socket in your server-side code:
// In order to use .off(), you will need to store the handlerFn argument you passed in to .on() in a variable.
io.socket.off(eventIdentity, handlerFn)
// Start listening for socket events from Sails with the specified eventName.
// Will trigger the provided callback function when a matching event is received.
// This happens when the server broadcasts a message to this socket directly, or to a room of which it is a member.
io.socket.on(eventName, function (msg) { })
// Send a virtual DELETE request to a Sails server using Socket.io.
io.socket.delete(url, data, function (data, jwres) {})
// Send a socket request(virtual GET) to a Sails server using Socket.io.
io.socket.get(url, data, function (resData, jwres) {})
// Send a socket request (virtual PATCH) to a Sails server using Socket.io.
io.socket.patch(url, data, function (resData, jwres) {})
// Send a socket request (virtual POST) to a Sails server using Socket.io.
io.socket.post(url, data, function (resData, jwres) {})
// Send a socket request (virtual PUT) to a Sails server using Socket.io.
io.socket.put(url, data, function (resData, jwres) {})
// Send a virtual request to a Sails server using Socket.io.
io.socket.request(options, function (resData, jwres) {})
+1
View File
@@ -0,0 +1 @@
module.exports = {extends: ['@commitlint/config-conventional']}
+225
View File
@@ -0,0 +1,225 @@
# *****************************************************************************
# BASICS
# *****************************************************************************
# Connect MongoDB Shell
mongo # connects to mongodb://127.0.0.1:27017 by default
mongo --host <host> --port <port> -u <user> -p <pwd> # omit the password if you want a prompt
# Show All Databases
show dbs
# Show Current Database
db
# Create Or Switch Database
use <database_name>
# Drop Database
db.dropDatabase()
# Create Collection
db.createCollection('posts')
# Show Collections
show collections
# *****************************************************************************
# CRUD
# *****************************************************************************
# Insert Row
db.posts.insert({
title: 'Post One',
body: 'Body of post one',
category: 'News',
tags: ['news', 'events'],
user: {
name: 'John Doe',
status: 'author'
},
date: Date()
})
# Insert Multiple Rows
db.posts.insertMany([
{
title: 'Post Two',
body: 'Body of post two',
category: 'Technology',
date: Date()
},
{
title: 'Post Three',
body: 'Body of post three',
category: 'News',
date: Date()
},
{
title: 'Post Four',
body: 'Body of post three',
category: 'Entertainment',
date: Date()
}
])
# Get All Rows
db.posts.find()
# Get All Rows Formatted
db.posts.find().pretty()
# Find One Row
db.posts.findOne({ category: 'News' })
# Find Rows
db.posts.find({ category: 'News' })
# Find Specific Fields
db.posts.find({ title: 'Post One' }, {
title: 1,
author: 1
})
# Update Row
db.posts.update({ title: 'Post Two' },
{
title: 'Post Two',
body: 'New body for post 2',
date: Date()
},
{
upsert: true
})
# Update Specific Field
db.posts.update({ title: 'Post Two' },
{
$set: {
body: 'Body for post 2',
category: 'Technology'
}
})
# Delete Row
db.posts.remove({ title: 'Post Four' })
# *****************************************************************************
# OTHER FUNCTIONS
# *****************************************************************************
# Sort Rows
db.posts.find().sort({ title: 1 }).pretty() # asc
db.posts.find().sort({ title: -1 }).pretty() # desc
# Count Rows
db.posts.find().count()
db.posts.find({ category: 'news' }).count()
# Limit Rows
db.posts.find().limit(2).pretty()
# Chaining
db.posts.find().limit(2).sort({ title: 1 }).pretty()
# Foreach
db.posts.find().forEach(function(doc) {
print("Blog Post: " + doc.title)
})
# Increment Field (\$inc)
db.posts.update({ title: 'Post Two' },
{
$inc: {
likes: 5
}
})
# Rename Field
db.posts.update({ title: 'Post Two' },
{
$rename: {
likes: 'views'
}
})
# Sub-Documents
db.posts.update({ title: 'Post One' },
{
$set: {
comments: [
{
body: 'Comment One',
user: 'Mary Williams',
date: Date()
},
{
body: 'Comment Two',
user: 'Harry White',
date: Date()
}
]
}
})
# Find By Element in Array (\$elemMatch)
db.posts.find({
comments: {
$elemMatch: {
user: 'Mary Williams'
}
}
}
)
# Add Index
db.posts.createIndex({ title: 1 })
# Drop Index
db.posts.dropIndex("title_1")
# Hide/Unhide Indexes
db.posts.hideIndex("title_1")
db.posts.unhideIndex("title_1")
# Text Search
db.posts.find({
$text: {
$search: "\"Post O\""
}
})
# Greater & Less Than
db.posts.find({ views: { $gt: 2 } })
db.posts.find({ views: { $gte: 7 } })
db.posts.find({ views: { $lt: 7 } })
db.posts.find({ views: { $lte: 7 } })
+18
View File
@@ -0,0 +1,18 @@
# *****************************************************************************
# BASICS
# *****************************************************************************
mysqldump -h hostname -u username -p database_name -P port > file.sql # Export database
mysql -u username -p database_name < file.sql # Import database
SHOW PROCESSLIST; # Show you any queries that are currently running or in the queue to run
show status where `variable_name` = 'Threads_connected'; # Show all connected threads
show variables like 'max_connections'; # Show maximum number of allowed connections
SET GLOBAL max_connections = 150; ## Set new value for maximum connections (no restart needed but for permanent change update my.cnf)
GRANT ALL PRIVILEGES ON prospectwith.* TO 'power'@'localhost' WITH GRANT OPTION; # Grant all privileges on database
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; # Create user
mysql -u root -pmypassword -e "MY SQL QUERY" &>> query.log & disown # Run SQL query in the background
+156
View File
@@ -0,0 +1,156 @@
# *****************************************************************************
# BASICS
# *****************************************************************************
redis-server /path/redis.conf # start redis with the related configuration file
redis-cli # opens a redis prompt
sudo systemctl restart redis.service # Restart Redis
sudo systemctl status redis # Check Redis status
# *****************************************************************************
# STRINGS
# *****************************************************************************
APPEND key value # append a value to a key
BITCOUNT key [start end] # count set bits in a string
SET key value # set value in key
SETNX key value # set if not exist value in key
SETRANGE key offset value # overwrite part of a string at key starting at the specified offset
STRLEN key # get the length of the value stored in a key
MSET key value [key value ...] # set multiple keys to multiple values
MSETNX key value [key value ...] # set multiple keys to multiple values, only if none of the keys exist
GET key # get value in key
GETRANGE key start end # get substring of stored value from start to end offsets (both inclusive)
MGET key [key ...] # get the values of all the given keys
INCR key # increment value in key
INCRBY key increment # increment the integer value of a key by the given amount
INCRBYFLOAT key increment # increment the float value of a key by the given amount
DECR key # decrement the integer value of key by one
DECRBY key decrement # decrement the integer value of a key by the given number
DEL key # delete key
EXPIRE key 120 # key will be deleted in 120 seconds
TTL key # returns the number of seconds until a key is deleted
# *****************************************************************************
# LISTS
# A list is a series of ordered values
# *****************************************************************************
RPUSH key value [value ...] # put the new value at the end of the list
RPUSHX key value # append a value at the end of the list, only if it exists
LPUSH key value [value ...] # put the new value at the start of the list
LPUSHX key value # append a value at the start of the list, only if it exists
LRANGE key start stop # give a subset of the list
LINDEX key index # get an element from a list by its index
LINSERT key BEFORE|AFTER pivot value # insert an element before or after another element in a list
LLEN key # return the current length of the list
LPOP key # remove the first element from the list and returns it
LSET key index value # set the value of an element in a list by its index
LREM key number_of_occurrences value # delete occurrences of value if the list stored in key
LTRIM key start stop # trim a list to the specified range
RPOP key # remove the last element from the list and returns it
RPOPLPUSH source destination # remove the last element in a list, prepend it to another list and return it
BLPOP key [key ...] timeout # remove and get the first element in a list, or block until one is available
BRPOP key [key ...] timeout # remove and get the last element in a list, or block until one is available
# *****************************************************************************
# SETS
# A set is similar to a list, except it does not have a specific order
# and each element may only appear once.
# *****************************************************************************
SADD key member [member ...] # add the given value to the set
SCARD key # get the number of members in a set
SREM key member [member ...] # remove the given value from the set
SISMEMBER myset value # test if the given value is in the set.
SMEMBERS myset # return a list of all the members of this set
SUNION key [key ...] # combine two or more sets and returns the list of all elements
SINTER key [key ...] # intersect multiple sets
SMOVE source destination member # move a member from one set to another
SPOP key [count] # remove and return one or multiple random members from a set
# *****************************************************************************
# SORTED SETS
# A sorted set is similar to a regular set, but now each value has an associated score.
# This score is used to sort the elements in the set.
# *****************************************************************************
ZADD key [NX|XX] [CH] [INCR] score member [score member ...] # add one or more members to a sorted set, or update its score if it already exists
ZCARD key # get the number of members in a sorted set
ZCOUNT key min max # count the members in a sorted set with scores within the given values
ZINCRBY key increment member # increment the score of a member in a sorted set
ZRANGE key start stop [WITHSCORES] # returns a subset of the sorted set
ZRANK key member # determine the index of a member in a sorted set
ZREM key member [member ...]  # remove one or more members from a sorted set
ZREMRANGEBYRANK key start stop # remove all members in a sorted set within the given indexes
ZREMRANGEBYSCORE key min max # remove all members in a sorted set, by index, with scores ordered from high to low
ZSCORE key member # get the score associated with the given mmeber in a sorted set
ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count] # return a range of members in a sorted set, by score
# *****************************************************************************
# HASHES
# Hashes are maps between string fields and string values,
# so they are the perfect data type to represent objects.
# *****************************************************************************
HGET key field # get the value of a hash field
HGETALL key # get all the fields and values in a hash
HSET key field value # set the string value of a hash field
HSETNX key field value # set the string value of a hash field, only if the field does not exists
HMSET key field value [field value ...] # set multiple fields at once
HINCRBY key field increment # increment value in hash by X
HDEL key field [field ...] # delete one or more hash fields
HEXISTS key field # determine if a hash field exists
HKEYS key # get all the fields in a hash
HLEN key # get the number of fields in a hash
HSTRLEN key field # get the length of the value of a hash field
HVALS key # get all the values in a hash
# *****************************************************************************
# HYPERLOGLOG
# HyperLogLog uses randomization in order to provide an approximation of the number
# of unique elements in a set using just a constant, and small, amount of memory
# *****************************************************************************
PFADD key element [element ...] # add the specified elements to the specified HyperLogLog
PFCOUNT key [key ...] # return the approximated cardinality of the set(s) observed by the HyperLogLog at key's)
PFMERGE destkey sourcekey [sourcekey ...] # merge N HyperLogLogs into a single one
# *****************************************************************************
# PUBLICATION & SUBSCRIPTION
# *****************************************************************************
PSUBSCRIBE pattern [pattern ...] # listen for messages published to channels matching the given patterns
PUBSUB subcommand [argument [argument ...]]  # inspect the state of the Pub/Sub subsystem
PUBLISH channel message # post a message to a channel
PUNSUBSCRIBE [pattern [pattern ...]]  # stop listening for messages posted to channels matching the given patterns
SUBSCRIBE channel [channel ...]  # listen for messages published to the given channels
UNSUBSCRIBE [channel [channel ...]] # stop listening for messages posted to the given channels
# *****************************************************************************
# OTHER COMMANDS
# *****************************************************************************
KEYS pattern # find all keys matching the given pattern
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+443
View File
@@ -0,0 +1,443 @@
/* *******************************************************************************************
* ANGULAR (2+) CHEATSHEET
* BASED ON https://angular.io/guide/cheatsheet
* DOCUMENTATION: https://angular.io/docs
* STYLE GUIDE: https://angular.io/guide/styleguide
* ******************************************************************************************* */
```
npm install --save @angular/cli // install command line interface (CLI) for Angular apps
ng serve // serve the app
ng build // build the release
```
/* *******************************************************************************************
* BOOSTRAPPING
* https://angular.io/guide/bootstrapping
* ******************************************************************************************* */
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
// Bootstraps the app, using the root component from the specified NgModule.
platformBrowserDynamic().bootstrapModule(AppModule);
/* *******************************************************************************************
* NG MODULES
* https://angular.io/guide/ngmodules
* ******************************************************************************************* */
import { NgModule } from '@angular/core';
@NgModule({
declarations: ...,
imports: ...,
exports: ...,
providers: ...,
bootstrap: ...
})
// Defines a module that contains components, directives, pipes, and providers.
class MyModule {}
// List of components, directives, and pipes that belong to this module.
declarations: [MyRedComponent, MyBlueComponent, MyDatePipe]
// List of modules to import into this module. Everything from the imported modules is available
// to declarations of this module.
imports: [BrowserModule, SomeOtherModule]
// List of components, directives, and pipes visible to modules that import this module.
exports: [MyRedComponent, MyDatePipe]
// List of dependency injection providers visible both to the contents of this module and to
// importers of this module.
providers: [MyService, { provide: ... }]
// List of components to bootstrap when this module is bootstrapped.
bootstrap: [MyAppComponent]
/* *******************************************************************************************
* TEMPLATE SYNTAX
* https://angular.io/guide/template-syntax
* ******************************************************************************************* */
// Binds property value to the result of expression firstName.
// <input [value]="firstName">
// Binds attribute role to the result of expression myAriaRole.
// <div [attr.role]="myAriaRole">
// Binds the presence of the CSS class extra-sparkle on the element to the truthiness of the
// expression isDelightful.
// <div [class.extra-sparkle]="isDelightful">
// Binds style property width to the result of expression mySize in pixels. Units are optional.
// <div [style.width.px]="mySize">
// Calls method readRainbow when a click event is triggered on this button element (or its
// children) and passes in the event object.
// <button (click)="readRainbow($event)">
// Binds a property to an interpolated string, for example, "Hello Seabiscuit".
// Equivalent to: <div [title]="'Hello ' + ponyName">
// <div title="Hello {{ponyName}}">
// Binds text content to an interpolated string, for example, "Hello Seabiscuit".
// <p>Hello {{ponyName}}</p>
// Sets up two-way data binding. Equivalent to: <my-cmp [title]="name" (titleChange)="name=$event">
// <my-cmp [(title)]="name">
// Creates a local variable movieplayer that provides access to the video element instance in
// data-binding and event-binding expressions in the current template.
// <video #movieplayer ...>
// <button (click)="movieplayer.play()">
// </video>
// The * symbol turns the current element into an embedded template.
// Equivalent to: <ng-template [myUnless]="myExpression"><p>...</p></ng-template>
// <p *myUnless="myExpression">...</p>
// Transforms the current value of expression cardNumber via the pipe called myCardNumberFormatter.
// <p>Card No.: {{cardNumber | myCardNumberFormatter}}</p>
// The safe navigation operator (?) means that the employer field is optional and if undefined,
// the rest of the expression should be ignored.
// <p>Employer: {{employer?.companyName}}</p>
// An SVG snippet template needs an svg: prefix on its root element to disambiguate the SVG
// element from an HTML component.
// <svg:rect x="0" y="0" width="100" height="100"/>
// An <svg> root element is detected as an SVG element automatically, without the prefix.
// <svg>
// <rect x="0" y="0" width="100" height="100"/>
// </svg>
/* *******************************************************************************************
* BUILT-IN DIRECTIVES
* https://angular.io/guide/attribute-directives
* ******************************************************************************************* */
import { CommonModule } from '@angular/common';
// Removes or recreates a portion of the DOM tree based on the showSection expression.
// <section *ngIf="showSection">
// Turns the li element and its contents into a template, and uses that to instantiate a view for
// each item in list.
// <li *ngFor="let item of list">
// Conditionally swaps the contents of the div by selecting one of the embedded templates based on
// the current value of conditionExpression.
// <div [ngSwitch]="conditionExpression">
// <ng-template [ngSwitchCase]="case1Exp">...</ng-template>
// <ng-template ngSwitchCase="case2LiteralString">...</ng-template>
// <ng-template ngSwitchDefault>...</ng-template>
// </div>
// Binds the presence of CSS classes on the element to the truthiness of the associated map
// values. The right-hand expression should return {class-name: true/false} map.
// <div [ngClass]="{'active': isActive, 'disabled': isDisabled}">
// Allows you to assign styles to an HTML element using CSS. You can use CSS directly, as in the
// first example, or you can call a method from the component.
// <div [ngStyle]="{'property': 'value'}">
// <div [ngStyle]="dynamicStyles()">
/* *******************************************************************************************
* FORMS
* https://angular.io/guide/forms
* ******************************************************************************************* */
import { FormsModule } from '@angular/forms';
// Provides two-way data-binding, parsing, and validation for form controls.
// <input [(ngModel)]="userName">
/* *******************************************************************************************
* CLASS DECORATORS
* ******************************************************************************************* */
import { Directive, ... } from '@angular/core';
// Declares that a class is a component and provides metadata about the component.
@Component({...})
class MyComponent() {}
// Declares that a class is a directive and provides metadata about the directive.
@Directive({...})
class MyDirective() {}
// Declares that a class is a pipe and provides metadata about the pipe.
@Pipe({...})
class MyPipe() {}
// Declares that a class can be injected into the constructor of another class
// by the dependency injector.
@Injectable()
class MyService() {}
/* *******************************************************************************************
* DIRECTIVE CONFIGURATION
* ******************************************************************************************* */
@Directive({ property1: value1, ... })
// Specifies a CSS selector that identifies this directive within a template. Supported selectors
// include element, [attribute], .class, and :not().
selector: '.cool-button:not(a)'
// Does not support parent-child relationship selectors.
// List of dependency injection providers for this directive and its children.
providers: [MyService, { provide: ... }]
/* *******************************************************************************************
* COMPONENT CONFIGURATION
* https://angular.io/api/core/Component
* ******************************************************************************************* */
@Component extends @Directive, so the @Directive configuration applies to components as well
// If set, the templateUrl and styleUrl are resolved relative to the component.
moduleId: module.id
// List of dependency injection providers scoped to this component's view.
viewProviders: [MyService, { provide: ... }]
// Inline template or external template URL of the component's view.
template: 'Hello {{name}}'
templateUrl: 'my-component.html'
// List of inline CSS styles or external stylesheet URLs for styling the components view.
styles: ['.primary {color: red}']
styleUrls: ['my-component.css']
/* *******************************************************************************************
* CLASS FIELD DECORATORS FOR DIRECTIVES AND COMPONENTS
* ******************************************************************************************* */
import { Input, ... } from '@angular/core';
// Declares an input property that you can update via property binding
// (example: <my-cmp [myProperty]="someExpression">).
@Input() myProperty;
// Declares an output property that fires events that you can subscribe to with an event binding
// (example: <my-cmp (myEvent)="doSomething()">).
@Output() myEvent = new EventEmitter();
// Binds a host element property (here, the CSS class valid) to a directive/component property
// (isValid).
@HostBinding('class.valid') isValid;
// Subscribes to a host element event (click) with a directive/component method (onClick),
// optionally passing an argument ($event).
@HostListener('click', ['$event']) onClick(e) {...}
// Binds the first result of the component content query (myPredicate) to a property
// (myChildComponent) of the class.
@ContentChild(myPredicate) myChildComponent;
// Binds the results of the component content query (myPredicate) to a property
// (myChildComponents) of the class.
@ContentChildren(myPredicate) myChildComponents;
// Binds the first result of the component view query (myPredicate) to a property
// (myChildComponent) of the class. Not available for directives.
@ViewChild(myPredicate) myChildComponent;
// Binds the results of the component view query (myPredicate) to a property (myChildComponents)
// of the class. Not available for directives.
@ViewChildren(myPredicate) myChildComponents;
/* *******************************************************************************************
* DIRECTIVE AND COMPONENT CHANGE DETECTION AND LIFECYCLE HOOKS
* ******************************************************************************************* */
// (implemented as class methods)
// Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious
// work here.
constructor(myService: MyService, ...) { ... }
// Called after every change to input properties and before processing content or child views.
ngOnChanges(changeRecord) { ... }
// Called after the constructor, initializing input properties, and the first call to ngOnChanges.
ngOnInit() { ... }
// Called every time that the input properties of a component or a directive are checked. Use it
// to extend change detection by performing a custom check.
ngDoCheck() { ... }
// Called after ngOnInit when the component's or directive's content has been initialized.
ngAfterContentInit() { ... }
// Called after every check of the component's or directive's content.
ngAfterContentChecked() { ... }
// Called after ngAfterContentInit when the component's views and child views / the view that a
// directive is in has been initialized.
ngAfterViewInit() { ... }
// Called after every check of the component's views and child views / the view that a directive
// is in.
ngAfterViewChecked() { ... }
// Called once, before the instance is destroyed.
ngOnDestroy() { ... }
/* *******************************************************************************************
* DEPENDENCY INJECTION CONFIGURATION
* https://angular.io/guide/dependency-injection
* ******************************************************************************************* */
// Sets or overrides the provider for MyService to the MyMockService class.
{ provide: MyService, useClass: MyMockService }
// Sets or overrides the provider for MyService to the myFactory factory function.
{ provide: MyService, useFactory: myFactory }
// Sets or overrides the provider for MyValue to the value 41.
{ provide: MyValue, useValue: 41 }
/* *******************************************************************************************
* ROUTING AND NAVIGATION
* https://angular.io/guide/router
* ******************************************************************************************* */
import { Routes, RouterModule, ... } from '@angular/router';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'path/:routeParam', component: MyComponent },
{ path: 'staticPath', component: ... },
{ path: '**', component: ... },
{ path: 'oldPath', redirectTo: '/staticPath' },
{ path: ..., component: ..., data: { message: 'Custom' } }
]);
// Configures routes for the application. Supports static, parameterized, redirect, and wildcard
// routes. Also supports custom route data and resolve.
const routing = RouterModule.forRoot(routes);
// Marks the location to load the component of the active route.
// <router-outlet></router-outlet>
// <router-outlet name="aux"></router-outlet>
// Creates a link to a different view based on a route instruction consisting of a route path,
// required and optional parameters, query parameters, and a fragment. To navigate to a root
// route, use the / prefix; for a child route, use the ./prefix; for a sibling or parent, use the
// ../ prefix.
// <a routerLink="/path">
// <a [routerLink]="[ '/path', routeParam ]">
// <a [routerLink]="[ '/path', { matrixParam: 'value' } ]">
// <a [routerLink]="[ '/path' ]" [queryParams]="{ page: 1 }">
// <a [routerLink]="[ '/path' ]" fragment="anchor">
// The provided classes are added to the element when the routerLink becomes the current active
// route.
// <a [routerLink]="[ '/path' ]" routerLinkActive="active">
class CanActivateGuard implements CanActivate {
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean { ... }
}
// An interface for defining a class that the router should call first to determine if it should
// activate this component. Should return a boolean or an Observable/Promise that resolves to a
// boolean.
{
path: ...,
canActivate: [CanActivateGuard]
}
class CanDeactivateGuard implements CanDeactivate<T> {
canDeactivate(
component: T,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean { ... }
}
// An interface for defining a class that the router should call first to determine if it should
// deactivate this component after a navigation. Should return a boolean or an Observable/Promise
// that resolves to a boolean.
{
path: ...,
canDeactivate: [CanDeactivateGuard]
}
class CanActivateChildGuard implements CanActivateChild {
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean { ... }
}
// An interface for defining a class that the router should call first to determine if it should
// activate the child route. Should return a boolean or an Observable/Promise that resolves to a
// boolean.
{
path: ...,
canActivateChild: [CanActivateGuard],
children: ...
}
class ResolveGuard implements Resolve<T> {
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any>|Promise<any>|any { ... }
}
// An interface for defining a class that the router should call first to resolve route data
// before rendering the route. Should return a value or an Observable/Promise that resolves to a
// value.
{
path: ...,
resolve: [ResolveGuard]
}
class CanLoadGuard implements CanLoad {
canLoad(
route: Route
): Observable<boolean>|Promise<boolean>|boolean { ... }
}
// An interface for defining a class that the router should call first to check if the lazy loaded
// module should be loaded. Should return a boolean or an Observable/Promise that resolves to a
// boolean.
{
path: ...,
canLoad: [CanLoadGuard],
loadChildren: ...
}
+434
View File
@@ -0,0 +1,434 @@
/* *******************************************************************************************
* ANGULARJS CHEATSHEET
* API DOCUMENTATION: https://docs.angularjs.org/api
* DEVELOPER GUIDE: https://docs.angularjs.org/guide
* ERROR REFERENCE: https://docs.angularjs.org/error
* ******************************************************************************************* */
/* *******************************************************************************************
* TIPS & TRICKS
* ******************************************************************************************* */
// You can retrieve a scope for any DOM element by using:
angular.element(aDomElement).scope()
// An object that contains information about the current AngularJS version.
// This object has the following properties: full, major, minor, dot, codeName
angular.version
/* *******************************************************************************************
* CSS CLASS USED BY ANGULAR
* ******************************************************************************************* */
// AngularJS applies this class to any element for which a new scope is defined.
ng-scope
// AngularJS applies this class to any element for which a new isolate scope is defined.
ng-isolate-scope
// AngularJS applies this class to any element that is attached to a data binding, via ng-bind or {{}} curly braces, for example.
ng-binding
// AngularJS applies this class to a form control widget element if that element's input does not pass validation.
ng-invalid, ng-valid
// AngularJS ngModel directive applies ng-pristine class to a new form control widget which did not have user interaction.
// Once the user interacts with the form control, the class is changed to ng-dirty.
ng-pristine, ng-dirty
// AngularJS ngModel directive applies ng-untouched class to a new form control widget which has not been blurred.
// Once the user blurs the form control, the class is changed to ng-touched.
ng-touched, ng-untouched
/* *******************************************************************************************
* NG MODULE > FUNCTIONS
* ******************************************************************************************* */
// Returns a function which calls function fn bound to self (self becomes the this for fn).
// You can supply optional args that are prebound to the function.
// This feature is also known as partial application, as distinguished from function currying.
angular.bind(self, fn, args)
// Use this function to manually start up AngularJS application.
angular.bootstrap(element, [modules], [config])
// Creates a deep copy of source, which should be an object or an array.
angular.copy(source, [destination])
// Wraps a raw DOM element or HTML string as a jQuery element.
angular.element(element)
// Determines if two objects or two values are equivalent.
// Supports value types, regular expressions, arrays and objects.
angular.equals(o1, o2)
// Configure several aspects of error handling in AngularJS if used as a setter or return the current configuration if used as a getter.
angular.errorHandlingConfig([config])
// Extends the destination object dst by copying own enumerable properties from the src object(s) to dst.
// You can specify multiple src objects.
angular.extend(dst, src)
// Invokes the iterator function once for each item in obj collection, which can be either an object or an array.
angular.forEach(obj, iterator, [context])
// Deserializes a JSON string.
angular.fromJson(json)
// A function that returns its first argument.
// This function is useful when writing code in the functional style.
angular.identity(value)
// Creates an injector object that can be used for retrieving services as well as for dependency injection.
angular.injector(modules, [strictDi])
// Determines if a reference is an Array.
angular.isArray(value)
// Determines if a value is a date.
angular.isDate(value)
// Determines if a reference is defined.
angular.isDefined(value)
// Determines if a reference is a DOM element (or wrapped jQuery element).
angular.isElement(value)
// Determines if a reference is a Function.
angular.isFunction(value)
// Determines if a reference is a Number.
angular.isNumber(value)
// Determines if a reference is an Object. Unlike typeof in JavaScript, nulls are not considered to be objects.
angular.isObject(value)
// Determines if a reference is a String.
angular.isString(value)
// Determines if a reference is undefined.
angular.isUndefined(value)
// The angular.module is a global place for creating, registering and retrieving AngularJS modules.
// All modules (AngularJS core or 3rd party) that should be available to an application must be registered using this mechanism.
// Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module
angular.module(name, [requires], [configFn])
// A function that performs no operations.
// This function can be useful when writing code in the functional style.
angular.noop()
// Use this function to reload the current application with debug information turned on.
// This takes precedence over a call to $compileProvider.debugInfoEnabled(false).
angular.reloadWithDebugInfo()
// Serializes input into a JSON-formatted string.
// Properties with leading $$ characters will be stripped since AngularJS uses this notation internally.
angular.toJson(obj, pretty)
/* *******************************************************************************************
* NG MODULE > DIRECTIVES
* ******************************************************************************************* */
// Use this directive to auto-bootstrap an AngularJS application.
// Only one AngularJS application can be auto-bootstrapped per HTML document.
// You can specify an AngularJS module to be used as the root module for the application.
'ng-app'
// The ngBind attribute tells AngularJS to replace the text content of the specified HTML element with
// the value of a given expression, and to update the text content when the value of that expression changes.
'ng-bind'
// Evaluates the expression and inserts the resulting HTML into the element in a secure way.
'ng-bind-html'
// The ngBindTemplate directive specifies that the element text content should be replaced with
// the interpolation of the template in the ngBindTemplate attribute.
'ng-bind-template'
// Specify custom behavior on blur event.
'ng-blur'
// Evaluate the given expression when the user changes the input.
'ng-change'
// Sets the checked attribute on the element, if the expression inside ngChecked is truthy.
'ng-checked'
// The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding
// an expression that represents all classes to be added.
'ng-class'
// The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in
// conjunction with ngRepeat and take effect only on odd (even) rows.
'ng-class-even'
// The ngClassOdd and ngClassEven directives work exactly as ngClass, except they work in
// conjunction with ngRepeat and take effect only on odd (even) rows.
'ng-class-odd'
// The ngClick directive allows you to specify custom behavior when an element is clicked.
'ng-click'
// The ngCloak directive is used to prevent the AngularJS html template from being briefly displayed
// by the browser in its raw (uncompiled) form while your application is loading.
'ng-cloak'
// The ngController directive attaches a controller class to the view.
'ng-controller'
// Specify custom behavior on copy event.
'ng-copy'
// Specify custom behavior on cut event.
'ng-cut'
// Allows you to specify custom behavior on a dblclick event.
'ng-dblclick'
// This directive sets the disabled attribute on the element (typically a form control, e.g. input, button, select etc.)
// if the expression inside ngDisabled evaluates to truthy.
'ng-disabled'
// Specify custom behavior on focus event.
'ng-focus'
// Nestable alias of form directive. HTML does not allow nesting of form elements.
// It is useful to nest forms, for example if the validity of a sub-group of controls needs to be determined.
'ng-form'
// Shows or hides the given HTML element based on the expression provided to the ngHide attribute.
'ng-hide'
// Executes the expression and replaces with the right href link
'ng-href'
// Removes or recreates a portion of the DOM tree based on an {expression}.
'ng-if'
// Fetches, compiles and includes an external HTML fragment.
'ng-include'
// Allows you to evaluate an expression in the current scope.
'ng-init'
// Force the angular.element library.
// This should be used to force either jqLite by leaving ng-jq blank or setting the name of the jquery variable under window (eg. jQuery).
'ng-jq'
// Specify custom behavior on keydown event.
'ng-keydown'
// Specify custom behavior on keypress event.
'ng-keypress'
// Specify custom behavior on keyup event.
'ng-keyup'
// Text input that converts between a delimited string and an array of strings.
'ng-list'
// Adds the maxlength validator to ngModel.
'ng-maxlength'
// Adds the minlength validator to ngModel.
'ng-minlength'
// The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController,
// which is created and exposed by this directive.
'ng-model'
// Modify the behaviour of ngModel directives within your application.
// You can specify an ngModelOptions directive on any element.
// All ngModel directives will use the options of their nearest ngModelOptions ancestor.
'ng-model-options'
// Allows you to specify custom behavior on mousedown event.
'ng-mousedown'
// Specify custom behavior on mouseenter event.
'ng-mouseenter'
// Specify custom behavior on mouseleave event.
'ng-mouseleave'
// Specify custom behavior on mousemove event.
'ng-mousemove'
// Specify custom behavior on mouseover event.
'ng-mouseover'
// Specify custom behavior on mouseup event.
'ng-mouseup'
// Tells AngularJS not to compile or bind the contents of the current DOM element,
// including directives on the element itself that have a lower priority than ngNonBindable.
'ng-non-bindable'
// Sets the open attribute on the element, if the expression inside ngOpen is truthy.
'ng-open'
// The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select>
// element using the array or object obtained by evaluating the ngOptions comprehension expression.
'ng-options'
// Specify custom behavior on paste event.
'ng-paste'
// ngPattern adds the pattern validator to ngModel.
// It is most often used for text-based input controls, but can also be applied to custom text-based controls.
'ng-pattern'
// Displays messages according to en-US localization rules.
'ng-pluralize'
// Sets the readonly attribute on the element, if the expression inside ngReadonly is truthy
'ng-readonly'
// Instantiates a template once per item from a collection
// Special properties are exposed on the local scope of each template instance, including:
// $index, $first, $middle, $last, $even, $odd
'ng-repeat'
// ngRequired adds the required validator to ngModel.
// It is most often used for input and select controls, but can also be applied to custom controls.
'ng-required'
// Sets the selected attribute on the element, if the expression inside ngSelected is truthy.
'ng-selected'
// Shows or hides the given HTML element based on the expression provided to the ngShow attribute.
'ng-show'
// Using AngularJS markup like {{hash}} in a src attribute doesn't work right:
// The browser will fetch from the URL with the literal text {{hash}} until AngularJS
// replaces the expression inside {{hash}}. The ngSrc directive solves this problem.
'ng-src'
// Using AngularJS markup like {{hash}} in a srcset attribute doesn't work right:
// The browser will fetch from the URL with the literal text {{hash}} until AngularJS
// replaces the expression inside {{hash}}. The ngSrcset directive solves this problem.
'ng-srcset'
// Allows you to set CSS style on an HTML element conditionally.
'ng-style'
// Enables binding AngularJS expressions to onsubmit events.
'ng-submit'
// Used to conditionally swap DOM structure on your template based on a scope expression.
'ng-switch'
// Marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
'ng-transclude'
// Binds the given expression to the value of the element.
// It is mainly used on input[radio] and option elements, so that when the element is selected,
// the ngModel of that element (or its select parent element) is set to the bound value.
'ng-value'
/* *******************************************************************************************
* NG MODULE > TYPE
* ******************************************************************************************* */
// A cache object used to store and retrieve data, primarily used by $templateRequest
// and the script directive to cache templates and other data.
$cacheFactory.Cache
// Don't forget the cache
// A shared object between directive compile / linking functions which contains normalized
// DOM element attributes. The values reflect current binding state {{ }}.
$compile.directive.Attributes
// Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with x- or data-)
// to its normalized, camelCase form.
$compile.directive.Attributes.$normalize(name)
// Adds the CSS class value specified by the classVal parameter to the element.
// If animations are enabled then an animation will be triggered for the class addition.
$compile.directive.Attributes.$addClass(classVal)
// Removes the CSS class value specified by the classVal parameter from the element.
// If animations are enabled then an animation will be triggered for the class removal.
$compile.directive.Attributes.$removeClass(classVal)
// Adds and removes the appropriate CSS class values to the element based on the difference
// between the new and old CSS class values (specified as newClasses and oldClasses).
$compile.directive.Attributes.$updateClass(newClasses, oldClasses)
// Observes an interpolated attribute.
$compile.directive.Attributes.$observe(key, fn)
// Set DOM element attribute value.
$compile.directive.Attributes.$set(name, value)
// A map of DOM element attribute names to the normalized name.
// This is needed to do reverse lookup from normalized name back to actual name.
$compile.directive.Attributes.$attr
// A root scope can be retrieved using the $rootScope key from the $injector.
$rootScope.Scope([providers], [instanceCache])
/* *******************************************************************************************
* NG MODULE > FILTERS
* ******************************************************************************************* */
// Formats a number as a currency (ie $1,234.56).
// When no currency symbol is provided, default symbol for current locale is used.
{{ currency_expression | currency : symbol : fractionSize}}
$filter('currency')(amount, symbol, fractionSize)
// Formats date to a string based on the requested format.
{{ date_expression | date : format : timezone}}
$filter('date')(date, format, timezone)
// Selects a subset of items from array and returns it as a new array.
{{ filter_expression | filter : expression : comparator : anyPropertyKey}}
$filter('filter')(array, expression, comparator, anyPropertyKey)
// Allows you to convert a JavaScript object into JSON string.
// This filter is mostly useful for debugging.
// When using the double curly notation the binding is automatically converted to JSON.
{{ json_expression | json : spacing}}
$filter('json')(object, spacing)
// Creates a new array or string containing only a specified number of elements.
// The elements are taken from either the beginning or the end of the source array,
// string or number, as specified by the value and sign (positive or negative) of limit.
// Other array-like objects are also supported (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc).
// If a number is used as input, it is converted to a string.
{{ limitTo_expression | limitTo : limit : begin}}
$filter('limitTo')(input, limit, begin)
// Converts string to lowercase.
{{ lowercase_expression | lowercase}}
$filter('lowercase')()
// Formats a number as text.
// If the input is null or undefined, it will just be returned.
// If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
// If the input is not a number an empty string is returned.
{{ number_expression | number : fractionSize}}
$filter('number')(number, fractionSize)
// Returns an array containing the items from the specified collection,
// ordered by a comparator function based on the values computed using the expression predicate.
{{ orderBy_expression | orderBy : expression : reverse : comparator}}
$filter('orderBy')(collection, expression, reverse, comparator)
// Converts string to uppercase.
{{ uppercase_expression | uppercase}}
$filter('uppercase')()
+683
View File
@@ -0,0 +1,683 @@
/****************************
* CSS3 CHEATSHEET - Beginner Friendly
* Learn more: https://web.dev/learn/css/
* Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS
* PDF for Better Readability: https://github.com/LeCoupa/awesome-cheatsheets/files/8880372/CSS_Cheatsheet.pdf
* Brief overview about CSS: http://jonkinney.com/assets/21/advanced_css.pdf
* (Advance) Know more about each topic in-depth: https://www.ciwcertified.com/resources/documents/sample-chapter/CCT02CDHTCSCK1405.PDF
*
*
*
* Table of contents
* -------------------
* 01 | Font
* 02 | Text
* 03 | Background
* 04 | Border
* 05 | Box Model
* 06 | Colors
* 07 | Template Layout
* 08 | Table
* 09 | Columns
* 10 | List & Markers
* 11 | Animations
* 12 | Transitions
* 13 | CSS Flexbox (Important)
* - Parent Properties (flex container)
* - Child Properties (flex items)
* 14 | CSS Grid (Useful in Complex Web Designs)
* - Parent Properties (Grid container)
* - Child Properties (Grid items)
* 15 | Media Queries
*
*
*
*****************************/
/***************************
------------ 01: Font -----------
There are many properties related to the font, such as the face, weight, style, etc. These
properties allow you to change the style or complete look of your text.
*******************************/
/** Body Selector which applies properties to whole body <body></body> */
body {
/* Font-Family */
font-family: "Segoe UI", Tahoma, sans-serif; /* You can declare multiple fonts. */
/*if first font doesn't exists other ones will be declared serial wise */
/* Font-Style */
font-style: italic;
/* Font-Variant */
font-variant: small-caps;
/* Font-Weight */
font-weight: bold;
/* Font-Size */
font-size: larger;
/* Font */
font: style variant weight size family;
}
/***************************
------------ 02: Text -----------
Text properties allow one to manipulate alignment, spacing, decoration, indentation, etc., in the
document.
*******************************/
/* Applies to all tags with class 'container' ex: <div class="container"></div> */
.container {
/* Text-Align */
text-align: justify;
/* Letter-Spacing */
letter-spacing: 0.15em;
/* Text-Decoration */
text-decoration: underline;
/* Word-Spacing */
word-spacing: 0.25em;
/* Text-Transform */
text-transform: uppercase;
/* Text-Indent */
text-indent: 0.5cm;
/* Line-Height */
line-height: normal;
}
/***************************
------------ 03: Background -----------
As the name suggests, these properties are related to background, i.e., you can change the color,
image, position, size, etc., of the document.
*******************************/
/* Applies to all tags with id 'wrapper' ex: <div id="wrapper"></div> */
#wrapper {
/* Background-Image */
background-image: url("Path");
/* Background-Position */
background-position: right top;
/* Background-Size */
background-size: cover;
/* Background-Repeat */
background-repeat: no-repeat;
/* Background-Attachment */
background-attachment: scroll;
/* Background-Color */
background-color: fuchsia;
/* Background */
background: color image repeat attachment position;
}
/***************************
------------ 04: Border -----------
Border properties are used to change the style, radius, color, etc., of buttons or other items of
the document.
*******************************/
/* You can also select multiple items */
div,
.container {
/* Border-Width */
border-width: 5px;
/* Border-Style */
border-style: solid;
/* Border-Color */
border-color: aqua;
/* Border-Radius */
border-radius: 15px;
/* Border */
border: width style color;
}
/***************************
------------ 05: Box Model -----------
In laymen's terms, the CSS box model is a container that wraps around every HTML element. It
consists of margins, borders, padding, and the actual content.
It is used to create the design and layout of web pages.
*******************************/
.wrapper {
/* Float */
float: none;
/* Clear */
clear: both;
/* Display */
display: block;
/* Height */
height: fit-content;
/* Width */
width: auto;
/* Margin */
margin: top right bottom left;
/* Padding */
padding: top right bottom left;
/* Overflow */
overflow: hidden;
/* Visibility */
visibility: visible;
/* z-index */
z-index: 1;
/* position */
position: static | relative | fixed | absolute | sticky;
}
/***************************
------------ 06: Colors -----------
With the help of the color property, one can give color to text, shape, or any other object.
*******************************/
p,
span,
.text {
/* Color - 1 */
color: cornsilk;
/* Color - 2 */
color: #fff8dc;
/* Color - 3 */
color: rgba(255, 248, 220, 1);
/* Color - 4 */
color: hsl(48, 100%, 93%);
/* Opacity */
opacity: 1;
}
/***************************
------------ 07: Template Layout -----------
Specifies the visual look of the content inside a template
*******************************/
/* '*' selects all elements on a page */
* {
/* Box-Align */
box-align: start;
/* Box-Direction */
box-direction: normal;
/* Box-Flex */
box-flex: normal;
/* Box-Flex-Group */
box-flex-group: 2;
/* Box-Orient */
box-orient: inline;
/* Box-Pack */
box-pack: justify;
/* Box-Sizing */
box-sizing: margin-box;
/* max-width */
max-width: 800px;
/* min-width */
min-width: 500px;
/* max-height */
max-height: 100px;
/* min-height */
min-height: 80px;
}
/***************************
------------ 08: Table -----------
Table properties are used to give style to the tables in the document. You can change many
things like border spacing, table layout, caption, etc.
*******************************/
table {
/* Border-Collapse */
border-collapse: separate;
/* Empty-Cells */
empty-cells: show;
/* Border-Spacing */
border-spacing: 2px;
/* Table-Layout */
table-layout: auto;
/* Caption-Side */
caption-side: bottom;
}
/***************************
------------ 09: Columns -----------
These properties are used explicitly with columns of the tables, and they are used to give the
table an incredible look.
*******************************/
/* Applies to <table class="nice-table"></table> */
/* Not <table></table> */
table.nice-table {
/* Column-Count */
column-count: 10;
/* Column-Gap */
column-gap: 5px;
/* Column-rule-width */
column-rule-width: medium;
/* Column-rule-style */
column-rule-style: dotted;
/* Column-rule-color */
column-rule-color: black;
/* Column-width */
column-width: 10px;
/* Column-span */
column-span: all;
}
/***************************
------ 10: List & Markers -------
List and marker properties are used to customize lists in the document.
*******************************/
li,
ul,
ol {
/* List-style-type */
list-style-type: square;
/* List-style-position */
list-style-position: 20px;
/* List-style-image */
list-style-image: url("image.gif");
/* Marker-offset */
marker-offset: auto;
}
/***************************
------------ 11: Animations -----------
CSS animations allow one to animate transitions or other media files on the web page.
*******************************/
svg,
.loader {
/* Animation-name */
animation-name: myanimation;
/* Animation-duration */
animation-duration: 10s;
/* Animation-timing-function */
animation-timing-function: ease;
/* Animation-delay */
animation-delay: 5ms;
/* Animation-iteration-count */
animation-iteration-count: 3;
/* Animation-direction */
animation-direction: normal;
/* Animation-play-state */
animation-play-state: running;
/* Animation-fill-mode */
animation-fill-mode: both;
}
/***************************
------------ 12: Transitions -----------
Transitions let you define the transition between two states of an element.
*******************************/
a,
button {
/* Transition-property */
transition-property: none;
/* Transition-duration */
transition-duration: 2s;
/* Transition-timing-function */
transition-timing-function: ease-in-out;
/* Transition-delay */
transition-delay: 20ms;
}
/***************************
------------ 13: CSS Flexbox (Important) -----------
Flexbox is a layout of CSS that lets you format HTML easily. Flexbox makes it simple to align
items vertically and horizontally using rows and columns. Items will "flex" to different sizes to fill
the space. And overall, it makes the responsive design more manageable.
*******************************/
/* ---------------------- Parent Properties (flex container) ------------ */
section,
div#wrapper {
/* display */
display: flex;
/* flex-direction */
flex-direction: row | row-reverse | column | column-reverse;
/* flex-wrap */
flex-wrap: nowrap | wrap | wrap-reverse;
/* flex-flow */
flex-flow: column wrap;
/* justify-content */
justify-content: flex-start | flex-end | center | space-between | space-around;
/* align-items */
align-items: stretch | flex-start | flex-end | center | baseline;
/* align-content */
align-content: flex-start | flex-end | center | space-between | space-around;
}
/* ---------------------- Child Properties (flex items) ------------ */
p,
span,
h1,
h2,
h3,
h4,
h5,
h6,
a {
/* order */
order: 5; /* default is 0 */
/* flex-grow */
flex-grow: 4; /* default 0 */
/* flex-shrink */
flex-shrink: 3; /* default 1 */
/* flex-basis */
flex-basis: | auto; /* default auto */
/* flex shorthand */
flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
/* align-self */
align-self: auto | flex-start | flex-end | center | baseline | stretch;
}
/***************************
------------ 14: CSS Grid (Useful in Complex Web Designs) -----------
Grid layout is a 2-Dimensional grid system to CSS that creates complex responsive web design
layouts more easily and consistently across browsers.
*******************************/
/* ---------------------- Parent Properties (Grid container) ------------ */
section,
div#wrapper {
/* display */
display: grid | inline-grid;
/* grid-template-columns */
grid-template-columns: 12px 12px 12px;
/* grid-template-rows */
grid-template-rows: 8px auto 12px;
/* grid-template */
grid-template: none | <grid-template-rows> / <grid-template-columns>;
/* column-gap */
column-gap: <line-size>;
/* row-gap */
row-gap: <line-size>;
/* grid-column-gap */
grid-column-gap: <line-size>;
/* grid-row-gap */
grid-row-gap: <line-size>;
/* gap shorthand */
gap: <grid-row-gap> <grid-column-gap>;
/* grid-gap shorthand */
grid-gap: <grid-row-gap> <grid-column-gap>;
/* justify-items */
justify-items: start | end | center | stretch;
/* align-items */
align-items: start | end | center | stretch;
/* place-items */
place-items: center;
/* justify-content */
justify-content: start | end | center | stretch | space-around | space-between;
/* align-content */
align-content: start | end | center | stretch | space-around | space-between;
/* place-content */
place-content: <align-content> / <justify-content>;
/* grid-auto-columns */
grid-auto-columns: <track-size> ...;
/* grid-auto-rows */
grid-auto-rows: <track-size> ...;
/* grid-auto-flow */
grid-auto-flow: row | column | row dense | column dense;
}
/* ---------------------- Child Properties (Grid items) ------------ */
p,
span,
h1,
h2,
h3,
h4,
h5,
h6,
a {
/* grid-column-start */
grid-column-start: <number> | <name> | span <number> | span <name> | auto;
/* grid-column-end */
grid-column-end: <number> | <name> | span <number> | span <name> | auto;
/* grid-row-start */
grid-row-start: <number> | <name> | span <number> | span <name> | auto;
/* grid-row-end */
grid-row-end: <number> | <name> | span <number> | span <name> | auto;
/* grid-column shorthand */
grid-column: <start-line> / <end-line> | <start-line> / span <value>;
/* grid-row shorthand */
grid-row: <start-line> / <end-line> | <start-line> / span <value>;
/* grid-area */
grid-area: <name> | <row-start> / <column-start> / <row-end> / <column-end>;
/* justify-self */
justify-self: start | end | center | stretch;
/* align-self */
align-self: start | end | center | stretch;
/* place-self */
place-self: center;
}
/***************************
------------ 15: MEDIA QUERIES -----------
Using media queries are a popular technique for delivering a tailored style sheet to
desktops, laptops, tablets, and mobile phones (such as iPhone and Android phones).
|----------------------------------------------------------|
| Responsive Grid Media Queries - 1280, 1024, 768, 480 |
| 1280-1024 - desktop (default grid) |
| 1024-768 - tablet landscape |
| 768-480 - tablet |
| 480-less - phone landscape & smaller |
|----------------------------------------------------------|
*******************************/
@media all and (min-width: 1024px) and (max-width: 1280px) { }
@media all and (min-width: 768px) and (max-width: 1024px) { }
@media all and (min-width: 480px) and (max-width: 768px) { }
@media all and (max-width: 480px) { }
/* Small screens - MOBILE */
@media only screen { } /* Define mobile styles - Mobile First */
@media only screen and (max-width: 40em) { } /* max-width 640px, mobile-only styles, use when QAing mobile issues */
/* Medium screens - TABLET */
@media only screen and (min-width: 40.063em) { } /* min-width 641px, medium screens */
@media only screen and (min-width: 40.063em) and (max-width: 64em) { } /* min-width 641px and max-width 1024px, use when QAing tablet-only issues */
/* Large screens - DESKTOP */
@media only screen and (min-width: 64.063em) { } /* min-width 1025px, large screens */
@media only screen and (min-width: 64.063em) and (max-width: 90em) { } /* min-width 1024px and max-width 1440px, use when QAing large screen-only issues */
/* XLarge screens */
@media only screen and (min-width: 90.063em) { } /* min-width 1441px, xlarge screens */
@media only screen and (min-width: 90.063em) and (max-width: 120em) { } /* min-width 1441px and max-width 1920px, use when QAing xlarge screen-only issues */
/* XXLarge screens */
@media only screen and (min-width: 120.063em) { } /* min-width 1921px, xlarge screens */
/*------------------------------------------*/
/* Portrait */
@media screen and (orientation:portrait) { /* Portrait styles here */ }
/* Landscape */
@media screen and (orientation:landscape) { /* Landscape styles here */ }
/* CSS for iPhone, iPad, and Retina Displays */
/* Non-Retina */
@media screen and (-webkit-max-device-pixel-ratio: 1) {
}
/* Retina */
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
}
/* iPhone Portrait */
@media screen and (max-device-width: 480px) and (orientation:portrait) {
}
/* iPhone Landscape */
@media screen and (max-device-width: 480px) and (orientation:landscape) {
}
/* iPad Portrait */
@media screen and (min-device-width: 481px) and (orientation:portrait) {
}
/* iPad Landscape */
@media screen and (min-device-width: 481px) and (orientation:landscape) {
}
/* Make Sure you don't forgot to add */
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /> /* within <head> tag */
+743
View File
@@ -0,0 +1,743 @@
/*
* -----------------------
* Ember.js Cheatsheet
* -----------------------
*
* Docs: https://guides.emberjs.com/
* Quick start: https://guides.emberjs.com/current/getting-started/quick-start/
*
* Table of contents
* -------------------
* 01 | Installation
* 02 | Ember CLI
* 03 | Directory layout
* 04 | Routes
* 05 | Templates
* 06 | Components
* 07 | Models
* 08 | Services
* 09 | Testing
* 10 | Addons
* 11 | Configuration
* 12 | Community
*
*/
/*
* 01 | Installation
* --------------------------------------------------------------
* Getting started with Ember is easy. Ember projects are created
* and managed through our command line build tool Ember CLI.
*/
```
npm install -g ember-cli
ember new <application-name>
ember serve
```
/*
* 02 | Ember CLI
* --------------------------------------------------------------
* Ember CLI is the Ember.js command line utility that provides a
* fast Broccoli-powered asset pipeline, a strong conventional
* project structure, and a powerful addon system for extension.
*
* Among the principal features of Ember CLI are:
- Project/Addon creation: create new projects quickly without having to worry about project structure;
- Build pipeline: asset compilation, finger-printing and more out of the box;
- Generators: use the built-in generators and get files that follow the latest practices, and matching tests;
- Ember Addons: extend both your application and Ember CLI itself with community solutions. Also an excellent
way to easily integrate 3rd party libraries into your Ember app.
*/
Basic commands
Command | Aliases | Description
--------------------------------------------------
```
ember new | | Create new project with the provided name (ex. ember new <app-name>)
ember server | ember s | Starts development server (default port is 4200)
ember test | ember t | Run tests in CI mode
ember generate | ember g | Run generator
ember destroy | ember d | Remove code created by generator
ember help | ember h | Get more info on available cli command
ember install | ember i | Install given addon into project and save to package.json
ember | | List available cli commands
```
Useful commands
```
ember s --proxy <proxy-url>
ember s --port <port>
```
/*
* 03 | Directory Layout
* --------------------------------------------------------------
*
* Layout of the root folder */
app/
` This is where folders and files for models, components, routes, templates and styles are stored. The majority of your coding on an Ember project happens in this folder. `
config/
` The config directory contains the environment.js where you can configure settings for your app. `
node_modules/
` This directory is from npm. npm is the package manager for Node.js. Ember is built with Node and uses a variety of Node.js modules for operation. The package.json file maintains the list of current npm dependencies for the app. Any Ember CLI addons you install will also show up here. `
public/
` This directory contains assets such as images and fonts. `
vendor/
` This directory is where front-end dependencies (such as JavaScript or CSS) that are not managed by NPM go. `
tests/testem.js
` Automated tests for our app go in the tests folder, and Ember CLI's test runner testem is configured in testem.js. `
ember-cli-build.js
` This file describes how Ember CLI should build our app. `
package.json
` Packages listed in package.json are installed in the node_modules directory. `
/*
* Layout of the app directory */
adapters/
` Adapters with the convention adapter-name.js. `
components/
` Components with the convention component-name.js. Components must have a dash in their name. So blog-post is an acceptable name, but post is not. `
controllers/
` Controllers behave like a specialized type of Component that is rendered by the router when entering a Route. `
helpers/
` Helpers with the convention helper-name.js. Helpers must have a dash in their name. Remember that you must register your helpers by exporting makeBoundHelper or calling registerBoundHelper explicitly. `
models/
` Models with the convention model-name.js. `
routes/
` Routes with the convention route-name.js. Child routes are defined in sub-directories, parent/child.js. To provide a custom implementation for generated routes (equivalent to App.Route when using globals), use app/routes/basic.js. `
styles/
` Contains your stylesheets, whether SASS, LESS, Stylus, Compass, or plain CSS (though only one type is allowed, see Asset Compilation). These are all compiled into <app-name>.css. `
templates/
` Your HTMLBars templates. These are compiled to /dist/assets/<app-name>.js. The templates are named the same as their filename, minus the extension (i.e. templates/foo/bar.hbs -> foo/bar). `
serializers/
` Serializers for your models or adapter, where model-name.js or adapter-name.js. `
utils/
` Utility modules with the convention utility-name.js. `
router.js
` Your route configuration. The routes defined here correspond to routes in app/routes/. `
/*
* 03 | Routes
* --------------------------------------------------------------
*
* When your application starts, the router matches the current URL to the routes that you've defined.
* The routes, in turn, are responsible for displaying templates, loading data, and setting up application state.
*
* > ember g route <route-name>
*/
import Route from '@ember/routing/route';
export default Route.extend({
model() {
// Typically, the model hook should return an Ember Data record,
// but it can also return any promise object (Ember Data records are
// promises), or a plain JavaScript object or array. Ember will wait
// until the data finishes loading (until the promise is resolved)
// before rendering the template.
}
});
/*
* 04 | Templates
* --------------------------------------------------------------
*
* Ember uses the Handlebars templating library to power your app's user
* interface. Handlebars templates contain static HTML and dynamic
* content inside Handlebars expressions, which are invoked with
* double curly braces: {{}}.
*
* Templates are backed with a context. A context is an object from
* which Handlebars expressions read their properties. In Ember this
* is often a component. For templates rendered by a route (like application.hbs),
* the context is a controller.
*
* > ember g template <template-name>
*/
// Here's an basic exmpale of a template
```hbs
Hello, <strong>{{firstName}} {{lastName}}</strong>!
```
/*
* 05 | Components
* --------------------------------------------------------------
*
* Ember components are used to encapsulate markup and style into
* reusable content. Components consist of two parts: a JavaScript
* component file that defines behavior, and its accompanying Handlebars
* template that defines the markup for the component's UI.
*
* > ember g component <component-name>
*/
// app/components/<component-name>.js
import Component from '@ember/component';
export default Component.extend({
});
// app/templates/components/<component-name>.hbs
```hbs
{{yield}}
```
/*
* Actions
*
* Provide a means to communicate events and changes
*/
// app/components/rental-listing.js
import Component from '@ember/component';
export default Component.extend({
isWide: false,
actions: {
toggleImageSize() {
this.toggleProperty('isWide');
}
}
});
// Actions can be attached to DOM elements inside templates using the {{action}} helper
``` app/templates/components/rental-listing.hbs
<article class="listing">
<a {{action 'toggleImageSize'}} class="image {{if isWide "wide"}}">
<img src="http://www.fillmurray.com/200/300" alt="">
</a>
</article>
```
/*
* Component lifecycle
*
* As components are rendered, re-rendered and finally removed, Ember provides
* lifecycle hooks that allow you to run code at specific times in a component's life.
*/
On Initial Render
1 init
2 didReceiveAttrs
3 willRender
4 didInsertElement // Good place to integrate with 3rd party libraries
5 didRender
On Re-Render
1 didUpdateAttrs
2 didReceiveAttrs
3 willUpdate
4 willRender
5 didUpdate
6 didRender
On Component Destroy
1 willDestroyElement
2 willClearRender
2 didDestroyElement
/*
* Block params
*
* Components can have properties passed in, but they can also return
* output to be used in a block expression.
*/
// Here an entire blog post model is being passed to the component as a
// single component property. In turn the component is returning values using yield.
``` app/templates/index.hbs
{{blog-post post=model}}
```
``` app/templates/components/blog-post.hbs
{{yield post.title post.body post.author}}
```
// The block expression can then use block params to bind names to any yielded
// values for use in the block. This allows for template customization when using
// a component, where the markup is provided by the consuming template, but any
// event handling behavior implemented in the component is retained such as click() handlers.
``` app/templates/index.hbs
{{#blog-post post=model as |title body author|}}
<h2>{{title}}</h2>
<p class="author">by {{author}}</p>
<p class="post-body">{{body}}</p>
{{/blog-post}}
```
// The names are bound in the order that they are passed to yield in the component template.
/*
* 06 | Models
* --------------------------------------------------------------
*
* Models are objects that represent the underlying data that your application
* presents to the user. Different apps will have very different models,
* depending on what problems they're trying to solve.
*
* Ember Data, included by default when you create a new application,
* is a library that integrates tightly with Ember to make it easy to
* retrieve models from your server as JSON, save updates back to the server,
* and create new models in the browser.
*
* > ember g model <model-name>
*/
import DS from 'ember-data';
import { computed } from '@ember/object';
const { attr, Model } = DS;
export default Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date'),
// Computed properties
// These are effectively fuctions declared as properties. The function's result
// will recompute every time one of the provided 'dependent keys' changes.
fullName: computed('firstName', 'lastName', function() {
let firstName = this.get('firstName');
let lastName = this.get('lastName');
return `${firstName} ${lastName}`;
})
});
/*
* 07 | Services
* --------------------------------------------------------------
*
* A Service is an Ember object that lives for the duration of the application, and can
* be made available in different parts of your application. Services are useful for
* features that require shared state or persistent connections.
*
* Example uses of services might include:
*
* - User/session authentication.
* - Geolocation.
* - WebSockets.
* - Server-sent events or notifications.
* - Server-backed API calls that may not fit Ember Data.
* - Third-party APIs.
* - Logging.
*
* > ember g service <service-name>
*/
/*
* Defining services
*
* Like any Ember object, a service is initialized and can have properties and
* methods of its own. Below, the shopping cart service manages an items array
* that represents the items currently in the shopping cart.
*/
// app/services/shopping-cart.js
import Service from '@ember/service';
export default Service.extend({
items: null,
init() {
this._super(...arguments);
this.set('items', []);
},
remove(item) {
this.get('items').removeObject(item);
}
});
/*
* Accessing services
*
* To access a service, you can inject it in any object such as a component or another
* service using the `inject` function from the `@ember/service` module.
*/
// app/components/cart-contents.js
import Component from '@ember/component';
import { inject } from '@ember/service';
export default Component.extend({
shoppingCart: inject() // will load the service in file /app/services/shopping-cart.js
actions: {
remove(item) {
this.get('shoppingCart').remove(item);
}
}
});
// Once injected into a component, a service can also be used in the template.
// Note cart being used below to get data from the cart.
```hbs app/templates/components/cart-contents.hbs
<ul>
{{#each cart.items as |item|}}
<li>
{{item.name}}
<button {{action "remove" item}}>Remove</button>
</li>
{{/each}}
</ul>
```
/*
* 08 | Testing
* --------------------------------------------------------------
*
* Testing is a core part of the Ember framework and its development cycle.
*
* > ember g acceptance-test <test-name>
* > ember g integration-test <test-name>
* > ember g unit-test <test-name>
* > ember t --server
* > ember s && visit localhost:4200/tests
*/
/*
* Acceptance & application tests
*
* In these kinds of tests, we interact with the application in the same ways that a
* user would, such as filling out form fields and clicking buttons. Application
* tests ensure that the interactions within a project are basically functional, the
* core features of a project have not regressed, and the project's goals are being met.
*
* Some useful helpers from '@ember/test-helpers':
* - `click(selector)`
* Clicks an element and triggers any actions triggered by the element's click event and
* returns a promise that fulfills when all resulting async behavior is complete.
*
* - `fillIn(selector, value)`
* Fills in the selected input with the given value and returns a promise that
* fulfills when all resulting async behavior is complete. Works with <select> elements
* as well as <input> elements. Keep in mind that with <select> elements, value must be set
* to the value of the <option> tag, rather than its content (for example, true rather than "Yes").
*
* - `triggerKeyEvent(selector, type, keyCode)`
* Simulates a key event type, e.g. keypress, keydown, keyup with the desired keyCode on element found by the selector.
*
* - `triggerEvent(selector, type, options)`
* Triggers the given event, e.g. blur, dblclick on the element identified by the provided selector.
*
* - `visit(url)`
* Visits the given route and returns a promise that fulfills when all resulting async behavior is complete.
*
* - `currentURL()`
* Returns the current URL.
*
* - `find(selector, context)`
* Finds an element within the app's root element and within the context (optional). Scoping to the
* root element is especially useful to avoid conflicts with the test framework's reporter, and this
* is done by default if the context is not specified.
*
* - `findAll(selector)`
* Find all elements matched by the given selector. Equivalent to calling querySelectorAll() on the
* test root element. Returns an array of matched elements.
*
*/
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { visit, fillIn, click } from '@ember/test-helpers';
module('Acceptance | posts', function(hooks) {
// `setupApplicationTest` deals with application setup and teardown.
setupApplicationTest(hooks);
test('should add new post', async function(assert) {
await visit('/posts/new');
await fillIn('input.title', 'My new post');
await click('button.submit');
const title = this.element.querySelector('ul.posts li:first').textContent;
assert.equal(title, 'My new post');
});
});
/*
* Integration & rendering tests
*
* Rendering Tests are, as the name suggests, rendering components and helpers
* by verifying the correct behaviour when the component or helper interacts
* with the system in the same way that it will within the context of the application,
* including being rendered from a template and receiving Ember's lifecycle hooks.
*
* If we need to test the interactions between various parts of the application,
* such as behaviour between UI controls we can utilize Rendering Tests.
*/
// app/components/pretty-color.js
import Component from '@ember/component';
import { computed } from '@ember/object';
export default Component.extend({
attributeBindings: ['style'],
style: computed('name', function() {
const name = this.get('name');
return `color: ${name}`;
})
});
// tests/integration/components/pretty-color-test.js
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | pretty color', function(hooks) {
// Make sure to call the setupRenderingTest function together with the hooks
// parameter first in your new module. This will do the necessary setup for
// testing your component for you, including setting up a way to access the
// rendered DOM of your component later on in the test, and cleaning up
// once your tests in this module are finished.
setupRenderingTest(hooks);
test('it renders', async function(assert) {
assert.expect(2);
// set the outer context to red
this.set('colorValue', 'red');
await render(hbs`{{pretty-color name=colorValue}}`);
assert.equal(this.element.querySelector('div').getAttribute('style'), 'color: red', 'starts as red');
this.set('colorValue', 'blue');
assert.equal(this.element.querySelector('div').getAttribute('style'), 'color: blue', 'updates to blue'); });
});
// Stubbing services
//
// In cases where components have dependencies on Ember services, it is
// possible to stub these dependencies for rendering tests. You stub Ember
// services by using the built-in register() function to register your
// stub service in place of the default.
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import Service from '@ember/service';
//Stub location service
const locationStub = Service.extend({
city: 'New York',
country: 'USA',
currentLocation: {
x: 1234,
y: 5678
},
getCurrentCity() {
return this.get('city');
},
getCurrentCountry() {
return this.get('country');
}
});
module('Integration | Component | location indicator', function(hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function(assert) {
this.owner.register('service:location-service', locationStub);
});
test('should reveal current location', async function(assert) {
await render(hbs`{{location-indicator}}`);
assert.equal(this.element.textContent.trim(),
'You currently are located in New York, USA');
});
});
/*
* Unit & container tests
*
* Unit tests (as well as container tests) are generally used to test a
* small piece of code and ensure that it is doing what was intended.
*/
// app/services/some-thing.js
import Service from '@ember/service';
export default Service.extend({
foo: 'bar',
testMethod() {
this.set('foo', 'baz');
}
});
// tests/unit/services/some-thing-test.js
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Service | some thing', function(hooks) {
// The `setupTest` helper provides us with some conveniences, such as the `this.owner` object,
// that helps us to create or lookup objects which are needed to setup our test.
// In this example, we use the `this.owner` object to lookup the service instance that
// becomes our test subject: `someThing`. Note that in a unit test you can customize any
// object under test by setting its properties accordingly. We can use the `set` method
// of the test object to achieve this.
setupTest(hooks);
test('should update foo on testMethod', function(assert) {
const someThing = this.owner.lookup('service:some-thing');
someThing.testMethod();
assert.equal(someThing.get('foo'), 'baz');
});
});
/*
* Running tests
*
* Run your tests with `ember test` on the command-line. You can re-run your tests on
* every file-change with `ember test --server`.
*
* Tests can also be executed when you are running a local development server
* (started by running `ember server`), at the `/tests` URI which renders the `tests/index.html` template.
*/
```
ember test
ember test --server
ember test --filter="dashboard"
run ember server then visit http://localhost:4200/tests
```
/*
* 09 | Addons
* --------------------------------------------------------------
*
* Ember has a rich ecosystem of addons that can be easily added to projects.
* Addons provide a wide range of functionality to projects, often saving time and
* letting you focus on your project.
*
* To browse addons, visit the [EmberObserver](https://emberobserver.com/) website. It catalogs and categorizes Ember
* addons that have been published to NPM and assigns them a score based on a variety of criteria.
*
* > ember install <addont-name>
*/
/*
* 10 | Configuration
* --------------------------------------------------------------
*
* Ember CLI ships with support for managing your application's environment. Ember CLI
* will setup a default environment config file at config/environment. Here, you can define
* an ENV object for each environment, which are currently limited to three: development,
* test, and production.
*/
// The ENV object has three important keys:
// - `EmberENV` can be used to define Ember feature flags (see the Feature Flags guide).
// - `APP` can be used to pass flags/options to your application instance.
// - `environment` contains the name of the current environment (development,production or test).
// You can access these environment variables in your application code by importing from `your-application-name/config/environment`.
import ENV from 'your-application-name/config/environment';
if (ENV.environment === 'development') {
// ...
}
/*
* 11 | Community
* --------------------------------------------------------------
*
* Ember's secret sauce
*
* more at [Ember Community Page](https://emberjs.com/community/)
*
*/
// Ember Discussion Forum
//
// url: http://discuss.emberjs.com/
//
// A great venue for discussing things like features, architecture, and best practices
// and a great place to ask questions (and get great answers from Ember Core Team members
// and other members of the community)
// Ember Community Slack
//
// url: https://embercommunity.slack.com/
//
// Use the Slackin app to receive an invitation.
// Ember Times
//
// url: https://the-emberjs-times.ongoodbits.com/
//
// Follow the progress of new features in the Ember ecosystem, requests for community
// input (RFCs), and calls for contributors
// Ember Weekly
//
// url: http://www.emberweekly.com/
//
// A curated list of Ember learning resources (podcasts, videos, blog posts, books, and more)
// Official Ember Blog
//
// url: https://emberjs.com/blog/
//
// Big announcements like new Ember.js version release notes or State of the Union information
// Ember Github
//
// url: https://github.com/emberjs/
// Ember Meetups
//
// url: https://emberjs.com/community/meetups/
+201
View File
@@ -0,0 +1,201 @@
<!-- * *******************************************************************************************
* HTML5 Cheat sheet by Hackr.io
* Source: https://websitesetup.org/wp-content/uploads/2014/02/HTML-CHEAT-SHEET-768x8555.png
* ******************************************************************************************* * -->
<!-- Document Summary -->
<!DOCTYPE html> <!-- Tells the browser that HTML5 version of HTML to be recognized by the browser -->
<html lang="en"></html> <!-- The HTML lang attribute is used to identify the language of text content on the web. This information helps search engines return language specific results, -->
<head></head> <!-- Contains Information specific to the page like title, styles and scripts -->
<title></title> <!-- Title for the page that shows up in the browser title bar -->
<body></body> <!-- Content that the user will see -->
<!-- Document Information -->
<base/> <!-- Usefull for specifying relative links in a document -->
<style></style> <!-- Contains styles for the html document -->
<meta/> <!-- Contains additional information about the page, author, page description and other hidden page info -->
<script></script> <!-- Contains all scripts internal or external -->
<link/> <!-- Used to create relationships with external pages and stylesheets -->
<!-- Document Structure -->
<h1></h1> ... <h6></h6> <!-- All six levels of heading with 1 being the most promiment and 6 being the least prominent -->
<p></p> <!-- Used to organize paragraph text -->
<div></div> <!-- A generic container used to denote a page section -->
<span></span> <!-- Inline section or block container used for creating inline style elements -->
<br/> <!-- Creates a line-break -->
<hr> <!-- Creates a sectional break into HTML -->
<!-- Text Formatting -->
<strong></strong> and <b></b> <!-- Makes text contained in the tag as bold -->
<em></em> and <i></i> <!-- Alternative way to make the text contained in the tag as italic -->
<del></del> <!-- Creates a strike through the text element -->
<pre></pre> <!-- Preformatted monospace text block with some spacing intact -->
<blockquote></blockquote> <!-- Contains long paragraphs of quotations often cited -->
<abbr></abbr> <!-- Contains abbreviations while also making the full form avaialable -->
<address></address> <!-- Used to display contact information -->
<code></code> <!-- Used to display inline code snippets -->
<q></q> <!-- Defines a short inline quotation -->
<sub></sub> <!-- Defines subscripted text -->
<sup></sup> <!-- Defines superscripted text -->
<kbd></kbd> <!-- Specifies text as keyboard input -->
<small></small> <!-- Specifies small text -->
<ins></ins> <!-- Defines a text that has been inserted into the document -->
<!-- Links Formatting -->
<a href="url"></a> <!-- Used to link to external or internal pages of a wbesite -->
<a href="mailto:email@example.com"></a> <!-- Used to link to an email address -->
<a href="name"></a> <!-- Used to link to a document element -->
<a href="#name"></a> <!-- Used to link to specific div element -->
<a href="tel://####-####-##"></a> <!-- Used to display phone numbers and make them clickable -->
<!-- Image Formatting -->
<img src="url" alt="text"> <!-- Used to display images in a webpage where src="url" contains the link to the image source and alt="" contains an alternative text to display when the image is not displayed -->
<!-- List Formatting -->
<ol></ol> <!-- Used to create ordered lists with numbers in the items -->
<ul></ul> <!-- Used to display unordered lists with numbers in the items -->
<li></li> <!-- Contains list items inside ordered and unordered lists -->
<dl></dl> <!-- Contains list item definitions -->
<dt></dt> <!-- Definition of single term inline with body content -->
<dd></dd> <!-- The descrpition of the defined term -->
<!-- Forms Formatting and Attributes -->
<form action="url"></form> <!-- Form element creates a form and action="" specifies where the data is to be sent to when the visitor submits the form -->
<!-- Supported attributes -->
method="somefunction()" <!-- Contains the type of request (GET, POST... etc) which dictates how to send the data of the form -->
enctype="" <!-- Dictates how the data is to be encoded when the data is sent to the web server. -->
autocomplete="" <!-- Specifies if the autocomplete functionality is enabled or not -->
novalidate <!-- Dictates if the form will be validated or not -->
accept-charset="" <!-- Identifies the character encoding upon form submission -->
target="" <!-- Tell where to display the information upon form submission. Possible values: '_blank', '_self', '_parent', '_top' -->
<fieldset disabled="disabled"></fieldset> <!-- Identifies the group of all fields in the form -->
<label for=""></label> <!-- A simple field label telling the user what to type in the field -->
<legend></legend> <!-- The form legend acts as a caption for the fieldset element -->
<input type="text/email/number/color/date"> <!-- Input is the input field where the user can input various types of data -->
<!-- Supported attributes -->
name="" <!-- Describes the name of the form -->
width="" <!-- Specifies the width of an input field -->
value="" <!-- Describes the value of the input information field -->
size="" <!-- Specifies the input element width in characters -->
maxlength="" <!-- Specifies the maximum input character numbers -->
required="" <!-- Specifies if the input field is required to fill in before submitting the form -->
step="" <!-- Identifies the legal number intervals of the input field -->
<textarea name="" id="" cols="30" rows="10"> <!-- Specifies a large input text field for longer messages -->
</textarea>
<select name=""></select> <!-- Describes a dropdown box for users to select from variety of choices -->
<!-- Supported attributes -->
name="" <!-- The name for a dropdown combination box -->
size="" <!-- Specifies the number of available options -->
multiple <!-- Allows for multiple option selections -->
required <!-- Requires that a value is selected before submitting the form -->
autofocus <!-- Specifies that the dropdown automatically comes to focus once the page loads -->
<optgroup></optgroup> <!-- Specifies the entire grouping of available options -->
<option value=""></option> <!-- Defines one of the avaialble option from the dropdown list -->
<button></button> <!-- A clickable button to submit the form -->
<!-- Tables Formatting -->
<table></table> <!-- Defines and contains all table related content -->
<caption></caption> <!-- A description of what table is and what it contains -->
<thead></thead> <!-- The table headers contain the type of information defined in each column underneath -->
<tbody></tbody> <!-- Contains the tables data or information -->
<tfoot></tfoot> <!-- Defines table footer -->
<tr></tr> <!-- Contains the information to be included in a table row -->
<th></th> <!-- Contains the information to be included in a single table header -->
<td></td> <!-- Contains actual information in a table cell -->
<colgroup></colgroup> <!-- Groups a single or multiple columns for formatting purposes -->
<col> <!-- Defines a single column of information inside a table -->
<!-- Objects and iFrames -->
<object data=""></object> <!-- Describes and embed file type including audio, video, PDF's, images -->
<!-- Supported attributes -->
type="" <!-- Describes the type of media embedded -->
height="" <!-- Describes the height of the object in pixels -->
width="" <!-- Describes the width of the object in pixels -->
usemap="" <!-- This is the name of the client-side image map in the object -->
<iframe src="" frameborder="0"></iframe> <!-- Contains an inline frame that allows to embed external information -->
<embed src="" type=""> <!-- Acts as a container for external application or plug-in -->
src="" <!-- The source of the external file you're embedding -->
width="" <!-- Describes the width of the iframe in pixels -->
<!-- HTML5 New Tags -->
<header></header> <!-- Defines the header block for a document or a section -->
<footer></footer> <!-- Defines the footer block for a document or a section -->
<main></main> <!-- Describes the main content of a document -->
<article></article> <!-- Identifies an article inside a document -->
<aside></aside> <!-- Specifies content contained in a document sidebar -->
<section></section> <!-- Defines a section of a document -->
<details></details> <!-- Describes additonal information that user can view or hide -->
<dialog></dialog> <!-- A dialog box or a window -->
<figure></figure> <!-- An independent content block featuring images, diagrams or illustrations -->
<figcaption></figcaption> <!-- Caption that describe a figure -->
<mark></mark> <!-- Displays a portion of highlighted text with in a page content -->
<nav></nav> <!-- Navigation links for the user in a document -->
<menuitem></menuitem> <!-- The specific menu item that a user can raise from a pop up menu -->
<meter></meter> <!-- Describes the scalar measurement with in a known array -->
<progress></progress> <!-- Displays the progress of a task usually a progress bar -->
<rp></rp> <!-- Describes text within the browsers that do not support ruby notations -->
<rt></rt> <!-- Displays east asian typography character details -->
<ruby></ruby> <!-- Describes annotations for east asian typography -->
<summary></summary> <!-- Contains a visible heading for details element -->
<bdi></bdi> <!-- Helps you format parts of text in a different direction than other text -->
<time></time> <!-- Identifies the time and date -->
<wbr> <!-- A line break within the content -->
<!-- Some other useful tags -->
<canvas></canvas> <!-- Allows to draw 2D shapes on the web page with the help of javascript -->
<map></map> <!-- Specifies an image map -->
<!-- Collective Character Obejcts -->
&#34; &quot; Quotation Marks - "
&#38; &amp; Ampersand - &
&#60; &lt; Less than sign - <
&#62; &gt; Greater than sign - >
&#160; &nbsp; Non-breaking space
&#169; &copy; Copyright Symbol - ©
&#64; &Uuml; @ symbol - @
&#149; &ouml; Small bullet - .
&#153; &ucirc; Trademark Symbol - ™
+339
View File
@@ -0,0 +1,339 @@
/* *******************************************************************************************
* REACT.JS CHEATSHEET
* DOCUMENTATION: https://reactjs.org/docs/
* FILE STRUCTURE: https://reactjs.org/docs/faq-structure.html
* ******************************************************************************************* */
```
npm install --save react // declarative and flexible JavaScript library for building UI
npm install --save react-dom // serves as the entry point of the DOM-related rendering paths
npm install --save prop-types // runtime type checking for React props and similar objects
```
// notes: don't forget the command lines
/* *******************************************************************************************
* REACT
* https://reactjs.org/docs/react-api.html
* ******************************************************************************************* */
// Create and return a new React element of the given type.
// Code written with JSX will be converted to use React.createElement().
// You will not typically invoke React.createElement() directly if you are using JSX.
React.createElement(
type,
[props],
[...children]
)
// Clone and return a new React element using element as the starting point.
// The resulting element will have the original elements props with the new props merged in shallowly.
React.cloneElement(
element,
[props],
[...children]
)
// Verifies the object is a React element. Returns true or false.
React.isValidElement(object)
React.Children // provides utilities for dealing with the this.props.children opaque data structure.
// Invokes a function on every immediate child contained within children with this set to thisArg.
React.Children.map(children, function[(thisArg)])
// Like React.Children.map() but does not return an array.
React.Children.forEach(children, function[(thisArg)])
// Returns the total number of components in children,
// equal to the number of times that a callback passed to map or forEach would be invoked.
React.Children.count(children)
// Verifies that children has only one child (a React element) and returns it.
// Otherwise this method throws an error.
React.Children.only(children)
// Returns the children opaque data structure as a flat array with keys assigned to each child.
// Useful if you want to manipulate collections of children in your render methods,
// especially if you want to reorder or slice this.props.children before passing it down.
React.Children.toArray(children)
// The React.Fragment component lets you return multiple elements in a render() method without creating an additional DOM element
// You can also use it with the shorthand <></> syntax.
React.Fragment
/* *******************************************************************************************
* REACT.COMPONENT
* React.Component is an abstract base class, so it rarely makes sense to refer to React.Component
* directly. Instead, you will typically subclass it, and define at least a render() method.
* https://reactjs.org/docs/react-component.html
* ******************************************************************************************* */
class Component extends React.Component {
// Will be called before it is mounted
constructor(props) {
// Call this method before any other statement
// or this.props will be undefined in the constructor
super(props);
// The constructor is also often used to bind event handlers to the class instance.
// Binding makes sure the method has access to component attributes like this.props and this.state
this.method = this.method.bind(this);
// The constructor is the right place to initialize state.
this.state = {
active: true,
// In rare cases, its okay to initialize state based on props.
// This effectively “forks” the props and sets the state with the initial props.
// If you “fork” props by using them for state, you might also want to implement componentWillReceiveProps(nextProps)
// to keep the state up-to-date with them. But lifting state up is often easier and less bug-prone.
color: props.initialColor
};
}
// Enqueues changes to the component state and
// tells React that this component and its children need to be re-rendered with the updated state.
// setState() does not always immediately update the component. It may batch or defer the update until later.
// This makes reading this.state right after calling setState() a potential pitfall.
// Instead, use componentDidUpdate or a setState callback.
// You may optionally pass an object as the first argument to setState() instead of a function.
setState(updater[, callback]) { }
// Invoked just before mounting occurs (before render())
// This is the only lifecycle hook called on server rendering.
componentWillMount() { }
// Invoked immediately after a component is mounted.
// Initialization that requires DOM nodes should go here.
// If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
// This method is a good place to set up any subscriptions. If you do that, dont forget to unsubscribe in componentWillUnmount().
componentDidMount() { }
// Invoked before a mounted component receives new props.
// If you need to update the state in response to prop changes (for example, to reset it),
// you may compare this.props and nextProps and perform state transitions using this.setState() in this method.
componentWillReceiveProps(nextProps) { }
// Let React know if a components output is not affected by the current change in state or props.
// The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.
// shouldComponentUpdate() is invoked before rendering when new props or state are being received. Defaults to true.
// This method is not called for the initial render or when forceUpdate() is used.
// Returning false does not prevent child components from re-rendering when their state changes.
shouldComponentUpdate(nextProps, nextState) { }
// Invoked just before rendering when new props or state are being received.
// Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
// Note that you cannot call this.setState() here; nor should you do anything else
// (e.g. dispatch a Redux action) that would trigger an update to a React component before componentWillUpdate() returns.
// If you need to update state in response to props changes, use componentWillReceiveProps() instead.
componentWillUpdate(nextProps, nextState) { }
// Invoked immediately after updating occurs. This method is not called for the initial render.
// Use this as an opportunity to operate on the DOM when the component has been updated.
// This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
componentDidUpdate(prevProps, prevState) { }
// Invoked immediately before a component is unmounted and destroyed.
// Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests,
// or cleaning up any subscriptions that were created in componentDidMount().
componentWillUnmount() { }
// Error boundaries are React components that catch JavaScript errors anywhere in their child component tree,
// log those errors, and display a fallback UI instead of the component tree that crashed.
// Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
componentDidCatch() { }
// This method is required.
// It should be pure, meaning that it does not modify component state,
// it returns the same result each time its invoked, and
// it does not directly interact with the browser (use lifecycle methods for this)
// It must return one of the following types: react elements, string and numbers, portals, null or booleans.
render() {
// Contains the props that were defined by the caller of this component.
console.log(this.props);
// Contains data specific to this component that may change over time.
// The state is user-defined, and it should be a plain JavaScript object.
// If you dont use it in render(), it shouldnt be in the state.
// For example, you can put timer IDs directly on the instance.
// Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made.
// Treat this.state as if it were immutable.
console.log(this.state);
return (
<div>
{/* Comment goes here */}
Hello, {this.props.name}!
</div>
);
}
}
// Can be defined as a property on the component class itself, to set the default props for the class.
// This is used for undefined props, but not for null props.
Component.defaultProps = {
color: 'blue'
};
component = new Component();
// By default, when your components state or props change, your component will re-render.
// If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().
// Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().
component.forceUpdate(callback)
/* *******************************************************************************************
* REACT.DOM
* The react-dom package provides DOM-specific methods that can be used at the top level of
* your app and as an escape hatch to get outside of the React model if you need to.
* Most of your components should not need to use this module.
* https://reactjs.org/docs/react-dom.html
* ******************************************************************************************* */
// Render a React element into the DOM in the supplied container and return a reference
// to the component (or returns null for stateless components).
ReactDOM.render(element, container[, callback])
// Same as render(), but is used to hydrate a container whose HTML contents were rendered
// by ReactDOMServer. React will attempt to attach event listeners to the existing markup.
ReactDOM.hydrate(element, container[, callback])
// Remove a mounted React component from the DOM and clean up its event handlers and state.
// If no component was mounted in the container, calling this function does nothing.
// Returns true if a component was unmounted and false if there was no component to unmount.
ReactDOM.unmountComponentAtNode(container)
// If this component has been mounted into the DOM, this returns the corresponding native browser
// DOM element. This method is useful for reading values out of the DOM, such as form field values
// and performing DOM measurements. In most cases, you can attach a ref to the DOM node and avoid
// using findDOMNode at all.
ReactDOM.findDOMNode(component)
// Creates a portal. Portals provide a way to render children into a DOM node that exists outside
// the hierarchy of the DOM component.
ReactDOM.createPortal(child, container)
/* *******************************************************************************************
* REACTDOMSERVER
* The ReactDOMServer object enables you to render components to static markup.
* https://reactjs.org/docs/react-dom.html
* ******************************************************************************************* */
// Render a React element to its initial HTML. React will return an HTML string.
// You can use this method to generate HTML on the server and send the markup down on the initial
// request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
ReactDOMServer.renderToString(element)
// Similar to renderToString, except this doesnt create extra DOM attributes that React uses
// internally, such as data-reactroot. This is useful if you want to use React as a simple static
// page generator, as stripping away the extra attributes can save some bytes.
ReactDOMServer.renderToStaticMarkup(element)
// Render a React element to its initial HTML. Returns a Readable stream that outputs an HTML string.
// The HTML output by this stream is exactly equal to what ReactDOMServer.renderToString would return.
// You can use this method to generate HTML on the server and send the markup down on the initial
// request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
ReactDOMServer.renderToNodeStream(element)
// Similar to renderToNodeStream, except this doesnt create extra DOM attributes that React uses
// internally, such as data-reactroot. This is useful if you want to use React as a simple static
// page generator, as stripping away the extra attributes can save some bytes.
ReactDOMServer.renderToStaticNodeStream(element)
/* *******************************************************************************************
* TYPECHECKING WITH PROPTYPES
* https://reactjs.org/docs/typechecking-with-proptypes.html
* ******************************************************************************************* */
import PropTypes from 'prop-types';
MyComponent.propTypes = {
// You can declare that a prop is a specific JS type. By default, these
// are all optional.
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: PropTypes.node,
// A React element.
optionalElement: PropTypes.element,
// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: PropTypes.instanceOf(Message),
// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
]),
// An array of a certain type
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
// An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
}),
// You can chain any of the above with `isRequired` to make sure a warning
// is shown if the prop isn't provided.
requiredFunc: PropTypes.func.isRequired,
// A value of any data type
requiredAny: PropTypes.any.isRequired,
// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
},
// You can also supply a custom validator to `arrayOf` and `objectOf`.
// It should return an Error object if the validation fails. The validator
// will be called for each key in the array or object. The first two
// arguments of the validator are the array or object itself, and the
// current item's key.
customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
if (!/matchme/.test(propValue[key])) {
return new Error(
'Invalid prop `' + propFullName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
}
})
};
File diff suppressed because it is too large Load Diff
+799
View File
@@ -0,0 +1,799 @@
/* *******************************************************************************************
* GLOBAL CONFIG
* Vue.config is an object containing Vues global configurations.
* You can modify its properties listed below before bootstrapping your application.
* https://vuejs.org/v2/api/#Global-Config
* ******************************************************************************************* */
// Configure whether to allow vue-devtools inspection
Vue.config.devtools = true
// Enable component init, compile, render and patch performance tracing in the browser devtool timeline.
Vue.config.performance = true
// Prevent the production tip on Vue startup.
Vue.config.productionTip = false
// Suppress all Vue logs and warnings
Vue.config.silent = false
// Make Vue ignore custom elements defined outside of Vue
Vue.config.ignoredElements = [
'my-custom-web-component',
'another-web-component',
/^ion-/
]
// Define custom key alias(es) for v-on.
Vue.config.keyCodes = {
v: 86,
f1: 112,
// camelCase won`t work
mediaPlayPause: 179,
// instead you can use kebab-case with double quotation marks
"media-play-pause": 179,
up: [38, 87]
}
// Assign a handler for uncaught errors during component render function and watchers.
Vue.config.errorHandler = function (err, vm, info) {
// handle error
// `info` is a Vue-specific error info, e.g. which lifecycle hook
// the error was found in. Only available in 2.2.0+
}
// Define custom merging strategies for options
Vue.config.optionMergeStrategies._my_option = function (parent, child, vm) {
return child + 1
}
// Assign a custom handler for runtime Vue warnings.
// Note this only works during development and is ignored in production.
Vue.config.warnHandler = function (msg, vm, trace) {
// `trace` is the component hierarchy trace
}
/* *******************************************************************************************
* GLOBAL API
* https://vuejs.org/v2/api/#Global-API
* ******************************************************************************************* */
Vue.version // Provides the installed version of Vue as a string.
Vue.extend(options) // Create a “subclass” of the base Vue constructor.
Vue.mixin( mixin ) // Apply a mixin globally, which affects every Vue instance created afterwards.
Vue.nextTick([callback, context]) // Defer the callback to be executed after the next DOM update cycle.
Vue.use(plugin) // Install a Vue.js plugin. If the plugin is an Object, it must expose an install method.
Vue.set(target, key, value) // Set a property on an object. If the object is reactive, ensure the property is created as a reactive property and trigger view updates.
Vue.delete(target, key) // Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates.
// Register or retrieve a global directive.
Vue.directive('my-directive', {
bind: function () {},
inserted: function () {},
update: function () {},
componentUpdated: function () {},
unbind: function () {}
})
// Register (function directive)
Vue.directive('my-directive', function () {
// This will be called as `bind` and `update`
})
// Getter, return the directive definition if registered
var myDirective = Vue.directive('my-directive')
// Register a global filter
Vue.filter('my-filter', function (value) { })
// Getter, return the filter if registered
var myFilter = Vue.filter('my-filter')
// Register an extended constructor
Vue.component('my-component', Vue.extend({ }))
// Register an options object (automatically call Vue.extend)
Vue.component('my-component', { })
// Retrieve a registered component (always return constructor)
var MyComponent = Vue.component('my-component')
Vue.compile(template) // Compiles a template string into a render function
/* *******************************************************************************************
* OPTIONS > DATA
* https://vuejs.org/v2/api/#Options-Data
* ******************************************************************************************* */
new Vue({
// A list/hash of attributes that are exposed to accept data from the parent component.
// It has an Array-based simple syntax and an alternative Object-based syntax that allows
// advanced configurations such as type checking, custom validation and default values.
props: {
height: Number,
age: {
type: Number,
default: 0,
required: true,
validator: function (value) {
return value >= 0
}
}
},
// Primarily intended to make unit testing easier
propsData: {
age: 12
},
// The data object for the Vue instance.
// Vue will recursively convert its properties into getter/setters to make it “reactive”.
// Note: you should not use an arrow function with the data property
data () {
return {
a: 1,
b: 2
}
},
// Computed properties to be mixed into the Vue instance.
// All getters and setters have their this context automatically bound to the Vue instance.
// Computed properties are cached, and only re-computed on reactive dependency changes.
// Note that if a certain dependency is out of the instances scope (i.e. not reactive),
// the computed property will not be updated.
computed: {
// Note: you should not use an arrow function to define a computed property.
aDouble: function () {
return this.a * 2
},
aPlus: {
get: function () {
return this.a + 1
},
set: function (v) {
this.a = v - 1
}
}
},
// An object where keys are expressions to watch and values are the corresponding callbacks.
// The value can also be a string of a method name, or an Object that contains additional options.
// The Vue instance will call $watch() for each entry in the object at instantiation.
watch: {
// Note: you should not use an arrow function to define a watcher.
a: function (val, oldVal) {
console.log('new: %s, old: %s', val, oldVal)
},
// String method name
b: 'someMethod',
// Deep watcher
c: {
handler: function (val, oldVal) { /* ... */ },
deep: true
},
// The callback will be called immediately after the start of the observation
d: {
handler: function (val, oldVal) { /* ... */ },
immediate: true
}
},
// Methods to be mixed into the Vue instance. You can access these methods directly on the VM instance,
// or use them in directive expressions. All methods will have their this context automatically bound to
// the Vue instance.
methods: {
// Note: you should not use an arrow function to define a method.
plus () {
this.a++
}
}
})
/* *******************************************************************************************
* OPTIONS > DOM
* https://vuejs.org/v2/api/#Options-DOM
* ******************************************************************************************* */
new Vue({
// Provide the Vue instance an existing DOM element to mount on.
// It can be a CSS selector string or an actual HTMLElement.
// After the instance is mounted, the resolved element will be accessible as vm.$el.
el: '#example',
// A string template to be used as the markup for the Vue instance.
// The template will replace the mounted element.
// Any existing markup inside the mounted element will be ignored,
// unless content distribution slots are present in the template.
// If the string starts with # it will be used as a querySelector and
// use the selected elements innerHTML as the template string. This
// allows the use of the common <script type="x-template"> trick to include templates.
template: `
<div class="checkbox-wrapper" @click="check">
<div :class="{ checkbox: true, checked: checked }"></div>
<div class="title">{{ title }}</div>
</div>
`,
// An alternative to string templates allowing you to leverage the full programmatic power of JavaScript.
// The render function receives a createElement method as its first argument used to create VNodes.
// If the component is a functional component, the render function also receives an extra argument context,
// which provides access to contextual data since functional components are instance-less.
render (createElement) {
// create kebabCase id
var headingId = getChildrenTextContent(this.$slots.default)
.toLowerCase()
.replace(/\W+/g, '-')
.replace(/(^\-|\-$)/g, '')
return createElement(
'h' + this.level,
[
createElement('a', {
attrs: {
name: headingId,
href: '#' + headingId
}
}, this.$slots.default)
]
)
},
// Provide an alternative render output when the default render function encounters an error.
// The error will be passed to renderError as the second argument.
// This is particularly useful when used together with hot-reload.
renderError (createElement, err) {
return createElement('pre', { style: { color: 'red' }}, err.stack)
}
})
/* *******************************************************************************************
* OPTIONS > LIFECYCLE HOOKS
* https://vuejs.org/v2/api/#Options-Lifecycle-Hooks
* ******************************************************************************************* */
// All lifecycle hooks automatically have their this context bound to the instance,
// so that you can access data, computed properties, and methods. This means you should not
// use an arrow function to define a lifecycle method (e.g. created: () => this.fetchTodos()).
// The reason is arrow functions bind the parent context, so this will not be the Vue instance as
// you expect and this.fetchTodos will be undefined.
new Vue({
// Called synchronously immediately after the instance has been initialized,
// before data observation and event/watcher setup.
beforeCreate () {
console.log('The instance has been initialized')
},
// Called synchronously after the instance is created. At this stage, the instance has
// finished processing the options which means the following have been set up: data observation,
// computed properties, methods, watch/event callbacks. However, the mounting phase has not been
// started, and the $el property will not be available yet.
created () {
console.log('The instance has been created')
},
// Called right before the mounting begins: the render function
// is about to be called for the first time.
beforeMount () {
console.log('The instance is about to be mounted')
},
// Called after the instance has been mounted, where el is replaced by the newly created vm.$el.
// If the root instance is mounted to an in-document element, vm.$el will also be in-document when
// mounted is called.
mounted () {
console.log('The instance has been mounted')
// Note that mounted does not guarantee that all child components have also been mounted.
// If you want to wait until the entire view has been rendered, you can use vm.$nextTick
// inside of mounted:
this.$nextTick(function () {
// Code that will run only after the
// entire view has been rendered
})
},
// Called when the data changes, before the virtual DOM is re-rendered and patched.
// You can perform further state changes in this hook and they will not trigger additional re-renders.
// This hook is not called during server-side rendering.
beforeUpdate () {
console.log('The instance is about to be re-rendered and patched')
},
// The components DOM will have been updated when this hook is called, so you can perform DOM-dependent
// operations here. However, in most cases you should avoid changing state inside the hook. To react
// to state changes, its usually better to use a computed property or watcher instead.
updated () {
console.log('The instance has been re-rendered and patched')
// Note that updated does not guarantee that all child components have also been re-rendered.
// If you want to wait until the entire view has been re-rendered, you can use vm.$nextTick
// inside of updated:
this.$nextTick(function () {
// Code that will run only after the
// entire view has been re-rendered
})
},
// Called when a kept-alive component is activated.
activated () {
console.log('Component activated')
},
// Called when a kept-alive component is deactivated.
deactivated () {
console.log('Component deactivated')
},
// Called right before a Vue instance is destroyed.
// At this stage the instance is still fully functional.
beforeDestroy () {
console.log('The instance is about to be destroyed')
},
// Called after a Vue instance has been destroyed.
// When this hook is called, all directives of the Vue instance have been unbound,
// all event listeners have been removed, and all child Vue instances have also been destroyed.
destroyed () {
console.log('The instance has been destroyed')
},
// Called when an error from any descendent component is captured.
// The hook receives three arguments: the error, the component instance that triggered the error,
// and a string containing information on where the error was captured.
// The hook can return false to stop the error from propagating further.
errorCaptured (error, vm, info) {
console.log(`The error (${error}) has been captured for ${vm}: ${info}`)
// An errorCaptured hook can return false to prevent the error from propagating further.
// This is essentially saying “this error has been handled and should be ignored.”
// It will prevent any additional errorCaptured hooks or the global config.errorHandler
// from being invoked for this error.
return false
},
})
/* *******************************************************************************************
* OPTIONS > ASSETS
* https://vuejs.org/v2/api/#Options-Assets
* ******************************************************************************************* */
new Vue({
// A hash of directives to be made available to the Vue instance.
directives: {
myDirective: {
// Called only once, when the directive is first bound to the element.
// This is where you can do one-time setup work.
bind: function (el, binding, vnode, oldVnode) {
console.log('The directive is first bound to the element.')
},
// Called when the bound element has been inserted into its parent node
// (this only guarantees parent node presence, not necessarily in-document).
inserted: function (el, binding, vnode, oldVnode) {
console.log('The bound element has been inserted into its parent node.')
},
// Called after the containing components VNode has updated, but possibly before its
// children have updated. The directives value may or may not have changed, but you can
// skip unnecessary updates by comparing the bindings current and old values (see below
// on hook arguments).
update: function (el, binding, vnode, oldVnode) {
console.log('The component VNode has updated.')
},
// Called after the containing components VNode and the VNodes of its children have updated.
componentUpdated: function (el, binding, vnode, oldVnode) {
console.log('The components VNode and the VNodes of its children have updated.')
},
// Called only once, when the directive is unbound from the element.
unbind: function (el, binding, vnode, oldVnode) {
console.log('The directive is unbound from the element.')
},
}
},
// A hash of filters to be made available to the Vue instance.
filters: {
myFilter: function (value) {
console.log('Do your computations and return something to display.')
}
}
})
/* *******************************************************************************************
* OPTIONS > COMPOSITION
* https://vuejs.org/v2/api/#Options-Composition
* ******************************************************************************************* */
new Vue({
// Specify the parent instance for the instance to be created. Establishes a parent-child
// relationship between the two. The parent will be accessible as this.$parent for the child,
// and the child will be pushed into the parents $children array.
parent: vueInstance,
// The mixins option accepts an array of mixin objects. These mixin objects can contain instance
// options like normal instance objects, and they will be merged against the eventual options
// using the same option merging logic in Vue.extend(). e.g. If your mixin contains a created
// hook and the component itself also has one, both functions will be called.
// Mixin hooks are called in the order they are provided, and called before the components own hooks.
mixins: [mixin],
// Allows declaratively extending another component (could be either a plain options object or a
// constructor) without having to use Vue.extend. This is primarily intended to make it easier to
// extend between single file components. This is similar to mixins, the difference being that
// the components own options takes higher priority than the source component being extended.
extends: ObjectOrFunction,
})
/* *******************************************************************************************
* OPTIONS > MISC
* https://vuejs.org/v2/api/#Options-Lifecycle-Hooks
* ******************************************************************************************* */
new Vue({
// Allow the component to recursively invoke itself in its template.
// Note that when a component is registered globally with Vue.component(), the global ID is
// automatically set as its name.
// Another benefit of specifying a name option is debugging. Named components result in more
// helpful warning messages. Also, when inspecting an app in the vue-devtools, unnamed components
// will show up as <AnonymousComponent>, which isnt very informative. By providing the name
// option, you will get a much more informative component tree.
name: 'myComponent',
// Change the plain text interpolation delimiters.
delimiters: ['${', '}'],
// Causes a component to be stateless (no data) and instanceless (no this context). They are
// only a render function that returns virtual nodes making them much cheaper to render.
functional: true,
// By default, parent scope attribute bindings that are not recognized as props will
// “fallthrough” and be applied to the root element of the child component as normal HTML
// attributes. When authoring a component that wraps a target element or another component,
// this may not always be the desired behavior. By setting inheritAttrs to false, this default
// behavior can be disabled. The attributes are available via the $attrs instance property
// (also new in 2.4) and can be explicitly bound to a non-root element using v-bind.
// Note: this option does not affect class and style bindings.
inheritAttrs: true,
// When set to true, will preserve and render HTML comments found in templates. The default
// behavior is discarding them.
comments: true,
})
/* *******************************************************************************************
* INSTANCE PROPERTIES
* https://vuejs.org/v2/api/#Instance-Properties
* ******************************************************************************************* */
// The data object that the Vue instance is observing.
// The Vue instance proxies access to the properties on its data object.
vm.$data
// An object representing the current props a component has received.
// The Vue instance proxies access to the properties on its props object.
vm.$props
// The root DOM element that the Vue instance is managing.
vm.$el
// The instantiation options used for the current Vue instance.
// This is useful when you want to include custom properties in the options:
vm.$options
// The parent instance, if the current instance has one.
vm.$parent
// The root Vue instance of the current component tree.
// If the current instance has no parents this value will be itself.
vm.$root
// The direct child components of the current instance.
// Note theres no order guarantee for $children, and it is not reactive.
// If you find yourself trying to use $children for data binding,
// consider using an Array and v-for to generate child components,
// and use the Array as the source of truth.
vm.$children
// Used to programmatically access content distributed by slots.
// Each named slot has its own corresponding property (e.g. the contents of slot="foo" will
// be found at vm.$slots.foo). The default property contains any nodes not included in a named slot.
// Accessing vm.$slots is most useful when writing a component with a render function.
vm.$slots
// Used to programmatically access scoped slots. For each slot, including the default one, the
// object contains a corresponding function that returns VNodes.
// Accessing vm.$scopedSlots is most useful when writing a component with a render function.
vm.$scopedSlots
// An object that holds child components that have ref registered.
vm.$refs
// Whether the current Vue instance is running on the server.
vm.$isServer
// Contains parent-scope attribute bindings (except for class and style) that are not recognized
// (and extracted) as props. When a component doesnt have any declared props, this essentially
// contains all parent-scope bindings (except for class and style), and can be passed down to an
// inner component via v-bind="$attrs" - useful when creating higher-order components.
vm.$attrs
// Contains parent-scope v-on event listeners (without .native modifiers).
// This can be passed down to an inner component via v-on="$listeners" - useful when creating
// higher-order components.
vm.$listeners
/* *******************************************************************************************
* INSTANCE METHODS > DATA
* https://vuejs.org/v2/api/#Instance-Methods-Data
* ******************************************************************************************* */
// Watch an expression or a computed function on the Vue instance for changes.
// The callback gets called with the new value and the old value.
// The expression only accepts dot-delimited paths.
// For more complex expressions, use a function instead.
var unwatch = vm.$watch('a.b.c', function (newVal, oldVal) {
// do something
}, {
// To also detect nested value changes inside Objects, you need to pass in deep: true
// in the options argument. Note that you dont need to do so to listen for Array mutations.
deep: true,
// Passing in immediate: true in the option will trigger the callback immediately with the
// current value of the expression:
immediate: true
})
// later, teardown the watcher
unwatch()
// This is the alias of the global Vue.set.
vm.$set(target,key, value)
// This is the alias of the global Vue.delete.
vm.$delete(target, key)
/* *******************************************************************************************
* INSTANCE METHODS > EVENTS
* https://vuejs.org/v2/api/#Instance-Methods-Events
* ******************************************************************************************* */
// Listen for a custom event on the current vm. Events can be triggered by vm.$emit.
// The callback will receive all the additional arguments passed into these event-triggering methods.
vm.$on(event, callback)
// Listen for a custom event, but only once.
// The listener will be removed once it triggers for the first time.
vm.$once(event, callback)
// Remove custom event listener(s).
// If no arguments are provided, remove all event listeners;
// If only the event is provided, remove all listeners for that event;
// If both event and callback are given, remove the listener for that specific callback only.
vm.$off([event, callback])
// Trigger an event on the current instance.
// Any additional arguments will be passed into the listeners callback function.
vm.$emit(event, [args])
/* *******************************************************************************************
* INSTANCE METHODS > LIFECYCLE
* https://vuejs.org/v2/api/#Instance-Methods-Lifecycle
* ******************************************************************************************* */
// If a Vue instance didnt receive the el option at instantiation, it will be in “unmounted”
// state, without an associated DOM element. vm.$mount() can be used to manually start the mounting
// of an unmounted Vue instance.
vm.$mount([elementOrSelector])
// Force the Vue instance to re-render. Note it does not affect all child components,
// only the instance itself and child components with inserted slot content.
vm.$forceUpdate()
// Defer the callback to be executed after the next DOM update cycle.
// Use it immediately after youve changed some data to wait for the DOM update.
// This is the same as the global Vue.nextTick, except that the callbacks this context is
// automatically bound to the instance calling this method.
vm.$nextTick([callback])
// Completely destroy a vm. Clean up its connections with other existing vms, unbind all its
// directives, turn off all event listeners.
// Triggers the beforeDestroy and destroyed hooks.
vm.$destroy()
/* *******************************************************************************************
* DIRECTIVES
* https://vuejs.org/v2/api/#Directives
* ******************************************************************************************* */
// <!-- Updates the elements textContent. -->
// <!-- If you need to update the part of textContent, you should use {{ Mustache }} interpolations. -->
// <span v-text="msg"></span>
// <!-- Updates the elements innerHTML. Note that the contents are inserted as plain HTML -->
// <!-- they will not be compiled as Vue templates. If you find yourself trying to compose templates -->
// <!-- using v-html, try to rethink the solution by using components instead. -->
// <div v-html="html"></div>
// <!-- Toggles the elements display CSS property based on the truthy-ness of the expression value. -->
// <!-- This directive triggers transitions when its condition changes. -->
// <div v-show="condition"></div>
// <!-- Conditionally render the element based on the truthy-ness of the expression value. -->
// <!-- The element and its contained directives / components are destroyed and re-constructed -->
// <!-- during toggles. If the element is a <template> element, its content will be extracted as -->
// <!-- the conditional block. This directive triggers transitions when its condition changes. -->
// <div v-if="condition"></div>
// <div v-else-if="anotherCondition"></div>
// <div v-else></div>
// <!-- Render the element or template block multiple times based on the source data. -->
// <!-- The directives value must use the special syntax alias in expression to provide an alias -->
// <!-- for the current element being iterated on: -->
// <div v-for="item in items">{{ item.text }}</div>
// <!-- Alternatively, you can also specify an alias for the index (or the key if used on an Object): -->
// <div v-for="(item, index) in items"></div>
// <div v-for="(val, key) in object"></div>
// <div v-for="(val, key, index) in object"></div>
// <!-- Attaches an event listener to the element. The event type is denoted by the argument. -->
// <!-- The expression can be a method name, an inline statement, or omitted if there are modifiers present. -->
// .stop: Call event.stopPropagation().
// .prevent: Call event.preventDefault().
// .capture: Add event listener in capture mode.
// .self: Only trigger handler if event was dispatched from this element.
// .{keyCode | keyAlias}: Only trigger handler on certain keys.
// .native: Listen for a native event on the root element of component.
// .once: Trigger handler at most once.
// .left: (2.2.0+) only trigger handler for left button mouse events.
// .right: (2.2.0+) only trigger handler for right button mouse events.
// .middle: (2.2.0+) only trigger handler for middle button mouse events.
// .passive: (2.3.0+) attaches a DOM event with { passive: true }.
// Method handler: <button v-on:click="doThis"></button>
// Object syntax (2.4.0+): <button v-on="{ mousedown: onMouseDown, mouseup: onMouseUp }"></button>
// Inline statement: <button v-on:click="doThat('hello', $event)"></button>
// Shorthand: <button @click="doThis"></button>
// Stop propagation: <button @click.stop="doThis"></button>
// Prevent default: <button @click.prevent="doThis"></button>
// Prevent default without expression: <form @submit.prevent></form>
// Chain modifiers: <button @click.stop.prevent="doThis"></button>
// Key modifier using keyAlias: <input @keyup.enter="onEnter">
// Key modifier using keyCode: <input @keyup.13="onEnter">
// The click event will be triggered at most once: <button v-on:click.once="doThis"></button>
// <!-- Dynamically bind one or more attributes, or a component prop to an expression. -->
// <!-- When used to bind the class or style attribute, it supports additional value types such as -->
// <!-- Array or Objects. See linked guide section below for more details. -->
// .prop: Bind as a DOM property instead of an attribute.
// .camel: (2.1.0+) transform the kebab-case attribute name into camelCase.
// .sync: (2.3.0+) a syntax sugar that expands into a v-on handler for updating the bound value.
// Bind an attribute: <img v-bind:src="imageSrc">
// Shorthand: <img :src="imageSrc">
// With inline string concatenation: <img :src="'/path/to/images/' + fileName">
// Class binding: <div :class="{ red: isRed }"></div>
// Style binding: <div :style="{ fontSize: size + 'px' }"></div>
// Binding an object of attributes <div v-bind="{ id: someProp, 'other-attr': otherProp }"></div>
// DOM attribute binding with prop modifier: <div v-bind:text-content.prop="text"></div>
// Prop binding. "prop" must be declared in my-component: <my-component :prop="someThing"></my-component>
// Pass down parent props in common with a child component: <child-component v-bind="$props"></child-component>
// XLink: <svg><a :xlink:special="foo"></a></svg>
// <!-- Create a two-way binding on a form input element or a component. -->
// <!-- For detailed usage and other notes, see the Guide section linked below. -->
// .lazy: Listen to change events instead of input
// .number: Cast input string to numbers
// .trim: Trim input
// <input v-model="message" placeholder="edit me">
// <textarea v-model="message" placeholder="add multiple lines"></textarea>
// <input type="checkbox" id="checkbox" v-model="checked">
// <!-- Skip compilation for this element and all its children. -->
// <!-- You can use this for displaying raw mustache tags. -->
// <!-- Skipping large numbers of nodes with no directives on them can also speed up compilation. -->
// <span v-pre>{{ this will not be compiled }}</span>
// <!-- This directive will remain on the element until the associated Vue instance finishes -->
// <!-- compilation. Combined with CSS rules such as [v-cloak] { display: none }, this directive -->
// <!-- can be used to hide un-compiled mustache bindings until the Vue instance is ready. -->
// <div v-cloak>{{ message }}</div>
// [v-cloak] { display: none; }
// <!-- Render the element and component once only. On subsequent re-renders, the element/component -->
// <!-- and all its children will be treated as static content and skipped. This can be used to -->
// <!-- optimize update performance. -->
// <span v-once>This will never change: {{msg}}</span>
// <my-component v-once :comment="msg"></my-component>
/* *******************************************************************************************
* SPECIAL ATTRIBUTES
* https://vuejs.org/v2/api/#Special-Attributes
* ******************************************************************************************* */
// <!-- The key special attribute is primarily used as a hint for Vues virtual DOM algorithm to -->
// <!-- identify VNodes when diffing the new list of nodes against the old list. Without keys, Vue uses -->
// <!-- an algorithm that minimizes element movement and tries to patch/reuse elements of the same type -->
// <!-- in-place as much as possible. With keys, it will reorder elements based on the order change of -->
// <!-- keys, and elements with keys that are no longer present will always be removed/destroyed. -->
// <ul><li v-for="item in items" :key="item.id">...</li></ul>
// <transition><span :key="text">{{ text }}</span></transition>
// <!-- ref is used to register a reference to an element or a child component. The reference will be -->
// <!-- registered under the parent components $refs object. If used on a plain DOM element, the -->
// <!-- reference will be that element; if used on a child component, the reference will be component instance: -->
// <!-- vm.$refs.p will be the DOM node -->
// <p ref="p">hello</p>
// <!-- vm.$refs.child will be the child comp instance -->
// <child-comp ref="child"></child-comp>
// <!-- Used on content inserted into child components to indicate which named slot the content belongs to. -->
// <!-- Child markup: -->
// <header><slot name="header"></slot></header>
// <!-- Parent markup: -->
// <app-layout><h1 slot="header">Here might be a page title</h1></app-layout>
// <!-- Used for dynamic components and to work around limitations of in-DOM templates. -->
// <component :is="currentView"></component>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

-17
View File
@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="38px" height="38px" viewBox="0 0 38 38" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>facebook</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Cheatsheet-Block" transform="translate(-105.000000, -113.000000)">
<g id="Social-Icons" transform="translate(20.000000, 113.000000)">
<g id="facebook" transform="translate(85.000000, 0.000000)">
<path d="M0,19 C0,8.50658923 8.50658923,0 19,0 C29.4934108,0 38,8.50658923 38,19 C38,29.4934108 29.4934108,38 19,38 C8.50658923,38 0,29.4934108 0,19 Z" id="back" fill="#3B5998"></path>
<path d="M20.3470644,29.5382524 L20.3470644,19.2012493 L23.2005294,19.2012493 L23.5786751,15.6390608 L20.3470644,15.6390608 L20.3519125,13.8561511 C20.3519125,12.9270775 20.4401869,12.4292586 21.7746049,12.4292586 L23.558475,12.4292586 L23.558475,8.86666667 L20.7046061,8.86666667 C17.2766505,8.86666667 16.070099,10.5947113 16.070099,13.5007391 L16.070099,15.6394642 L13.9333333,15.6394642 L13.9333333,19.2016527 L16.070099,19.2016527 L16.070099,29.5382524 L20.3470644,29.5382524 Z" id="Shape" fill="#FFFFFF"></path>
</g>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.4 KiB

-17
View File
@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="38px" height="38px" viewBox="0 0 38 38" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>LinkedIN</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Cheatsheet-Block" transform="translate(-164.000000, -227.000000)">
<g id="Social-Icons" transform="translate(20.000000, 227.000000)">
<g id="LinkedIN" transform="translate(144.000000, 0.000000)">
<path d="M0,19 C0,8.50658923 8.50658923,0 19,0 C29.4934108,0 38,8.50658923 38,19 C38,29.4934108 29.4934108,38 19,38 C8.50658923,38 0,29.4934108 0,19 Z" id="back" fill="#0077B5"></path>
<path d="M13.4270957,15.7366299 L13.4270957,28.6738181 L9.12128023,28.6738181 L9.12128023,15.7366299 L13.4270957,15.7366299 Z M13.7106876,11.7346357 C13.7106876,12.9768441 12.7756427,13.9708169 11.274274,13.9708169 L11.2467575,13.9708169 C9.80119562,13.9708169 8.86666667,12.9768441 8.86666667,11.7346357 C8.86666667,10.4661526 9.82965799,9.5 11.3026504,9.5 C12.7756427,9.5 13.6827412,10.4661526 13.7106876,11.7346357 Z M28.9555136,21.2560298 L28.9553416,28.6738181 L24.6496981,28.6738181 L24.6496981,21.7524151 C24.6496981,20.0139072 24.0266215,18.8275969 22.467898,18.8275969 C21.2783256,18.8275969 20.5697758,19.6273432 20.2585815,20.3997844 C20.144732,20.676613 20.1167855,21.0623184 20.1167855,21.4489684 L20.1167855,28.6741616 L15.8104541,28.6741616 C15.8104541,28.6741616 15.8672069,16.9509322 15.8104541,15.7369734 L20.1167855,15.7369734 L20.1167855,17.5694176 C20.6882687,16.6885289 21.7117964,15.4328397 23.9979011,15.4328397 C26.8313262,15.4328397 28.9555136,17.2822851 28.9555136,21.2560298 Z" id="Shape" fill="#FFFFFF"></path>
</g>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.0 KiB

-22
View File
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="38px" height="38px" viewBox="0 0 38 38" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>Messenger</title>
<desc>Created with Sketch.</desc>
<defs>
<path d="M19,11 C14.0294275,11 10,14.7309462 10,19.3333325 C10,21.955835 11.3087455,24.295055 13.3540371,25.8226111 L13.3540371,29 L16.418455,27.3181666 C17.2362813,27.5445001 18.102685,27.6666665 19,27.6666665 C23.9705725,27.6666665 28,23.9357225 28,19.3333325 C28,14.7309462 23.9705725,11 19,11 L19,11 Z M19.8944088,22.2222238 L17.6024838,19.7777788 L13.1304348,22.2222238 L18.04969,17 L20.3975163,19.444445 L24.8136663,17 L19.8944088,22.2222238 L19.8944088,22.2222238 Z" id="path-1"></path>
</defs>
<g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Cheatsheet-Block" transform="translate(-68.000000, -227.000000)">
<g id="Social-Icons" transform="translate(20.000000, 227.000000)">
<g id="Messenger" transform="translate(48.000000, 0.000000)">
<circle id="Base" fill="#007FFF" cx="19" cy="19" r="19"></circle>
<mask id="mask-2" fill="white">
<use xlink:href="#path-1"></use>
</mask>
<use id="Clip-2" fill="#FFFFFF" xlink:href="#path-1"></use>
</g>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

-26
View File
@@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="38px" height="38px" viewBox="0 0 38 38" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>slack</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Cheatsheet-Block" transform="translate(-212.000000, -227.000000)">
<g id="Social-Icons" transform="translate(20.000000, 227.000000)">
<g id="slack" transform="translate(192.000000, 0.000000)">
<path d="M0,19 C0,8.50658923 8.37922819,0 18.7155311,0 C29.0518341,0 37.4310623,8.50658923 37.4310623,19 C37.4310623,29.4934108 29.0518341,38 18.7155311,38 C8.37922819,38 0,29.4934108 0,19 Z" id="back" fill="#FFFFFF"></path>
<g id="Group" transform="translate(8.721311, 8.866667)">
<path d="M12.9233905,1.25387541 C12.6204525,0.305827323 11.6189928,-0.21296612 10.6866498,0.0951868856 C9.75414353,0.40317377 9.24385485,1.42132459 9.54695616,2.36920656 L14.1371029,16.7273093 C14.4522956,17.6128962 15.3932986,18.1105923 16.2965568,17.8462951 C17.2387036,17.5705356 17.8130438,16.5532153 17.5123934,15.6124765 C17.5009557,15.5765946 12.9233905,1.25387541 12.9233905,1.25387541" id="Shape" fill="#DFA22F"></path>
<path d="M5.81104865,3.60331366 C5.50794732,2.6554317 4.5064875,2.13663826 3.57414459,2.44462514 C2.64163827,2.75261202 2.13134964,3.77076284 2.43445095,4.71881093 L7.02459769,19.0769137 C7.33979038,19.9625006 8.28079336,20.4601967 9.18405157,20.1957333 C10.1261983,19.9201399 10.7005386,18.9028197 10.3998882,17.9619147 C10.3884504,17.9261989 5.81104865,3.60331366 5.81104865,3.60331366" id="Shape" fill="#3CB187"></path>
<path d="M18.7011062,13.145259 C19.6336125,12.8372721 20.1437377,11.8191213 19.8407998,10.8710733 C19.5378619,9.92319128 18.536402,9.40439778 17.6040591,9.71238469 L3.48133512,14.3792 C2.61026606,14.6994798 2.12072884,15.6561661 2.38069337,16.5744787 C2.65193227,17.5323279 3.65257511,18.1162404 4.57789197,17.8105793 C4.6131857,17.7989508 18.7011062,13.145259 18.7011062,13.145259" id="Shape" fill="#CE1E5B"></path>
<path d="M6.42476754,17.2005858 C7.3440387,16.896918 8.52882987,16.5055388 9.80022141,16.0855869 C9.50153184,15.1509946 9.11656863,13.9462907 8.70333779,12.6535432 L5.3277205,13.7690404 L6.42476754,17.2005858" id="Shape" fill="#392538"></path>
<path d="M13.5372728,14.8509814 C14.8134029,14.4295344 15.9995012,14.0376568 16.9127267,13.7359826 C16.6140371,12.8013901 16.2289105,11.5963541 15.8156797,10.3032743 L12.4400623,11.4187716 L13.5372728,14.8509814" id="Shape" fill="#BB242A"></path>
<path d="M16.3901833,5.91421202 C17.3225262,5.60622514 17.8328148,4.58807432 17.5298769,3.64002623 C17.226939,2.69214426 16.2254791,2.17335082 15.2929728,2.4813377 L1.17024886,7.148153 C0.29917979,7.46843279 -0.19035743,8.4251191 0.0697704918,9.34343169 C0.340846009,10.3012809 1.34148885,10.8851934 2.26696909,10.5795323 C2.30209944,10.5679038 16.3901833,5.91421202 16.3901833,5.91421202" id="Shape" fill="#72C5CD"></path>
<path d="M4.11319108,9.96970494 C5.03246224,9.66603712 6.21758022,9.27449177 7.48913518,8.85453992 C7.07459715,7.55697486 6.68914378,6.3511082 6.39241494,5.42249617 L3.01598065,6.53815956 L4.11319108,9.96970494" id="Shape" fill="#248C73"></path>
<path d="M11.2255329,7.62026667 C12.5019898,7.19865356 13.6882515,6.80677596 14.6016404,6.50493552 C14.186939,5.20720437 13.8014856,4.00100547 13.5045934,3.07222733 L10.1283225,4.18789071 L11.2255329,7.62026667" id="Shape" fill="#62803A"></path>
</g>
</g>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 3.9 KiB

-28
View File
@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="38px" height="38px" viewBox="0 0 38 38" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>telegram</title>
<desc>Created with Sketch.</desc>
<defs>
<linearGradient x1="66.67%" y1="16.67%" x2="41.67%" y2="75%" id="linearGradient-1">
<stop stop-color="#37AEE2" offset="0%"></stop>
<stop stop-color="#1E96C8" offset="100%"></stop>
</linearGradient>
<linearGradient x1="61.2346759%" y1="43.69%" x2="74.7064382%" y2="80.24%" id="linearGradient-2">
<stop stop-color="#EFF7FC" offset="0%"></stop>
<stop stop-color="#FFFFFF" offset="100%"></stop>
</linearGradient>
</defs>
<g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Cheatsheet-Block" transform="translate(-116.000000, -227.000000)">
<g id="Social-Icons" transform="translate(20.000000, 227.000000)">
<g id="telegram" transform="translate(96.000000, 0.000000)">
<circle id="Oval" fill="url(#linearGradient-1)" cx="19" cy="19" r="19"></circle>
<path d="M15.3333333,28.1666667 C14.6854,28.1666667 14.7955,27.9220167 14.5720333,27.3050833 L12.6666667,21.0343167 L27.3333333,12.3333333" id="Shape" fill="#C8DAEA"></path>
<path d="M15.3333333,28.1666667 C15.8333333,28.1666667 16.05425,27.938 16.3333333,27.6666667 L19,25.0736667 L15.6736667,23.0678333" id="Shape" fill="#A9C9DD"></path>
<path d="M15.6733333,23.0683333 L23.7333333,29.0231667 C24.6530833,29.53065 25.3169,29.2679 25.546,28.16925 L28.8268333,12.70875 C29.1627333,11.36205 28.3134833,10.75125 27.4336,11.1507167 L8.1686,18.5792167 C6.85358333,19.1066667 6.86125,19.8403167 7.9289,20.1672167 L12.8727333,21.7102667 L24.3182333,14.4894333 C24.85855,14.1617833 25.35445,14.337935 24.9474333,14.6991667" id="Shape" fill="url(#linearGradient-2)"></path>
</g>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.1 KiB

-17
View File
@@ -1,17 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="38px" height="38px" viewBox="0 0 38 38" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 51.2 (57519) - http://www.bohemiancoding.com/sketch -->
<title>Twitter</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Symbols" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Cheatsheet-Block" transform="translate(-20.000000, -227.000000)">
<g id="Social-Icons" transform="translate(20.000000, 227.000000)">
<g id="Twitter">
<path d="M0,19 C0,8.50658923 8.50658923,0 19,0 C29.4934108,0 38,8.50658923 38,19 C38,29.4934108 29.4934108,38 19,38 C8.50658923,38 0,29.4934108 0,19 Z" id="back" fill="#55ACEE"></path>
<path d="M18.4309521,15.443438 L18.4708224,16.1008809 L17.806317,16.0203777 C15.3875175,15.711782 13.2743905,14.6652403 11.480226,12.9075869 L10.6030789,12.0354689 L10.3771471,12.6794945 C9.89870322,14.1151351 10.2043757,15.6312788 11.2011337,16.6509861 C11.732738,17.2145086 11.6131271,17.2950118 10.6961097,16.9595817 C10.3771471,16.8522441 10.0980548,16.7717409 10.0714746,16.8119925 C9.97844386,16.9059129 10.2974064,18.1268783 10.5499185,18.6098975 C10.8954613,19.2807576 11.5998369,19.9382004 12.3706632,20.3272993 L13.0218784,20.6358949 L12.2510522,20.6493121 C11.5068062,20.6493121 11.480226,20.6627293 11.5599666,20.9444905 C11.8257688,21.8166086 12.8756872,22.7423955 14.0452167,23.1449116 L14.8692033,23.4266728 L14.1515375,23.8560232 C13.088329,24.4732145 11.8390589,24.8220617 10.5897888,24.8488961 C9.99173397,24.8623133 9.5,24.9159821 9.5,24.9562337 C9.5,25.0904057 11.1213931,25.841769 12.0649907,26.1369474 C14.8957835,27.0090655 18.2581807,26.6333839 20.7833011,25.1440746 C22.5774655,24.0841156 24.37163,21.977615 25.2089068,19.9382004 C25.6607704,18.8514071 26.1126341,16.8656613 26.1126341,15.91304 C26.1126341,15.2958488 26.1525044,15.2153456 26.8967504,14.4773995 C27.3353239,14.0480491 27.7473173,13.578447 27.8270579,13.444275 C27.959959,13.1893482 27.9466689,13.1893482 27.2688734,13.4174406 C26.1392143,13.8199566 25.979733,13.7662878 26.5379175,13.1625138 C26.9499108,12.7331633 27.4416448,11.9549657 27.4416448,11.7268732 C27.4416448,11.6866216 27.2422932,11.7537076 27.0163614,11.8744624 C26.7771394,12.0086345 26.2455351,12.2098925 25.8468319,12.3306473 L25.1291661,12.5587397 L24.4779509,12.1159721 C24.119118,11.8744624 23.6140939,11.6061184 23.3482918,11.5256152 C22.6704963,11.3377744 21.6338679,11.3646088 21.022523,11.579284 C19.3612596,12.1830581 18.3113411,13.7394534 18.4309521,15.443438 Z" id="Shape" fill="#FFFFFF"></path>
</g>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.7 KiB

-10
View File
File diff suppressed because one or more lines are too long
+400
View File
@@ -0,0 +1,400 @@
CHEATSHEET C#
1. Data Types
Primitive Size Example
String 2 bytes/char s = "reference";
bool b = true;
char 2 bytes ch = 'a';
byte 1 byte b = 0x78;
short 2 bytes val = 70;
int 4 bytes val = 700;
long 8 bytes val = 70;
float 4 bytes val = 70.0F;
double 8 bytes val = 70.0D;
decimal 16 bytes val = 70.0M;
2. Arrays
2.1 Declaration
//Initiliazed using a list defined with curly braces
int[] nameArray = {100, 101, 102};
//Define an empty array
int[] nameArray = new int[3]; // 3 rows and 2 columns
//To access a specific item in the array
int[] nameArray = new int[10];
int firstNumber = nameArray[0];
nameArray[1] = 20;
//Multidimensional arrays
int [,] matrix = new int [2,2]
matrix[0,0] = 1;
matrix[0,1] = 2;
matrix[1,0] = 3;
matrix[1,1] = 4;
int[,] predefinedMatrix = new int[2,2] { { 1, 2 }, { 3, 4 } };
2.2 Array Operations
//Sort ascending
Array.Sort(nameArray);
//Sort begins at element 6 and sorts 20 elements
Array.Sort(nameArray,6,20);
//Use 1 array as a key & sort 2 arrays
string[] values = {"Juan", "Victor", "Elena"};
string[] keys = {"Jimenez", "Martin", "Ortiz"};
Array.Sort(keys, values);
//Clear elements in array (array, first element, # elements)
Array.Clear(nameArray, 0, nameArray.Length);
//Copy elements from one array to another
Array.Copy(scr, target, numOfElements);
3. String Operations
//To concatenate between strings, use the plus operator:
string firstName = "Erin";
string lastName = "Roger";
string fullName = firstName + " " + lastName;
//To add one string to another, use the += operator:
string secondLastName = "Green";
string fullName += secondLastName;
//ToString function
//It converts an object to its string representation so that it is suitable for display
Object.ToString();
//String formatting
//Each additional argument to the function can be referred to in the string using the brackets operator with the index number.
String.Format(String format, Object arg0);
format - A composite format string that includes one or more format items
arg0 - The first or only object to format
//Substring
//Returns a part of the string, beginning from the index specified as the argument. Substring also accepts a maximum length for the substring
String.Substring(beginAt);
String.Substring(beginAt, maximum);
//Replace
string newStr = oldStr.Replace("old","new");
//IndexOf
//Finds the first ocurrence of a string in a larger string
//Returns -1 if the string is not found
String.IndexOf(val, start, num)
val - string to search for
start - where to begin in string
//LastIndexOf
//Search from end of string
//Split
//Split is used to break delimited string into substrings
String.Split(Char[]);
//ToCharArray
//Places selected characteres in a string in a char array
String str = "AaBbCcDd";
//create array of 8 vowels
var chars = str.ToCharArray();
//create array of 'B' and 'C'
var chars = str.ToCharArray(2,2);
4. System.Text.StringBuilder
4.1 Constructor
StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder(myString);
StringBuilder sb = new StringBuilder(myString, capacity);
myString - Initial value of StringBuilder object
capacity - Initial size of buffer
5. DateTime
5.1 DateTime Constructor
DateTime(year, month, day)
DateTime(year, month, day, hour, minute, second)
DateTime newYear = DateTime.Parse("1/1/2018"):
DateTime currentDate = DateTime.Now;
DateTime nextYear = DateTime.AddYears(1);
6. TimeSpan
6.1 TimeSpan Constructor
TimpeSpan(hour, minute, sec)
TimeSpan timeS = new TimeSpan(10, 14, 50);
TimeSpan timeS_Hours = TimeSpan.FromDays(3640);
7. Formatting Values
Format item syntax: {index[,alignment][:format string]}
index - Specifies element in list of values to which format is applied
aligment - Indicates minimun width (in characters) to display value
format string - Contains the code which specififes the format of the displayed value
7.1 Numeric
Format Name Pattern Value Result
C or c Currency {0:C2}, 1000.1 $ 1000.1 A currency value
D or d Decimal {0:D5}, 30 00030 Integer digits with optional negative sign
E or e Exponential {0,9:E2}, 120.2 1.20+E002 Exponential notation
F or f Fixed-point {0,9:F2}, 120.2 120.2 Integral and decimal digits with optional negative sign
G or g General {0,9:G2}, 120.2 120.2 The more compact of either fixed-point or scientific notation
N or n Number {0,9:N1}, 1300.5 1,300,5 Integral and decimal digits, group separators, and a decimal separator with optional negative sign
P or p Percent {0,9:P3}, .0903 9.03% Number multiplied by 100 and displayed with a percent symbol
R or r Round-trip {0,9:R}, 3.1416 3.1316 A string that can round-trip to an identical number
X or x Hexadecimal {0,9:X4}, 31 001f A hexadecimal string
8. C# compiler at the Command Line
csc File.cs -> Compiles File.cs producing File.exe
csc -target:library File.cs -> Compiles File.cs producing File.dll
csc -out:My.exe File.cs -> Compiles File.cs and creates My.exe
csc -define:DEBUG -optimize -out:File2.exe *.cs -> Compiles all the C# files in the current directory with optimizations enabled and defines the DEBUG symbol. The output is File2.exe
csc -target:library -out:File2.dll -warn:0 -nologo -debug *.cs -> Compiles all the C# files in the current directory producing a debug version of File2.dll. No logo and no warnings are displayed
csc -target:library -out:Something.xyz *.cs -> Compiles all the C# files in the current directory to Something.xyz (a DLL)
8.1 Compiler Options Listed
Option Purpose
@ Reads a response file for more options.
-? Displays a usage message to stdout.
-additionalfile Names additional files that don't directly affect code generation but may be used by analyzers for producing errors or warnings.
-addmodule Links the specified modules into this assembly
-analyzer Run the analyzers from this assembly (Short form: -a)
-appconfig Specifies the location of app.config at assembly binding time.
-baseaddress Specifies the base address for the library to be built.
-bugreport Creates a 'Bug Report' file. This file will be sent together with any crash information if it is used with -errorreport:prompt or -errorreport:send.
-checked Causes the compiler to generate overflow checks.
-checksumalgorithm:<alg> Specifies the algorithm for calculating the source file checksum stored in PDB. Supported values are: SHA1 (default) or SHA256.
-codepage Specifies the codepage to use when opening source files.
-debug Emits debugging information.
-define Defines conditional compilation symbols.
-delaysign Delay-signs the assembly by using only the public part of the strong name key.
-deterministic Causes the compiler to output an assembly whose binary content is identical across compilations if inputs are identical.
-doc Specifies an XML Documentation file to generate.
-errorreport Specifies how to handle internal compiler errors: prompt, send, or none. The default is none.
-filealign Specifies the alignment used for output file sections.
-fullpaths Causes the compiler to generate fully qualified paths.
-help Displays a usage message to stdout.
-highentropyva Specifies that high entropy ASLR is supported.
-incremental Enables incremental compilation [obsolete].
-keycontainer Specifies a strong name key container.
-keyfile Specifies a strong name key file.
-langversion:<string> Specify language version: Default, ISO-1, ISO-2, 3, 4, 5, 6, 7, 7.1, 7.2, 7.3, or Latest
-lib Specifies additional directories in which to search for references.
-link Makes COM type information in specified assemblies available to the project.
-linkresource Links the specified resource to this assembly.
-main Specifies the type that contains the entry point (ignore all other possible entry points).
-moduleassemblyname Specifies an assembly whose non-public types a .netmodule can access.
-modulename:<string> Specify the name of the source module.
-noconfig Instructs the compiler not to auto include CSC.RSP file.
-nologo Suppresses compiler copyright message.
-nostdlib Instructs the compiler not to reference standard library (mscorlib.dll).
-nowarn Disables specific warning messages
-nowin32manifest Instructs the compiler not to embed an application manifest in the executable file.
-optimize Enables/disables optimizations.
-out Specifies the output file name (default: base name of file with main class or first file).
-parallel[+|-] Specifies whether to use concurrent build (+).
-pathmap Specifies a mapping for source path names output by the compiler.
-pdb Specifies the file name and location of the .pdb file.
-platform Limits which platforms this code can run on: x86, Itanium, x64, anycpu, or anycpu32bitpreferred. The default is anycpu.
-preferreduilang Specifies the language to be used for compiler output.
-publicsign Apply a public key without signing the assembly, but set the bit in the assembly indicating the assembly is signed.
-recurse Includes all files in the current directory and subdirectories according to the wildcard specifications.
-reference References metadata from the specified assembly files.
-refout Generate a reference assembly in addition to the primary assembly.
-refonly Generate a reference assembly instead of a primary assembly.
-resource Embeds the specified resource.
-ruleset:<file> Specify a ruleset file that disables specific diagnostics.
-subsystemversion Specifies the minimum version of the subsystem that the executable file can use.
-target Specifies the format of the output file by using one of four options: -target:appcontainerexe, -target:exe, -target:library, -target:module, -target:winexe, -target:winmdobj.
-unsafe Allows unsafe code.
-utf8output Outputs compiler messages in UTF-8 encoding.
-warn Sets the warning level (0-4).
-warnaserror Reports specific warnings as errors.
-win32icon Uses this icon for the output.
-win32manifest Specifies a custom win32 manifest file.
-win32res Specifies the win32 resource file (.res).
9. Control flow statements
9.1 Switch
switch (expression) {
//expression may be integer, string or enum
case expression:
//statements
break/ goto / return()
case ..
default
//statements
break/ goto / return()
}
9.2 If
if (condition) {
//statements
} else {
//statements
}
10. Loop
10.1 While
while (condition) {body}
10.2 Do while
do {body} while condition;
10.3 For
for (initializer; termination condition; iteration;) {
//statements
}
10.4 For each
foreach (type identifier in collection) {
//statements
}
11. Class Definition
11.1 Class
public | protected | internal | private
abstract | sealed | static
class className [:class/interfaces inherited from]
11.2 Constructor
[access modifier] className (parameters) [:initializer]
initializer -base calls constructor in base class.
this calls constuctor within class.
public class nameClass : Initializer {
public className(dataType param1 , dataType param2, ...) : base(param1, param2)
{ constructor body }
}
11.3 Method
[access modifier]
static | virtual | override | new | sealed | abstract
methodName (parameter list) { body }
virtual method can be overridden in subclass
override overrides virtual method in base class
new hides non-virtual method in base class
sealed prevents derived class from inheriting
abstract must be implemented by subclass
Passing parameters:
1. By default, parametres are passed by value
2. Passing by reference: ref, in and out modifers
To pass a parameter by reference with the intent of changing the value, use the ref, or out keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in modifier
11.4 Property
[modifier] <dataType> property name{
public string BrandName
{
get { return brandName; }
set { brandName = value; }
}
}
12. Struct
12.1 Defining a structure
[attribute][modifier] struct name [:interfaces] { struct-body }
12.2 Class vs Structure
-> Classes are reference types and structs are value types
-> Structures do not support inheritance
-> Structures cannot have default constructor
13. Enum
13.1 Declaring enum variable
enum <enumName> {
enumeration list
};
enumName - Specifies the enumeration type name
enumeration list is a comma-separated list of identifiers
//Each of the symbols in the enumeration list stands for an integer value, one greater than the symbol that precedes it.
14. Delegates
//A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
14.1 Declaring delegates
//Delegate declaration determines the methods that can be referenced by the delegate.
delegate <return type> <delegate-name> <parameter list>
14.2 Instantiating delegates
//When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method
public delegate void printString(string s);
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
15. Events
15.1 Declaring events
//To declare an event inside a class, first a delegate type for the event must be declared.
public delegate string MyDelegate(string str);
//The event itself is declared by using the event keyword
event MyDelegate MyEvent;
15.2 Commonly used Control Events
Event Delegate
Click, MouseEnter, DoubleClick, MouseLeave EventHandler( object sender, EventArgs e)
MouseDown, Mouseup, MouseMove MouseEventHandler(object sender, MouseEventArgs e)
e.X, e.Y x and y coordinates
e.Button MouseButton.Left, Middle, Right
KeyUp, KeyDown KeyEventHandler(object sndr, KeyEventArgs e)
e.Handled Indicates whether event is handled.
e.KeyCode Keys enumeration, e.g., Keys.V
e.Modifiers Indicates if Alt, Ctrl, or Shift key.
KeyPress KeyPressEventHandler(object sender, KeyPressEventArgs e)
+242
View File
@@ -0,0 +1,242 @@
main() Function
* The main() function is the starting point of the program: int main (int argc, char *argv[])
* The return type of the main() function is an integer (type int) and it is known as the return value of the program.
* As a rule of thumb, value 0 means success while non-zero means an error conditions.
Include Files
* The purpose of these files is to tell the compiler about the existence of external functions which the source code will make use of.
Preprocessor directives:
#include "mine.h" search current working directory first
#include <stdio.h> search command line directory then system
#define TRUE 1 macro substitution, usually use capitals
#define min(a,b) (a<b)?(a):(b) macro substitution with parameters
#define abs(a) (a<0)?(-(a)):(a) macro substitution
#define note /* comment */ this comment gets inserted every time note appears */
backslash \ at end of a line means continue
#undef TRUE undefines a previously defined macroname
#error stop compiling at this point
#if expression conditional compilation, start if structure
#elif expression else if expression != 0 compile following code
#else else compile following code
#endif end of conditional compiling
#ifdef macroname like #if, compiles if macroname defined
#ifndef like #if, compiles if macroname undefined
#line number [filename] set origin for __LINE__ and __FILE__
#pragma gives the compiler commands
Create and execute a program
In Linux systems:
1. Open up a terminal
2. Create the program: nano nameProgram.c
3. Write the program and save it
4. gcc -o nameExecutable nameProgram.c
32 Reserved words
Term Description
auto optional local declaration
break used to exit loop and used to exit switch
case choice in a switch
char basic declaration of a type character
const prefix declaration meaning variable can not be changed
continue go to bottom of loop in for, while and do loops
default optional last case of a switch
do executable statement, do-while loop
double basic declaration double precision floating point
else executable statement, part of "if" structure
enum basic declaration of enumeration type
extern prefix declaration meaning variable is defined externally
float basic declaration of floating point
for executable statement, for loop
goto jump within function to a label
if executable statement
int basic declaration of integer
long prefix declaration applying to many types
register prefix declaration meaning keep variable in register
return executable statement with or without a value
short prefix declaration applying to many types
signed prefix declaration applying to some types
sizeof operator applying to variables and types, gives size in bytes
static prefix declaration to make local variable static
struct declaration of a structure, like a record
switch executable statement for cases
typedef creates a new type name for an existing type
union declaration of variables that are in the same memory locations
unsigned prefix declaration applying to some types
void declaration of a typeless variable
volatile prefix declaration meaning the variable can be changed at any time
while executable statement, while loop or do-while loop
Basic types
Type Description
char character type, usually one byte ( a string is array of char )
int integer type, usually 2 or 4 bytes ( default )
float floating point type, usually 4 bytes
double floating point type, usually 8 bytes
void no type, typeless
enum enumeration type ( user defines the type name )
Type modifiers, prefix for basic types
Modifiers Description
signed has a sign ( default )
unsigned no sign bit in variable
long longer version of type (short or long alone means short int or
short shorter version of type long int because int is the default)
const variable can not be stored into
Storage Types
Prefix Description
auto local variable ( default )
static permanent when function exits, not auto
volatile can change from outside influence
extern variables are defined elsewhere, externally
register assign variable to register
Operators
( ) grouping parenthesis, function call
[ ] array indexing, also [ ][ ] etc.
-> selector, structure pointer
. select structure element
! relational not, complement, ! a yields true or false
~ bitwise not, ones complement, ~ a
++ increment, pre or post to a variable
-- decrement, pre or post to a variable
- unary minus, - a
+ unary plus, + a
* indirect, the value of a pointer, * p is value at pointer p address
& the memory address, & b is the memory address of variable b
sizeof size in bytes, sizeof a or sizeof (int)
(type) a cast, explicit type conversion, (float) i, (*fun)(a,b), (int*)x
* multiply, a * b
/ divide, a / b
% modulo, a % b
+ add, a + b
- subtract, a - b
<< shift left, left operand is shifted left by right operand bits
>> shift right, left operand is shifted right by right operand bits
< less than, result is true or false, a %lt; b
<= less than or equal, result is true or false, a <= b
> greater than, result is true or false, a > b
>= greater than or equal, result is true or false, a >= b
== equal, result is true or false, a == b
!= not equal, result is true or false, a != b
& bitwise and, a & b
^ bitwise exclusive or, a ^ b
| bitwise or, a | b
&& relational and, result is true or false, a < b && c >= d
|| relational or, result is true or false, a < b || c >= d
? exp1 ? exp2 : exp3 result is exp2 if exp1 != 0, else result is exp3
= store
+= add and store
-= subtract and store
*= multiply and store
/= divide and store
%= modulo and store
<<= shift left and store
>>= shift right and store
&= bitwise and and store
^= bitwise exclusive or and store
|= bitwise or and store
, separator as in ( y=x,z=++x )
; statement terminator.
Operator precedence
More precedence
LR ( ) [ ] -> . x++ x--
RL ! ~ - + ++x --x * & sizeof (type)
LR * / %
LR + -
LR << >>
LR < <= > >=
LR == !=
LR &
LR ^
LR |
LR &&
LR ||
RL ? :
RL = += -= *= /= %= >>= <<= &= ^= |=
LR ,
Less precedence
Conditional branching
if ( condition ) statement ;
else statement_2 ; /* optional else clause */
Switch statement
switch ( expression ) /* constants must be unique */
{
case constant_1: /* do nothing for this case */
break;
case constant_2: /* drop through and do same as constant_3*/
case constant_3:
statement_sequence /* can have but does not need { } */
break;
case constant_4:
statement_sequence /* does this and next */
/* statement_sequence also*/
case constant_5:
statement_sequence
break;
default: /* default executes if no constant equals*/
statement_sequence /* the expression. This is optional */
}
Function definition
type function_name(int a, float b, const char * ch,...) { function_body }
/* only parameters passed by address can are modified*/
/* in the calling function, local copy can be modified*/
char * strcpy( char * s1, const char * s2 ) { statements }
Declarations forms
basic_type variable;
type variable[val][val]...[val]={data,data,...}; /*multidimensional array*/
struct struct_name { /* struct_name is optional */
type variable_1; /* any declaration */
… /* all variable names must be unique*/
} variable_1, ... ; /* variables are optional */
struct struct_name { /* struct_name is optional */
type variable_1: length; /* any declaration : length in bits */
... /* type is int, unsigned or signed */
} variable_1, ... ; /* variables are optional, they can also be arrays and pointers */
union union_name { /* union_name is optional */
type variable_1; /* variable_1 overlays variable_2 */
type variable_2;
...
} variable_a, ...; /* variables are optional */
enum enum_type /* enum_name is optional */
{ enumeration_name_1, /* establishes enumeration literals */
enumeration_name_2=number,/* optional number, */
... /* default is 0, 1, 2, ... */
} variable, ...; /* variables are optional */
/* use dot notation to select a component of a struct or union */
+62
View File
@@ -0,0 +1,62 @@
> announcement: this doc is a quiz-, interview-oriented cheatsheet, which desigend for those who want to have an overview of XML, when preparing for interviews.
# What is XML
XML stands for eXtensible Markup Language, XML was designed to store and transport data. XML is often used for distributing data over the Internet(especial in web development).
# Then how can XML store data
XML uses a DTD to describe the data.
# The relation with HTML
* XML: is used to store or transport data.
So the XML is a **Complement** to HTML.
* HTML: is used to format and display the same data.
XML does not carry any information about how to be displayed. The same XML data can be used in many different presentation scenarios.
Because of this, with XML, there is a full separation between data and presentation.
# What is XML Schema/DTD
The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements:
# When Not to Use a XML DTD/Sschema
XML does not require a DTD/Schema.
When you are experimenting with XML, or when you are working with small XML files, creating DTDs may be a waste of time.
If you develop applications, wait until the specification is stable before you add a document definition. Otherwise, your software might stop working because of validation errors.
# XML Syntax
The XML language has no predefined tags, but the syntax is rather logic and easy to learn. XML documents must contain one root element that is the parent of all other elements.
```
<bookstore>
<book category="children">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
```
1. XML Tags are Case Sensitive
2. All XML Elements Must Have a Closeing Tag
```
<p>This is a paragraph.</p>
<br /> <!-- This is a self closing -->
```
3. XML Attribute Values Must Always be Quoted
4. Pay attention to the name rules.
# Reference
1. (W3School) [https://www.w3schools.com/xml/]
2. [cheat sheet in German](https://www.i-d-e.de/wp-content/uploads/2015/02/ide-xml-kurzreferenz.pdf)
+571
View File
@@ -0,0 +1,571 @@
#!/bin/bash
##############################################################################
# SHORTCUTS and HISTORY
##############################################################################
CTRL+A # move to beginning of line
CTRL+B # moves backward one character
CTRL+C # halts the current command
CTRL+D # deletes one character backward or logs out of current session, similar to exit
CTRL+E # moves to end of line
CTRL+F # moves forward one character
CTRL+G # aborts the current editing command and ring the terminal bell
CTRL+H # deletes one character under cursor (same as DELETE)
CTRL+J # same as RETURN
CTRL+K # deletes (kill) forward to end of line
CTRL+L # clears screen and redisplay the line
CTRL+M # same as RETURN
CTRL+N # next line in command history
CTRL+O # same as RETURN, then displays next line in history file
CTRL+P # previous line in command history
CTRL+Q # resumes suspended shell output
CTRL+R # searches backward
CTRL+S # searches forward or suspends shell output
CTRL+T # transposes two characters
CTRL+U # kills backward from point to the beginning of line
CTRL+V # makes the next character typed verbatim
CTRL+W # kills the word behind the cursor
CTRL+X # lists the possible filename completions of the current word
CTRL+Y # retrieves (yank) last item killed
CTRL+Z # stops the current command, resume with fg in the foreground or bg in the background
ALT+B # moves backward one word
ALT+D # deletes next word
ALT+F # moves forward one word
ALT+H # deletes one character backward
ALT+T # transposes two words
ALT+. # pastes last word from the last command. Pressing it repeatedly traverses through command history.
ALT+U # capitalizes every character from the current cursor position to the end of the word
ALT+L # uncapitalizes every character from the current cursor position to the end of the word
ALT+C # capitalizes the letter under the cursor. The cursor then moves to the end of the word.
ALT+R # reverts any changes to a command youve pulled from your history if youve edited it.
ALT+? # list possible completions to what is typed
ALT+^ # expand line to most recent match from history
CTRL+X then ( # start recording a keyboard macro
CTRL+X then ) # finish recording keyboard macro
CTRL+X then E # recall last recorded keyboard macro
CTRL+X then CTRL+E # invoke text editor (specified by $EDITOR) on current command line then execute resultes as shell commands
CTRL+A then D # logout from screen but don't kill it, if any command exist, it will continue
BACKSPACE # deletes one character backward
DELETE # deletes one character under cursor
history # shows command line history
!! # repeats the last command
!<n> # refers to command line 'n'
!<string> # refers to command starting with 'string'
esc :wq # exits and saves script
exit # logs out of current session
##############################################################################
# BASH BASICS
##############################################################################
env # displays all environment variables
echo $SHELL # displays the shell you're using
echo $BASH_VERSION # displays bash version
bash # if you want to use bash (type exit to go back to your previously opened shell)
whereis bash # locates the binary, source and manual-page for a command
which bash # finds out which program is executed as 'bash' (default: /bin/bash, can change across environments)
clear # clears content on window (hide displayed lines)
##############################################################################
# FILE COMMANDS
##############################################################################
ls # lists your files in current directory, ls <dir> to print files in a specific directory
ls -l # lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified
ls -a # lists all files in 'long format', including hidden files (name beginning with '.')
ln -s <filename> <link> # creates symbolic link to file
readlink <filename> # shows where a symbolic links points to
tree # show directories and subdirectories in easilly readable file tree
mc # terminal file explorer (alternative to ncdu)
touch <filename> # creates or updates (edit) your file
mktemp -t <filename> # make a temp file in /tmp/ which is deleted at next boot (-d to make directory)
cat <filename> # displays file raw content (will not be interpreted)
cat -n <filename> # shows number of lines
nl <file.sh> # shows number of lines in file
cat filename1 > filename2 # Copy filename1 to filename2
cat filename1 >> filename2 # merge two files texts together
any_command > <filename> # '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout)
more <filename> # shows the first part of a file (move with space and type q to quit)
head <filename> # outputs the first lines of file (default: 10 lines)
tail <filename> # outputs the last lines of file (useful with -f option) (default: 10 lines)
vim <filename> # opens a file in VIM (VI iMproved) text editor, will create it if it doesn't exist
mv <filename1> <dest> # moves a file to destination, behavior will change based on 'dest' type (dir: file is placed into dir; file: file will replace dest (tip: useful for renaming))
cp <filename1> <dest> # copies a file
rm <filename> # removes a file
find . -name <name> <type> # searches for a file or a directory in the current directory and all its sub-directories by its name
diff <filename1> <filename2> # compares files, and shows where they differ
wc <filename> # tells you how many lines, words and characters there are in a file. Use -lwc (lines, word, character) to ouput only 1 of those informations
sort <filename> # sorts the contents of a text file line by line in alphabetical order, use -n for numeric sort and -r for reversing order.
sort -t -k <filename> # sorts the contents on specific sort key field starting from 1, using the field separator t.
rev # reverse string characters (hello becomes olleh)
chmod -options <filename> # lets you change the read, write, and execute permissions on your files (more infos: SUID, GUID)
gzip <filename> # compresses files using gzip algorithm
gunzip <filename> # uncompresses files compressed by gzip
gzcat <filename> # lets you look at gzipped file without actually having to gunzip it
lpr <filename> # prints the file
lpq # checks out the printer queue
lprm <jobnumber> # removes something from the printer queue
genscript # converts plain text files into postscript for printing and gives you some options for formatting
dvips <filename> # prints .dvi files (i.e. files produced by LaTeX)
grep <pattern> <filenames> # looks for the string in the files
grep -r <pattern> <dir> # search recursively for pattern in directory
head -n file_name | tail +n # Print nth line from file.
head -y lines.txt | tail +x # want to display all the lines from x to y. This includes the xth and yth lines.
sed 's/<pattern>/<replacement>/g' <filename> # replace pattern in file with replacement value to std output the character after s (/) is the delimeter
sed -i 's/<pattern>/<replacement>/g' <filename> # replace pattern in file with replacement value in place
echo "this" | sed 's/is/at/g' # replace pattern from input stream with replacement value
##############################################################################
# DIRECTORY COMMANDS
##############################################################################
mkdir <dirname> # makes a new directory
rmdir <dirname> # remove an empty directory
rmdir -rf <dirname> # remove a non-empty directory
mv <dir1> <dir2> # rename a directory from <dir1> to <dir2>
cd # changes to home
cd .. # changes to the parent directory
cd <dirname> # changes directory
cp -r <dir1> <dir2> # copy <dir1> into <dir2> including sub-directories
pwd # tells you where you currently are
cd ~ # changes to home.
cd - # changes to previous working directory
##############################################################################
# SSH, SYSTEM INFO & NETWORK COMMANDS
##############################################################################
ssh user@host # connects to host as user
ssh -p <port> user@host # connects to host on specified port as user
ssh-copy-id user@host # adds your ssh key to host for user to enable a keyed or passwordless login
whoami # returns your username
su <user> # switch to a different user
su - # switch to root, likely needs to be sudo su -
sudo <command> # execute command as the root user
passwd # lets you change your password
quota -v # shows what your disk quota is
date # shows the current date and time
cal # shows the month's calendar
uptime # shows current uptime
w # displays whois online
finger <user> # displays information about user
uname -a # shows kernel information
man <command> # shows the manual for specified command
info <command> # shows another documentation system for the specific command
help # shows documentation about built-in commands and functions
df # shows disk usage
du <filename> # shows the disk usage of the files and directories in filename (du -s give only a total)
resize2fs # ext2/ext3/ext4 file system resizer
last <yourUsername> # lists your last logins
ps -u yourusername # lists your processes
kill <PID> # kills the processes with the ID you gave
killall <processname> # kill all processes with the name
top # displays your currently active processes
lsof # lists open files
bg # lists stopped or background jobs ; resume a stopped job in the background
fg # brings the most recent job in the foreground
fg <job> # brings job to the foreground
ping <host> # pings host and outputs results
whois <domain> # gets whois information for domain
dig <domain> # gets DNS information for domain
dig -x <host> # reverses lookup host
wget <file> # downloads file
netstat # Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships
time <command> # report time consumed by command execution
##############################################################################
# VARIABLES
##############################################################################
varname=value # defines a variable
varname=value command # defines a variable to be in the environment of a particular subprocess
echo $varname # checks a variable's value
echo $$ # prints process ID of the current shell
echo $! # prints process ID of the most recently invoked background job
echo $? # displays the exit status of the last command
read <varname> # reads a string from the input and assigns it to a variable
read -p "prompt" <varname> # same as above but outputs a prompt to ask user for value
column -t <filename> # display info in pretty columns (often used with pipe)
let <varname> = <equation> # performs mathematical calculation using operators like +, -, *, /, %
export VARNAME=value # defines an environment variable (will be available in subprocesses)
export -f <funcname> # Exports function 'funcname'
export var1="var1 value" # Export and assign in the same statement
export <varname> # Copy Bash variable
declare -x <varname> # Copy Bash variable
array[0]=valA # how to define an array
array[1]=valB
array[2]=valC
array=([2]=valC [0]=valA [1]=valB) # another way
array=(valA valB valC) # and another
${array[i]} # displays array's value for this index. If no index is supplied, array element 0 is assumed
${#array[i]} # to find out the length of any element in the array
${#array[@]} # to find out how many values there are in the array
declare -a # the variables are treated as arrays
declare -f # uses function names only
declare -F # displays function names without definitions
declare -i # the variables are treated as integers
declare -r # makes the variables read-only
declare -x # marks the variables for export via the environment
declare -l # uppercase values in the variable are converted to lowercase
declare -A # makes it an associative array
${varname:-word} # if varname exists and isn't null, return its value; otherwise return word
${varname:word} # if varname exists and isn't null, return its value; otherwise return word
${varname:=word} # if varname exists and isn't null, return its value; otherwise set it word and then return its value
${varname:?message} # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script
${varname:+word} # if varname exists and isn't null, return word; otherwise return null
${varname:offset:length} # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters
${variable#pattern} # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest
${variable##pattern} # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest
${variable%pattern} # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest
${variable%%pattern} # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest
${variable/pattern/string} # the longest match to pattern in variable is replaced by string. Only the first match is replaced
${variable//pattern/string} # the longest match to pattern in variable is replaced by string. All matches are replaced
${#varname} # returns the length of the value of the variable as a character string
*(patternlist) # matches zero or more occurrences of the given patterns
+(patternlist) # matches one or more occurrences of the given patterns
?(patternlist) # matches zero or one occurrence of the given patterns
@(patternlist) # matches exactly one of the given patterns
!(patternlist) # matches anything except one of the given patterns
$(UNIX command) # command substitution: runs the command and returns standard output
typeset -l <x> # makes variable local - <x> must be an interger
##############################################################################
# FUNCTIONS
##############################################################################
# The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth.
# $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters.
function functname() {
shell commands
}
unset -f functname # deletes a function definition
declare -f # displays all defined functions in your login session
##############################################################################
# FLOW CONTROLS
##############################################################################
statement1 && statement2 # and operator
statement1 || statement2 # or operator
-a # and operator inside a test conditional expression
-o # or operator inside a test conditional expression
# STRINGS
str1 == str2 # str1 matches str2
str1 != str2 # str1 does not match str2
str1 < str2 # str1 is less than str2 (alphabetically)
str1 > str2 # str1 is greater than str2 (alphabetically)
str1 \> str2 # str1 is sorted after str2
str1 \< str2 # str1 is sorted before str2
-n str1 # str1 is not null (has length greater than 0)
-z str1 # str1 is null (has length 0)
# FILES
-a file # file exists or its compilation is successful
-d file # file exists and is a directory
-e file # file exists; same -a
-f file # file exists and is a regular file (i.e., not a directory or other special type of file)
-r file # you have read permission
-s file # file exists and is not empty
-w file # your have write permission
-x file # you have execute permission on file, or directory search permission if it is a directory
-N file # file was modified since it was last read
-O file # you own file
-G file # file's group ID matches yours (or one of yours, if you are in multiple groups)
file1 -nt file2 # file1 is newer than file2
file1 -ot file2 # file1 is older than file2
# NUMBERS
-lt # less than
-le # less than or equal
-eq # equal
-ge # greater than or equal
-gt # greater than
-ne # not equal
if condition
then
statements
[elif condition
then statements...]
[else
statements]
fi
for x in {1..10}
do
statements
done
for name [in list]
do
statements that can use $name
done
for (( initialisation ; ending condition ; update ))
do
statements...
done
case expression in
pattern1 )
statements ;;
pattern2 )
statements ;;
esac
select name [in list]
do
statements that can use $name
done
while condition; do
statements
done
until condition; do
statements
done
##############################################################################
# COMMAND-LINE PROCESSING CYCLE
##############################################################################
# The default order for command lookup is functions, followed by built-ins, with scripts and executables last.
# There are three built-ins that you can use to override this order: `command`, `builtin` and `enable`.
command # removes alias and function lookup. Only built-ins and commands found in the search path are executed
builtin # looks up only built-in commands, ignoring functions and commands found in PATH
enable # enables and disables shell built-ins
eval # takes arguments and run them through the command-line processing steps all over again
##############################################################################
# INPUT/OUTPUT REDIRECTORS
##############################################################################
cmd1|cmd2 # pipe; takes standard output of cmd1 as standard input to cmd2
< file # takes standard input from file
> file # directs standard output to file
>> file # directs standard output to file; append to file if it already exists
>|file # forces standard output to file even if noclobber is set
n>|file # forces output to file from file descriptor n even if noclobber is set
<> file # uses file as both standard input and standard output
n<>file # uses file as both input and output for file descriptor n
n>file # directs file descriptor n to file
n<file # takes file descriptor n from file
n>>file # directs file description n to file; append to file if it already exists
n>& # duplicates standard output to file descriptor n
n<& # duplicates standard input from file descriptor n
n>&m # file descriptor n is made to be a copy of the output file descriptor
n<&m # file descriptor n is made to be a copy of the input file descriptor
&>file # directs standard output and standard error to file
<&- # closes the standard input
>&- # closes the standard output
n>&- # closes the ouput from file descriptor n
n<&- # closes the input from file descriptor n
|tee <file># output command to both terminal and a file (-a to append to file)
##############################################################################
# PROCESS HANDLING
##############################################################################
# To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y.
# This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal.
# Of course, to interrupt a job, type CTRL+C.
myCommand & # runs job in the background and prompts back the shell
jobs # lists all jobs (use with -l to see associated PID)
fg # brings a background job into the foreground
fg %+ # brings most recently invoked background job
fg %- # brings second most recently invoked background job
fg %N # brings job number N
fg %string # brings job whose command begins with string
fg %?string # brings job whose command contains string
kill -l # returns a list of all signals on the system, by name and number
kill PID # terminates process with specified PID
kill -s SIGKILL 4500 # sends a signal to force or terminate the process
kill -15 913 # Ending PID 913 process with signal 15 (TERM)
kill %1 # Where %1 is the number of job as read from 'jobs' command.
ps # prints a line of information about the current running login shell and any processes running under it
ps -a # selects all processes with a tty except session leaders
trap cmd sig1 sig2 # executes a command when a signal is received by the script
trap "" sig1 sig2 # ignores that signals
trap - sig1 sig2 # resets the action taken when the signal is received to the default
disown <PID|JID> # removes the process from the list of jobs
wait # waits until all background jobs have finished
sleep <number> # wait # of seconds before continuing
pv # display progress bar for data handling commands. often used with pipe like |pv
yes # give yes response everytime an input is requested from script/process
##############################################################################
# TIPS & TRICKS
##############################################################################
# set an alias
cd; nano .bash_profile
> alias gentlenode='ssh admin@gentlenode.com -p 3404' # add your alias in .bash_profile
# to quickly go to a specific directory
cd; nano .bashrc
> shopt -s cdable_vars
> export websites="/Users/mac/Documents/websites"
source .bashrc
cd $websites
##############################################################################
# DEBUGGING SHELL PROGRAMS
##############################################################################
bash -n scriptname # don't run commands; check for syntax errors only
set -o noexec # alternative (set option in script)
bash -v scriptname # echo commands before running them
set -o verbose # alternative (set option in script)
bash -x scriptname # echo commands after command-line processing
set -o xtrace # alternative (set option in script)
trap 'echo $varname' EXIT # useful when you want to print out the values of variables at the point that your script exits
function errtrap {
es=$?
echo "ERROR line $1: Command exited with status $es."
}
trap 'errtrap $LINENO' ERR # is run whenever a command in the surrounding script or function exits with non-zero status
function dbgtrap {
echo "badvar is $badvar"
}
trap dbgtrap DEBUG # causes the trap code to be executed before every statement in a function or script
# ...section of code in which the problem occurs...
trap - DEBUG # turn off the DEBUG trap
function returntrap {
echo "A return occurred"
}
trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing
##############################################################################
# COLORS AND BACKGROUNDS
##############################################################################
# note: \e or \x1B also work instead of \033
# Reset
Color_Off='\033[0m' # Text Reset
# Regular Colors
Black='\033[0;30m' # Black
Red='\033[0;31m' # Red
Green='\033[0;32m' # Green
Yellow='\033[0;33m' # Yellow
Blue='\033[0;34m' # Blue
Purple='\033[0;35m' # Purple
Cyan='\033[0;36m' # Cyan
White='\033[0;97m' # White
# Additional colors
LGrey='\033[0;37m' # Ligth Gray
DGrey='\033[0;90m' # Dark Gray
LRed='\033[0;91m' # Ligth Red
LGreen='\033[0;92m' # Ligth Green
LYellow='\033[0;93m'# Ligth Yellow
LBlue='\033[0;94m' # Ligth Blue
LPurple='\033[0;95m'# Light Purple
LCyan='\033[0;96m' # Ligth Cyan
# Bold
BBlack='\033[1;30m' # Black
BRed='\033[1;31m' # Red
BGreen='\033[1;32m' # Green
BYellow='\033[1;33m'# Yellow
BBlue='\033[1;34m' # Blue
BPurple='\033[1;35m'# Purple
BCyan='\033[1;36m' # Cyan
BWhite='\033[1;37m' # White
# Underline
UBlack='\033[4;30m' # Black
URed='\033[4;31m' # Red
UGreen='\033[4;32m' # Green
UYellow='\033[4;33m'# Yellow
UBlue='\033[4;34m' # Blue
UPurple='\033[4;35m'# Purple
UCyan='\033[4;36m' # Cyan
UWhite='\033[4;37m' # White
# Background
On_Black='\033[40m' # Black
On_Red='\033[41m' # Red
On_Green='\033[42m' # Green
On_Yellow='\033[43m'# Yellow
On_Blue='\033[44m' # Blue
On_Purple='\033[45m'# Purple
On_Cyan='\033[46m' # Cyan
On_White='\033[47m' # White
# Example of usage
echo -e "${Green}This is GREEN text${Color_Off} and normal text"
echo -e "${Red}${On_White}This is Red test on White background${Color_Off}"
# option -e is mandatory, it enable interpretation of backslash escapes
printf "${Red} This is red \n"
+820
View File
@@ -0,0 +1,820 @@
# Golang
## Summary
- Introduction
- [Hello World](#hello-world)
- [Go CLI Commands](#go-cli-commands)
- [Go Modules](#go-modules)
- Basic
- [Basic Types](#basic-types)
- [Variables](#variables)
- [Operators](#operators)
- [Conditional Statements](#conditional-statements)
- [Loops](#loops)
- [Arrays](#arrays)
- [Functions](#functions)
- Advanced
- [Structs](#structs)
- [Maps](#maps)
- [Pointers](#pointers)
- [Methods and Interfaces](#methods-and-interfaces)
- [Errors](#errors)
- [Testing](#testing)
- [Concurrency](#concurrency)
- Standard Libs
- [Package fmt](#package-fmt)
## Hello World
```go
package main
import "fmt"
func main() {
fmt.Println("Hello Gophers!")
}
```
[Return to Summary](#summary)
<hr/>
## Go CLI Commands
```bash
# Compile & Run code
$ go run [file.go]
# Compile
$ go build [file.go]
# Running compiled file
$ ./hello
# Test packages
$ go test [folder]
# Install packages/modules
$ go install [package]
# List installed packages/modules
$ go list
# Update packages/modules
$ go fix
# Format package sources
$ go fmt
# See package documentation
$ go doc [package]
# Add dependencies and install
$ go get [module]
# See Go environment variables
$ go env
# See version
$ go version
```
[Return to Summary](#summary)
<hr/>
## Go Modules
- Go projects are called **modules**
- Each module has multiple **packages**
- Each package should has a scoped functionality. Packages talk to each other to compose the code
- A module needs at least one package, the **main**
- The package main needs a entry function called **main**
```bash
# Create Module
$ go mod init [name]
```
Tip: By convention, modules names has the follow structure:
domain.com/user/module/package
Example: github.com/spf13/cobra
<hr/>
[Return to Summary](#summary)
## Basic Types
| Type | Set of Values | Values |
| :--------: | :----------------------------------------: | :-------------------------------------------: |
| bool | boolean | true/false |
| string | array of characters | needs to be inside "" |
| int | integers | 32 or 64 bit integer |
| int8 | 8-bit integers | [ -128, 128 ] |
| int16 | 16-bit integers | [ -32768, 32767] |
| int32 | 32-bit integers | [ -2147483648, 2147483647] |
| int64 | 64-bit integers | [ -9223372036854775808, 9223372036854775807 ] |
| uint8 | 8-bit unsigned integers | [ 0, 255 ] |
| uint16 | 16-bit unsigned integers | [ 0, 65535 ] |
| uint32 | 32-bit unsigned integers | [ 0, 4294967295 ] |
| uint64 | 64-bit unsigned integers | [ 0, 18446744073709551615 ] |
| float32 | 32-bit float | |
| float64 | 64-bit float | |
| complex64 | 32-bit float with real and imaginary parts | |
| complex128 | 64-bit float with real and imaginary parts | |
| byte | sets of bits | alias for uint8 |
| rune | Unicode characters | alias for int32 |
[Return to Summary](#summary)
<hr/>
## Variables
```go
// Declaration
var value int
// Initialization
value = 10
// Declaration + Initialization + Type inference
var isActive = true
// Short declaration (only inside functions)
text := "Hello"
// Multi declaration
var i, j, k = 1, 2, 3
// Variable not initialized = Zero values
// Numeric: 0
// Boolean: false
// String: ""
// Special value: nil (same as null)
var number int // 0
var text string // ""
var boolean bool // false
// Type conversions
// T(v) converts v to type T
i := 1.234 // float
int(i) // 1
// Constants
const pi = 3.1415
```
<hr/>
## Operators
[Return to Summary](#summary)
Arithmetic Operators
| Symbol | Operation | Valid Types |
|:---------:|:-------------:|:-------------:|
| `+` | Sum | integers, floats, complex values, strings |
| `-` | Difference | integers, floats, complex values |
| `*` | Product | integers, floats, complex values |
| `/` | Quotient | integers, floats, complex values |
| `%` | Remainder | integers |
| `&` | Bitwise AND | integers |
| `|` | Bitwise OR | integers |
| `^` | Bitwise XOR | integers |
| `&^` | Bit clear (AND NOT) | integers |
| `<<` | Left shift | integer << unsigned integer |
| `>>` | Right shift | integer >> unsigned integer |
Comparison Operators
| Symbol | Operation |
|:---------:|:-------------:|
| `==` | Equal |
| `!=` | Not equal |
| `<` | Less |
| `<=` | Less or equal |
| `>` | Greater |
| `>=` | Greater or equal |
Logical Operators
| Symbol | Operation |
|:---------:|:-------------:|
| `&&` | Conditional AND |
| `||` | Conditional OR |
| `!` | NOT |
[Return to Summary](#summary)
<hr/>
## Conditional Statements
```go
// If / Else
i := 1
if i > 0 {
// Condition is True! i is greater than zero
} else {
// Condition is False! i is lower or equal to zero
}
// Else if
i := 1
if i > 0 {
// Condition is True! i is greater than zero
} else if i > 0 && i < 2 {
// Condition is True! i greater than zero and lower than two
} else if i > 1 && i < 4 {
// Condition is True! i greater than one and lower than four
} else {
// None of the above conditions is True, so it falls here
}
// If with short statements
i := 2.567
if j := int(i); j == 2 {
// Condition is True! j, the integer value of i, is equal to two
} else {
// Condition is False! j, the integer value of i, is not equal to two
}
// Switch
text := 'hey'
switch text {
case 'hey':
// 'Hello!'
case 'bye':
// 'Byee'
default:
// 'Ok'
}
// Switch without condition
value := 5
switch {
case value < 2:
// 'Hello!'
case value >= 2 && value < 6:
// 'Byee'
default:
// 'Ok'
}
```
[Return to Summary](#summary)
<hr/>
## Loops
```go
// Golang only has the for loop
for i := 0; i < 10; i++ {
// i
}
// The first and third parameters are ommitable
// For as a while
i := 0;
for i < 10 {
i++
}
// Forever loop
for {
}
```
[Return to Summary](#summary)
<hr/>
## Arrays
```go
// Declaration with specified size
var array [3]string
array[0] = "Hello"
array[1] = "Golang"
array[2] = "World"
// Declaration and Initialization
values := [5]int{1, 2, 3, 4, 5}
// Slices: A subarray that acts as a reference of an array
// Determining min and max
values[1:3] // {2, 3, 4}
// Determining only max will use min = 0
values[:2] // {1, 2, 3}
// Determining only min will use max = last element
values[3:] // {3, 4}
// Length: number of elements that a slice contains
len(values) // 5
// Capacity: number of elements that a slice can contain
values = values[:1]
len(values) // 2
cap(values) // 5
// Slice literal
slice := []bool{true, true, false}
// make function: create a slice with length and capacity
slice := make([]int, 5, 6) // make(type, len, cap)
// Append new element to slice
slice := []int{ 1, 2 }
slice = append(slice, 3)
slice // { 1, 2, 3 }
slice = append(slice, 3, 2, 1)
slice // { 1, 2, 3, 3, 2, 1 }
// For range: iterate over a slice
slice := string["W", "o", "w"]
for i, value := range slice {
i // 0, then 1, then 2
value // "W", then "o", then "w"
}
// Skip index or value
for i := range slice {
i // 0, then 1, then 2
}
for _, value := range slice {
value // "W", then "o", then "w"
}
```
[Return to Summary](#summary)
<hr/>
## Functions
```go
// Functions acts as a scoped block of code
func sayHello() {
// Hello World!
}
sayHello() // Hello World!
// Functions can take zero or more parameters, as so return zero or more parameters
func sum(x int, y int) int {
return x + y
}
sum(3, 7) // 10
// Returned values can be named and be used inside the function
func doubleAndTriple(x int) (double, triple int) {
double = x * 2
triple = x * 3
return
}
d, t := doubleAndTriple(5)
// d = 10
// t = 15
// Skipping one of the returned values
_, t := doubleAndTriple(3)
// t = 9
// Functions can defer commands. Defered commands are
// runned in a stack order after the execution and
// returning of a function
var aux = 0
func switchValuesAndDouble(x, y int) {
aux = x
defer aux = 0 // cleaning variable to post use
x = y * 2
y = aux * 2
}
a, b = 2, 5
switchValuesAndDouble(2, 5)
// a = 10
// b = 4
// aux = 0
// Functions can be handled as values and be anonymous functions
func calc(fn func(int, int) int) int {
return fn(2, 6)
}
func sum(x, y int) int {
return x + y
}
func mult(x, y int) int {
return x * y
}
calc(sum) // 8
calc(mult) // 12
calc(
func(x, y int) int {
return x / y
}
) // 3
// Function closures: a function that returns a function
// that remembers the original context
func calc() func(int) int {
value := 0
return func(x int) int {
value += x
return value
}
}
calculator := calc()
calculator(3) // 3
calculator(45) // 48
calculator(12) // 60
```
[Return to Summary](#summary)
<hr/>
## Structs
Structs are a way to arrange data in specific formats.
```go
// Declaring a struct
type Person struct {
Name string
Age int
}
// Initializing
person := Person{"John", 34}
person.Name // "John"
person.Age // 34
person2 := Person{Age: 20}
person2.Name // ""
person2.Age // 20
person3 := Person{}
person3.Name // ""
person3.Age // 0
```
[Return to Summary](#summary)
<hr/>
## Maps
Maps are data structures that holds values assigneds to a key.
```go
// Declaring a map
var cities map[string]string
// Initializing
cities = make(map[string]string)
cities // nil
// Insert
cities["NY"] = "EUA"
// Retrieve
newYork = cities["NY"]
newYork // "EUA"
// Delete
delete(cities, "NY")
// Check if a key is setted
value, ok := cities["NY"]
ok // false
value // ""
```
[Return to Summary](#summary)
<hr/>
## Pointers
Pointers are a direct reference to a memory address that some variable or value is being stored.
```go
// Pointers has *T type
var value int
var pointer *int
// Point to a variable memory address with &
value = 3
pointer = &value
pointer // 3
pointer = 20
pointer // 20
pointer += 5
pointer // 25
// Pointers to structs can access the attributes
type Struct struct {
X int
}
s := Struct{3}
pointer := &s
s.X // 3
```
Obs: Unlike C, Go doesn't have pointer arithmetics.
[Return to Summary](#summary)
<hr/>
## Methods and Interfaces
Go doesn't have classes. But you can implement methods, interfaces and almost everything contained in OOP, but in what gophers call "Go Way"
```go
type Dog struct {
Name string
}
func (dog *Dog) bark() string {
return dog.Name + " is barking!"
}
dog := Dog{"Rex"}
dog.bark() // Rex is barking!
```
Interfaces are implicitly implemented. You don't need to inform that your struct are correctly implementing a interface if it already has all methods with the same name of the interface.
All structs implement the `interface{}` interface. This empty interface means the same as `any`.
```go
// Car implements Vehicle interface
type Vehicle interface {
Accelerate()
}
type Car struct {
}
func (car *Car) Accelerate() {
return "Car is moving on ground"
}
```
[Return to Summary](#summary)
<hr/>
## Errors
Go doesn't support `throw`, `try`, `catch` and other common error handling structures. Here, we use `error` package to build possible errors as a returning parameter in functions
```go
import "errors"
// Function that contain a logic that can cause a possible exception flow
func firstLetter(text string) (string, error) {
if len(text) < 1 {
return nil, errors.New("Parameter text is empty")
}
return string(text[0]), nil
}
a, errorA := firstLetter("Wow")
a // "W"
errorA // nil
b, errorB := firstLetter("")
b // nil
errorB // Error("Parameter text is empty")
```
[Return to Summary](#summary)
<hr/>
## Testing
Go has a built-in library to unit testing. In a separate file you insert tests for functionalities of a file and run `go test package` to run all tests of the actual package or `go test path` to run a specific test file.
```go
// main.go
func Sum(x, y int) int {
return x + y
}
// main_test.go
import (
"testing"
"reflect"
)
func TestSum(t *testing.T) {
x, y := 2, 4
expected := 2 + 4
if !reflect.DeepEqual(Sum(x, y), expected) {
t.Fatalf("Function Sum not working as expected")
}
}
```
[Return to Summary](#summary)
<hr/>
## Concurrency
One of the main parts that make Go attractive is its form to handle with concurrency. Different than parallelism, where tasks can be separated in many cores that the machine processor have, in concurrency we have routines that are more lightweight than threads and can run asynchronously, with memory sharing and in a single core.
```go
// Consider a common function, but that function can delay itself because some processing
func show(from string) {
for i := 0; i < 3; i++ {
fmt.Printf("%s : %d\n", from, i)
}
}
// In a blocking way...
func main() {
show("blocking1")
show("blocking2")
fmt.Println("done")
}
/* blocking1: 0
blocking1: 1
blocking1: 2
blocking2: 0
blocking2: 1
blocking2: 2
done
*/
// Go routines are a function (either declared previously or anonymous) called with the keyword go
func main() {
go show("routine1")
go show("routine2")
go func() {
fmt.Println("going")
}()
time.Sleep(time.Second)
fmt.Println("done")
}
/* Obs: The result will depends of what processes first
routine2: 0
routine2: 1
routine2: 2
going
routine1: 0
routine1: 1
routine1: 2
done
*/
// Routines can share data with channels
// Channels are queues that store data between multiple routines
msgs := make(chan string)
go func(channel chan string) {
channel <- "ping"
}(msgs)
go func(channel chan string) {
channel <- "pong"
}(msgs)
fmt.Println(<-msgs) // pong
fmt.Println(<-msgs) // ping
// Channels can be bufferized. Buffered channels will accept a limited number of values and when someone try to put belong their limit, it will throw and error
numbers := make(chan int, 2)
msgs<-0
msgs<-1
msgs<-2
// fatal error: all goroutines are asleep - deadlock!
// Channels can be passed as parameter where the routine can only send or receive
numbers := make(chan int)
go func(sender chan<- int) {
sender <- 10
}(numbers)
go func(receiver <-chan int) {
fmt.Println(<-receiver) // 10
}(numbers)
time.Sleep(time.Second)
// When working with multiple channels, the select can provide a control to execute code accordingly of what channel has bring a message
c1 := make(chan string)
c2 := make(chan string)
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
default:
fmt.Println("no messages")
}
go func() {
time.Sleep(1 * time.Second)
c1 <- "channel1 : one"
}()
go func() {
time.Sleep(2 * time.Second)
c2 <- "channel2 : one"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
/*
no messages
received channel1: one
received channel2: one
*/
// Channels can be closed and iterated
channel := make(chan int, 5)
for i := 0; i < 5; i++ {
channel <- i
}
close(channel)
for value := range channel {
fmt.Println(value)
}
/*
0
1
2
3
4
*/
```
[Return to Summary](#summary)
<hr/>
## Package `fmt`
```go
import "fmt"
fmt.Print("Hello World") // Print in console
fmt.Println("Hello World") // Print and add a new line in end
fmt.Printf("%s is %d years old", "John", 32) // Print with formatting
fmt.Errorf("User %d not found", 123) // Print a formatted error
```
[Return to Summary](#summary)
<hr/>
+650
View File
@@ -0,0 +1,650 @@
### HELLO WORLD :ghost:
```java
//Text file name HelloWorld.java
public class HelloWorld {
// main() is the method
public static void main (String[] args)
//Prints "Hello World" in the terminal window.
System.out.println("Hello World");
}
```
### COMPILATION & EXECUTING JAVA CODE
* Go to your program directory in terminal (Assumed JAVA Path is set)
* After for compile your code
> **javac HelloWorld.java (your program file name)**
* For run program
> **java HelloWorld (main class name)**
### DATA TYPES
| Type | Set of values | Values | Operators |
|:-------:|:-----------------------:|:----------------------------:|:---------:|
| short | integers | between -2^15 and + (2^15)-1 | + - * / % |
| int | integers | between -2^31 and + (2^31)-1 | + - * / % |
| long | integers | between -2^63 and + (2^63)-1 | + - * / % |
| float | integers | real numbers 32 bit | + - * / |
| double | floating-point numbers | real numbers 64 bit | + - * / |
| boolean | boolean values | true or false | && \|\| ! |
| char | characters | 16 bit | |
| String | sequences of characters |it's not a primitive data type| |
### DECLARATION AND ASSIGNMENT STATEMENTS
```java
//Declaration statement
int a,b;
//Assignment statement
a = 13212; //a is the variable name; 13212 is the literal which is assign to the variable a
//Initialization statement
int c = a + b;
//Compound assignment expressions
a += b; //a is the variable name; b is the variable name; this expression is an equivalent shorthand notation of a = a + b
a -= b; //a is the variable name; b is the variable name; this expression is an equivalent shorthand notation of a = a - b
a *= b; //a is the variable name; b is the variable name; this expression is an equivalent shorthand notation of a = a * b
a /= b; //a is the variable name; b is the variable name; this expression is an equivalent shorthand notation of a = a / b
a %= b; //a is the variable name; b is the variable name; this expression is an equivalent shorthand notation of a = a % b
a ^= b; //a is the variable name; b is the variable name; this expression is an equivalent shorthand notation of a = a ^ b
a &= b; //a is the variable name; b is the variable name; this expression is an equivalent shorthand notation of a = a & b
a \|= b; //a is the variable name; b is the variable name; this expression is an equivalent shorthand notation of a = a \| b
```
### COMPARISON OPERATORS
| Operation | Meaning |
|:---------:|:---------------------:|
| == | equal |
| != | not equal |
| < | less than |
| > | greater than |
| <= | less than or equal |
| >= | greater than or equal |
### PRINTING
```java
String s = "Happy Coding Folks!!"
System.out.print(String s) //print s
System.out.println(String s) //print s, followed by a newline
System.out.println() //print a newline
```
### PARSING COMMAND-LINE ARGUMENTS
```java
String s = "Java is the best!!"
int Integer.parseInt(String s) //convert s to an int value
double Double.parseDouble(String) //convert s to a double value
long Long.parseLong(String s) // convert s to a long value
````
### MATH LIBRARY
```java
Public Class Math{
double abs(double a) // absolute value of a
double max(double a, double b) //maximum of a and b
double min(double a, dobule a) //minimum of a and b
double sin(double theta) //sine of theta
double cos(double theta) //cosine of theta
double tan(double theta) //tangent of theta
double toRadians(double degrees) // convert angle from degrees to radians
double toDegrees(double radians) // convert angle from radians to degrees
double exp(double a) // exponential (e^a)
double pow(double a, double p) //raise a to the bth power (a^b)
double random() //random in [0,1)
double sqrt(double a) //square root of a
}
```
### EXAMPLES OF TYPE CONVERSION
| Expression | Expression type | Expression value |
|:---------------------:|:---------------:|:----------------:|
| (1 + 2 + 3 + 4) / 4.0 | double | 2.5 |
| Math.sqrt(4) | double | 2.0 |
| "123343" + 99 | String | "12334399" |
| 11 * 0.25 | double | 2.75 |
| (int) 11 * 0.25 | double | 2.75 |
| 11 * (int) 0.25 | int | 0 |
| (int) (11 * 0.25) | int | 2 |
### CONDITIONAL & LOOP STATEMENT
#### ANATOMY OF CONDITIONAL STATEMENT
> IF Statement
```java
if (x>y) { // x > y is the boolean expression
//Sequence of statements
x = y;
}
```
> IF-ELSE STATEMENT
```java
if (BOOLEAN EXPRESSION) {
//Sequence of statements
} else {
//Sequence of statements
}
```
> NESTED IF STATEMENT
```java
if (BOOLEAN EXPRESSION) {
//Sequence of statements
} else if {
//Sequence of statements
}
.
.
.
else {
//Sequence of statements
}
```
>SWITCH STATEMENT
```java
switch (VARIABLE TO EVALUATE ITS VALUE) {
case value: Statement; break;
...
...
...
default: Statement; break;
}
```
**Example:**
```java
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
```
#### ANATOMY OF A LOOP STATEMENT
>FOR LOOP STATEMENT
```java
for (declare and initialize a loop control variable; loop-continuation condition/s; increment or decrement of the variable of control)
{
//Statement
}
```
**Example:**
```java
for (int i = 0; i <= n; i++) {
System.out.println(i);
}
```
>Enhanced for loop/for-each
```java
for(dataType item : array) {
...
}
```
**Example:**
```java
// array of numbers
int[] numbers = {100, 200, 300, 400};
// for each loop
for (int number: numbers) {
System.out.println(number);
```
> WHILE LOOP STATEMENT
```java
while(condition){ //till condition will be true.
//code to be executed
}
```
**Example:**
```java
//Initialization is a separate statement
int power = 1;
while ( power <= 10/2 ) // power <= n/2 is an example of the loop-continuation condition
{
System.out.println(power);
}
```
> DO-WHILE LOOP STATEMENT
```java
do{ //always run one time even if condition would be false
//Statement
} while(loop-continuation condition);
```
**Example:**
```java
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
```
### ARRAY
> ARRAY DECLARATION
```java
int[] ai; // array of int
short[][] as; // array of array of short
short s, // scalar short
aas[][]; // array of array of short
Object[] ao; // array of Object
Collection<?>[] ca; // array of Collection of unknown type
```
> DECLARATION OF ARRAY VARIABLE
```java
Exception ae[] = new Exception[3];
Object aao[][] = new Exception[2][3];
int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
'S', 't', 'r', 'i', 'n', 'g' };
String[] aas = { "array", "of", "String", };
```
### ACCESS MODIFIERS
1. default(No keyword required)
2. private
3. public
4. protected
### NON ACCESS MODIFIERS
1. static
2. final
3. transient
4. abstract
5. synchronized
6. volatile
## Object Oriented Programming (OOPs) Concept :clipboard:
### OBJECT
```java
//Declare a variable, object name
String s;
//Invoke a contructor to create an object
s = new String ("Hello World");
//Invoke an instance method that operates on the object's value
char c = s.chartAt(4);
```
> INSTANCE VARIABLES
```java
public class Charge {
//Instance variable declarations
private final double rx, ry;
private final double q;
}
```
### METHODS
```java
public static double sum (int a, int b) { //double is the return type, sum is the method's name, a and b are two arguments of type int;
int result; //local variable
result = a + b;
return result;//return statement;
}
```
### CLASS DECLARATION
```java
class MyClass {
// field, constructor, and
// method declarations
}
```
**Example:**
```java
public class Bicycle {
// the Bicycle class has
// three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has
// one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has
// four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
```
>DECLARING CLASSESS IMPLEMENTATING AN INTERFACE AND EXTENDING PARENT CLASS
```java
class MyClass extends MySuperClass implements YourInterface {
// field, constructor, and
// method declarations
}
```
* MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
> CONSTRUCTORS
* A class contains constructors that are invoked to create objects from the class blueprint.
* Constructor declarations look like method declarations—except that they use the name of the class and have no return type
* Each and every class has defualt No-args constructor.
```java
public class Bicycle{
private int gear;
private int cadence;
private int speed;
public Bicycle(int startCadence, int startSpeed, int startGear) { //args-constructor
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public Bicycle(){//No-args constructor
super();
}
}
```
### POLYMORPHISM
* Polymorphism is the concept where an object behaves differently in different situations.
* There are two types of polymorphism
1. compile time polymorphism
2. runtime polymorphism.
#### 1. Compile Time Polymorphism
* Compile-time polymorphism is achieved by method overloading.
* method overloading is creating multiple method with methods name is same and arguments are different.
```java
public class Circle {
public void draw(){
System.out.println("Drwaing circle with default color Black and diameter 1 cm.");
}
public void draw(int diameter){ //method draw() overloaded.
System.out.println("Drwaing circle with default color Black and diameter"+diameter+" cm.");
}
public void draw(int diameter, String color){ //method draw() overloaded.
System.out.println("Drwaing circle with color"+color+" and diameter"+diameter+" cm.");
}
}
```
#### 2. Run Time Polymorphism
* Run-time polymorphism is achieved by method overriding.
* Runtime polymorphism is implemented when we have an **“IS-A”** relationship between objects.
* method overriding is the subclass has to override the superclass method.
```java
public interface Shape {
public void draw();
}
```
```java
public class Circle implements Shape{
@Override
public void draw(){
System.out.println("Drwaing circle");
}
}
```
```java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing Square");
}
}
```
* `Shape` is the superclass and there are two subclasses `Circle` and `Square`
* Below is an example of runtime polymorphism.
```java
Shape sh = new Circle();
sh.draw();
Shape sh1 = getShape(); //some third party logic to determine shape
sh1.draw();
```
### INHERITANCE
* Inheritance is the mechanism of code reuse.
* The object that is getting inherited is called the superclass and the object that inherits the superclass is called a subclass.
* We use `extends` keyword in java to implement inheritance from class.
* We use `implements` keyword in java to implement inheritance from interface.
```java
public class Superclass{
// methods and fields
}
```
```java
public interface Superinterface{
// methods and fields
}
```
```java
public class Subclass extends Superclass implements Superinterface{
// methods and fields
}
```
### Abstraction
* Abstraction is the concept of hiding the internal details and describing things in simple terms.
* Abstraction can be achieved by two ways.
1. Abstract Class
2. Interface
#### 1. Abstract Class
* An abstract class must be declared with an `abstract` keyword.
* It can have abstract and non-abstract methods.
* It cannot be instantiated.
* It can have constructors and static methods also.
* It can have final methods which will force the subclass not to change the body of the method.
```java
abstract class Flower{
abstract String Smell(); //abstract method.
String Oil(){ // non-abstract method.
System.out.println("Flower Oil is good.");
}
}
public class Lily extends Flower{
private String Smell(){ // implementation of abstarct method.
System.out.println("Lily smell's lovender.");
}
}
```
#### 2. Interface
* Interface is a blueprint of a **class**.
* It can have only abstract methods. [Except Java 8 and next versions.]
* Since Java 8, we can have **default and static** methods in an interface.
```java
interface print{
void printPaper();
}
public class A4 implements print{
public void printPaper(){
System.out.println("A4 Page Printed. ");
}
}
```
### Encapsulation
* Encapsulation is used for access restriction to class members and methods.
* Encapsulation is the technique used to implement abstraction in OOP.
* As in encapsulation, the data in a class is hidden from other classes, so it is also known as **data-hiding**.
* Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
* Best example of Encapsulation is POJO (Plain-Java-Object-Class).
```java
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
```
## ADVANCE DATA TYPE
* **STACK DATA TYPE**
```java
public class Stack<Item> implements Iterable <Item>
Stack() //create an empty stack
boolean isEmpty() //return if the stack empty
void push(Item item) // push an item onto the stack
Item pop() //return and remove the item that was inserted most recently
int size() //number of item on stack
```
* **QUEUE DATA TYPE**
```java
public class Queue<Item> implements Iterable<Item>
Queue() //create an empty queue
boolean isEmpty() //return if the queue empty
void enqueue(Item item) // insert an item onto queue
Item dequeue() //return and remove the item that was inserted least recently
int size() //number of item on queue
```
* **ITERABLE**
```java
//import Iterator
import java.util.Iterator;
public class Queue<Item> implements Iterable<Item> {
//FIFO queue
private Node first;
private Node last;
private class Node {
Item item;
Node next;
}
public void enqueue (Item item)
...
public Item dequeue()
...
}
```
* **SYMBOL TABLE DATA TYPE**
```java
public class ST<Key extends Comparable<Key>, Value>
ST() //create and empty symbol table
void put(Key key, Value val) //associate val with key
Value get(Key key) //value associated with key
void remove(Key key) //remove key (and its associated value)
boolean contains (Key key) //return if there is a value associated with key
int size() //number of key-value pairs
Iterable<Key> keys() // all keys in the symbol table
```
* **SET DATA TYPE**
```java
public class Set<Key extends Comparable<Key>> implements Iterable<Key>
Set() //create an empty set
boolean isEmpty() //return if the set is empty
void add (Key key) //add key to the set
void remove(Key key) //remove key from set
boolean contains(Key key) //return if the key is in the set
int size() //number of elements in set
```
+97
View File
@@ -0,0 +1,97 @@
/* *******************************************************************************************
* GLOBAL OBJECTS > OBJECT
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
* ******************************************************************************************* */
// Global object: properties
Object.length // length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. This number does not include the rest parameter. Has a value of 1.
Object.prototype // Represents the Object prototype object and allows to add new properties and methods to all objects of type Object.
// Methods of the Object constructor
Object.assign(target, ...sources) // Copies the values of all enumerable own properties from one or more source objects to a target object. method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object
Object.create(MyObject) // Creates a new object with the specified prototype object and properties. The object which should be the prototype of the newly-created object.
Object.defineProperty(obj, prop, descriptor) // Adds the named property described by a given descriptor to an object.
Object.defineProperties(obj, props) // Adds the named properties described by the given descriptors to an object.
Object.entries(obj) // Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
Object.freeze(obj) // Freezes an object: other code can't delete or change any properties.
Object.getOwnPropertyDescriptor(obj, prop) // Returns a property descriptor for a named property on an object.
Object.getOwnPropertyDescriptors(obj) // Returns an object containing all own property descriptors for an object.
Object.getOwnPropertyNames(obj) // Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
Object.getOwnPropertySymbols(obj) // Returns an array of all symbol properties found directly upon a given object.
Object.getPrototypeOf(obj) // Returns the prototype of the specified object.
Object.is(value1, value2); // Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
Object.isExtensible(obj) // Determines if extending of an object is allowed.
Object.isFrozen(obj) // Determines if an object was frozen.
Object.isSealed(obj) // Determines if an object is sealed.
Object.keys(obj) // Returns an array containing the names of all of the given object's own enumerable string properties.
Object.preventExtensions(obj) // Prevents any extensions of an object.
Object.seal(obj) // Prevents other code from deleting properties of an object.
Object.setPrototypeOf(obj, prototype) // Sets the prototype (i.e., the internal [[Prototype]] property).
Object.values(obj) // Returns an array containing the values that correspond to all of a given object's own enumerable string properties.
// Object instances and Object prototype object (Object.prototype.property or Object.prototype.method())
// Properties
obj.constructor // Specifies the function that creates an object's prototype.
obj.__proto__ // Points to the object which was used as prototype when the object was instantiated.
// Methods
obj.hasOwnProperty(prop) // Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
prototypeObj.isPrototypeOf(object) // Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
obj.propertyIsEnumerable(prop) // Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
obj.toLocaleString() // Calls toString().
obj.toString() // Returns a string representation of the object.
object.valueOf() // Returns the primitive value of the specified object.
/* *******************************************************************************************
* GLOBAL OBJECTS > ARRAY
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
* ******************************************************************************************* */
// Global object: properties
Array.length // Reflects the number of elements in an array.
Array.prototype // Represents the prototype for the Array constructor and allows to add new properties and methods to all Array objects.
// Global object: methods
Array.from(arrayLike[, mapFn[, thisArg]]) // Creates a new Array instance from an array-like or iterable object.
Array.isArray(obj) // Returns true if a variable is an array, if not false.
Array.of(element0[, element1[, ...[, elementN]]]) // Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
// Instance: properties
arr.length // Reflects the number of elements in an array.
// Instance: mutator methods
arr.copyWithin(target, start, end) // Copies a sequence of array elements within the array.
arr.fill(value, start, end) // Fills all the elements of an array from a start index to an end index with a static value.
arr.pop() // Removes the last element from an array and returns that element.
arr.flat() // merges nested array into one single array
arr.push([element1[, ...[, elementN]]]) // Adds one or more elements to the end of an array and returns the new length of the array.
arr.reverse() // Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.
arr.shift() // Removes the first element from an array and returns that element.
arr.sort() // Sorts the elements of an array in place and returns the array.
array.splice(start, deleteCount, item1, item2, ...) // Adds and/or removes elements from an array.
arr.unshift([element1[, ...[, elementN]]]) // Adds one or more elements to the front of an array and returns the new length of the array.
// Instance: accessor methods
arr.at(index) // Returns the element at the specified index in the array.
arr.concat(value1[, value2[, ...[, valueN]]]) // Returns a new array comprised of this array joined with other array(s) and/or value(s).
arr.includes(searchElement, fromIndex) // Determines whether an array contains a certain element, returning true or false as appropriate.
arr.indexOf(searchElement[, fromIndex]) // Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
arr.join(separator) // Joins all elements of an array into a string.
arr.lastIndexOf(searchElement, fromIndex) // Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
arr.slice(begin, end) // Extracts a section of an array and returns a new array.
arr.toString() // Returns a string representing the array and its elements. Overrides the Object.prototype.toString() method.
arr.toLocaleString(locales, options) // Returns a localized string representing the array and its elements. Overrides the Object.prototype.toLocaleString() method.
// Instance: iteration methods
arr.entries() // Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
arr.every(callback[, thisArg]) // Returns true if every element in this array satisfies the provided testing function.
arr.filter(callback[, thisArg]) // Creates a new array with all of the elements of this array for which the provided filtering function returns true.
arr.find(callback[, thisArg]) // Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found.
arr.findIndex(callback[, thisArg]) // Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
arr.forEach(callback[, thisArg]) // Calls a function for each element in the array.
arr.keys() // Returns a new Array Iterator that contains the keys for each index in the array.
arr.map(callback[, initialValue]) // Creates a new array with the results of calling a provided function on every element in this array.
arr.reduce(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
arr.reduceRight(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
arr.some(callback[, initialValue]) // Returns true if at least one element in this array satisfies the provided testing function.
arr.values() // Returns a new Array Iterator object that contains the values for each index in the array.
+604
View File
@@ -0,0 +1,604 @@
<?php
// Exit the file, string inside get's echo'ed
die("This file is not ment to be ran. ¯\_(ツ)_/¯");
exit("This file is not ment to be ran. ¯\_(ツ)_/¯");
/**
* Printing
*/
echo ""; // Print a string or type that can be made into a string(I.E int, float).
print_r($arr); // Print anything, with type hints for array's and object's
var_dump($arr); // Print anything, with type hints for any value and sizes
/**
* Usefull string manipulation methods
*/
$string = 'Awesome cheatsheets';
str_contains($string, 'cheat'); // Find if the string contains the specified string (PHP >= 8.0)
str_replace('Awesome', 'Bonjour', $string); // Replace all occurence
strcmp($string, 'Awesome cheatsheets'); // Compare two strings
strpos($string, 'a', 0); // Get position in the string
str_split($string, 2); // Split the string
strrev($string); // Reverse a string
trim($string); // Strip whitespace from the beginning and end of a string
ucfirst($string); // Make a string's first character uppercase
lcfirst($string); // Make a string's first character lowercase
substr($string, 0, 4); // Return part of a string
/**
* Declaring an Array
*/
// Indexed Array
$arr = array("John", "Doe", "Lorem", "Ipsum");
// Associative Array
$arr = array("John"=>"10", "Doe"=>"200", "Doe"=>"3000", "Ipsum"=>"40000");
// Multidimensional Arrays
$arr = array (
array("John",100,180),
array("Doe",150,130),
array("Lorem",500,200),
array("Ipsum",170,150)
);
// Declaring array with short syntax
$arr = ["John", "Doe", "Lorem", "Ipsum"]; // Indexed Array
$arr = ["John"=>"10", "Doe"=>"200", "Doe"=>"3000", "Ipsum"=>"40000"]; // Associative Array
$arr = [
["John",100,180],
["Doe",150,130],
["Lorem",500,200],
["Ipsum",170,150], // You can have a "," at the end without throwing syntax errors
];
/**
* Sorting an Array
*/
sort($arr); // Sort arrays in ascending order.
rsort($arr); // Sort arrays in descending order.
asort($arr); // Sort associative arrays in ascending order, according to the value.
ksort($arr); // Sort associative arrays in ascending order, according to the key.
arsort($arr); // Sort associative arrays in descending order, according to the value.
krsort($arr); // Sort associative arrays in descending order, according to the key.
/**
* Conditions
*/
// If/Elseif/Else
if($i > 10) {
} elseif( $i > 100) {
} else {
}
// Ternary
$string = $state == 'Running' ? 'He is running' : 'I don\'t know';
// Null coalescing
$string = $startDate ?? '';
/**
* Ways of looping
*/
continue; // Skip current iter
break; // Exit loop
// Foreach
foreach($arr as $key => $value) {
$key = $key;
$value = $value;
}
// For
for($i = 0; $i < count($arr); $i++) {
$key = $i;
$value = $arr[$i];
}
// While
$i = 0;
while($i < count($arr) - 1) {
$key = $i;
$value = $arr[$i];
}
// Do while
$i = 0;
do {
$key = $i;
$value = $arr[$i];
} while($i < count($arr));
// Switch
switch($arr) {
case 1:
break;
case 2:
break;
case 3:
break;
default:
}
/**
* Match (PHP >= 8.0)
* https://www.php.net/manual/fr/control-structures.match.php
*/
$food = 'apple';
$return_value = match($food) {
'apple', 'appel' => 'An apple',
'banana' => 'A banana',
'applepie' => 'An applepie',
default => 'A fruit'
};
//You can also use it as a conditionnal and throw exceptions
$str = 'Welcome to awesome cheatsheets';
$return_value = match(true) {
str_contains($str, 'Welcome') && str_contains($str ,'to') => 'en-EN',
str_contains($str, 'Bonjour') && str_contains($str, 'sur') => 'fr-FR',
default => throw new Exception('Not a recognized language')
};
/**
* Global variables
* http://php.net/manual/en/language.variables.superglobals.php
*/
$_SERVER; // SERVER variables
$_GET; // Query params
$_POST; // Post fields
$_REQUEST; // GET and POST together
$GLOBALS; // Array of global variables
$_SESSION; // Browser session
$_FILES; // Array of files that are sent in request
$_COOKIE; // Array of cookies sent in request
$_ENV; // php.ini options
$argv; // Array of terminal arguments (filename included)
$argc; // Number of arguments passed into terminal
/**
* Functions
*/
// Simple function
function name($parameter);
// Function with return type (void, int, float, string, array, object, mixed)
function name($parameter) : void;
// Function with optionnal parameter
function name($parameter = '') : string;
// Function with typed parameter (? means "can be null")
function name(?string $parameter) : ?string;
// Function with union types (PHP >= 8.0)
function name(int|string $parameter1, array $parameter2) : int|string;
// Function call
name('my_parameter');
// Null safe operator (PHP >= 8.0)
$myObject?->getName()?->startWith('A');
/**
* Class
* http://php.net/manual/en/language.oop5.basic.php
*/
class NormalClass extends AbstractClassName implements InterfaceName
{
use TraitName;
// --> PROPERTY TYPES <--
/**
* Public property, everyone can access this property.
* @var Type
*/
public $property;
/**
* Private property, only this instance can access this property.
* @var Type
*/
private $property;
/**
* Protected property, this instance and childs can access this property.
* @var Type
*/
protected $property;
/**
* Static property, is the same for all instances of this class.
* @var Type
*/
static $property;
// --> FUNCTION TYPES <--
/**
* Public function, everyone can access this function.
* @param Type
* @return Type
*/
public function publicFunction(Type $var = null): Type
{
}
/**
* Private function, only this instance can access this function.
* @param Type
* @return Type
*/
private function privateFunction(Type $var = null): Type
{
}
/**
* Protected function, this instance and childs can access this function.
* @param Type
* @return Type
*/
protected function protectedFunction(Type $var = null): Type
{
}
/**
* Static function, doesn't need an instance to be executed.
* @param Type
* @return Type
*/
public static function staticFunction(Type $var = null): Type
{
}
// --> MAGIC METHODS <--
/**
* Gets triggered on creating a new class instance
* http://php.net/manual/en/language.oop5.decon.php
* @param Type
* @return void
*/
public function __construct(Type $var = null)
{
}
/**
* Gets triggered on destruction of a class instance
* http://php.net/manual/en/language.oop5.decon.php
* @return void
*/
public function __destruct()
{
}
/**
* __set() is run when writing data to inaccessible properties.
* http://php.net/manual/en/language.oop5.overloading.php
* @param string name
* @param mixed value
* @return void
*/
public function __set(string $name , mixed $value)
{
}
/**
* __get() is utilized for reading data from inaccessible properties.
* http://php.net/manual/en/language.oop5.overloading.php
* @param string name
* @return mixed
*/
public function __get(string $name)
{
}
/**
* __isset() is triggered by calling isset() or empty() on inaccessible properties.
* http://php.net/manual/en/language.oop5.overloading.php
* @param string name
* @return bool
*/
public function __isset(string $name)
{
}
/**
* __unset() is invoked when unset() is used on inaccessible properties.
* http://php.net/manual/en/language.oop5.overloading.php
* @param string name
* @return void
*/
public function __unset(string $name)
{
}
/**
* __call is triggered when invoking inaccessible methods in an object context.
* http://php.net/manual/en/language.oop5.overloading.php
* @param string name
* @param array arguments
* @return mixed
*/
public function __call(string $name, array $arguments)
{
}
/**
* __callStatic() is triggered when invoking inaccessible methods in a static context.
* http://php.net/manual/en/language.oop5.overloading.php
* @param string name
* @param array arguments
* @return mixed
*/
public static function __callStatic(string $name, array $arguments)
{
}
/**
* http://php.net/manual/en/language.oop5.magic.php
* @return array
*/
public function __sleep()
{
}
/**
* http://php.net/manual/en/language.oop5.magic.php
* @return void
*/
public function __wakeup()
{
}
/**
* http://php.net/manual/en/language.oop5.magic.php
* @return string
*/
public function __toString()
{
}
/**
* http://php.net/manual/en/language.oop5.magic.php
* @param Type
* @return mixed
*/
public function __invoke(Type $var = null)
{
}
/**
* http://php.net/manual/en/language.oop5.magic.php
* @param array properties
* @return object
*/
public static function __set_state(array $properties)
{
}
/**
* http://php.net/manual/en/language.oop5.magic.php
* @return array
*/
public function __debugInfo()
{
}
}
/**
* Every class that has implemented this interface need to have the same functions.
*/
interface InterfaceName
{
public function FunctionName(Type $var = null): Type;
}
/**
* Combination of class and interface.
*/
abstract class AbstractClassName
{
/**
* Classes extending this abstract class need to have this function.
* @param Type
* @return Type
*/
abstract function abstractFunction(Type $var = null): Type;
}
/**
* Basic Implementation of LoggerAwareInterface.
* @see https://github.com/php-fig/log/blob/master/Psr/Log/LoggerAwareTrait.php
*/
trait LoggerAwareTrait
{
/**
* The logger instance.
*
* @var LoggerInterface
*/
protected $logger;
/**
* Sets a logger.
*
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
}
/**
* Example with use of LoggerAwareTrait.
*/
class ClassWithLogger
{
/**
* Use the LoggerAwareTrait in this class.
*/
use LoggerAwareTrait;
}
/**
* Enums (PHP >=8.1)
* https://www.php.net/manual/fr/language.types.enumerations.php
*/
interface StateCode {
public function stateCode() : int;
}
enum States implements StateCode {
case Running;
case Stopped;
public function stateCode() : int {
return match($this) {
State::Running => '444',
State::Stopped => '666'
};
}
}
/**
* You can also declare backed Enums
*/
enum States : int implements StateCode {
case Running = 1;
case Stopped = 0;
public function stateCode() : int {
return match($this) {
State::Running => '444',
State::Stopped => '666'
};
}
}
/** Enums can be use as a type */
function notify(State $state) {
// ...
}
notify(State::Running);
/**
* PHP Regex.
*/
// Meta Characters.
^ Start of subject (or line in multiline mode)
$ End of subject (or line in multiline mode)
[ Start character class definition
] End character class definition
| Alternates, eg (a|b) matches a or b
( Start subpattern
) End subpattern
\ Escape character
// Pattern Modifiers.
i Caseless - ignore case
m Multiline mode - ^ and $ match start and end of lines
s Dotall - . class includes newline
x Extended- comments & whitespace
e preg_replace only - enables evaluation of replacement as PHP code
S Extra analysis of pattern
U Pattern is ungreedy
u Pattern is treated as UTF-8
// Subpattern Modifiers & Assertions.
(?:) Non capturing subpattern ((?:foo|fu)bar) matches foobar or fubar without foo or fu appearing as a captured subpattern
(?=) Positive look ahead assertion foo(?=bar) matches foo when followed by bar
(?!) Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
(?<=) Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
(?<!) Negative look behind assertion (?<!foo)bar matches bar when not preceded by foo
(?>) Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
(?(x)) Conditional subpatterns (?(3)foo|fu)bar Matches foo if 3rd subpattern has matched, fu if not
(?#) Comment (?# Pattern does x y or z)
// Base Character Classes
\w Any "word" character (a-z 0-9 _)
\W Any non "word" character
\s Whitespace (space, tab CRLF)
\S Any non whitepsace character
\d Digits (0-9)
\D Any non digit character
. (Period) - Any character except newline
// Multiplicity.
n* Zero or more of n
n+ One or more of n
n? Zero or one occurrences of n
{n} n occurrences exactly
{n,} At least n occurrences
{,m} At most m occurrences
{n,m} Between n and m occurrences (inclusive)
// PHP Regular Expression Functions.
Function Description
preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all() The preg_match_all() function matches all occurrences of pattern in string. Useful for search and replace.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split() Preg Split (preg_split()) operates exactly like the split() function, except that regular expressions are accepted as input parameters.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regex pattern within a string.
preg_ quote() Quote regular expression characters
// Code Snippets.
//A better solution for validate email syntax is using filter_var.
if (filter_var('test+email@fexample.com', FILTER_VALIDATE_EMAIL)) {
echo "Your email is ok.";
} else {
echo "Wrong email address format.";
}
//Validate username, consist of alpha-numeric (a-z, A-Z, 0-9), underscores, and has minimum 5 character and maximum 20 character.
//You could change the minimum character and maximum character to any number you like.
$username = "user_name12";
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
echo "Your username is ok.";
} else {
echo "Wrong username format.";
}
//Validate domain
$url = "http://domain-name.com/";
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
echo "Your url is ok.";
} else {
echo "Wrong url.";
}
//Extract domain name from certain URL
$url = "http://domain-name.com/index.html";
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
echo $host; // domain-name.com
//Highlight a word in the content
$text = "A regular expression (shortened as regex) is a sequence of characters that define a search pattern. Usually such patterns are used by string-searching algorithms for 'find' or 'find and replace' operations on strings, or for input validation.";
$text = preg_replace("/\b(regex)\b/i", 'replaced content', $text);
echo $text; /*A regular expression (shortened as replaced content) is a sequence of characters that define a search pattern. Usually such patterns are used by string-searching algorithms for 'find' or 'find and replace' operations on strings, or for input validation.*/
+382
View File
@@ -0,0 +1,382 @@
# Python
* Python is an interpreted, high-level and general-purpose, dynamically typed programming language
* It is also Object oriented, modular oriented and a scripting language.
* In Python, everything is considered as an Object.
* A python file has an extension of .py
* Python follows Indentation to separate code blocks instead of flower brackets({}).
* We can run a python file by the following command in cmd(Windows) or shell(mac/linux).
`$ python <filename.py>` or `$ python3 <filename.py>`
#### By default, python doesn't require any imports to run a python file.
## Create and execute a program
1. Open up a terminal/cmd
1. Create the program: nano/cat > nameProgram.py
1. Write the program and save it
1. python nameProgram.py
<br>
### Basic Datatypes
| Data Type | Description |
| --------- | ----------- |
| int | Integer values [0, 1, -2, 3] |
| float | Floating point values [0.1, 4.532, -5.092] |
| char | Characters [a, b, @, !, `] |
| str | Strings [abc, AbC, A@B, sd!, `asa] |
| bool | Boolean Values [True, False] |
| complex | Complex numbers [2+3j, 4-1j] |
<br>
## Keywords
<br>
- As of python3.8 there are 35 keywords
| Keyword | Description | Category |
|---------- | ---------- | --------- |
| True | Boolean value for not False or 1 | Value Keyword|
| False | Boolean Value for not True or 0 | Value Keyword |
| None | No Value | Value keyword |
| and | returns true if both (oprand) are true (other language && ) | Operator keyword |
| or | returns true of either operands is true (other language || ) | Operator keyword |
| in | returns true if word is in iterator | Operator keyword |
| is | returns true if id of variables are same | Operator keyword |
| not | returns opposite Boolean value | Operator Keyword |
| if | get into block if expression is true | conditional |
| elif | for more than 1 if checks | conditional |
| else | this block will be executed if condition is false | conditional |
| for | used for looping | iteration |
| while | used for looping | iteration |
| break | get out of loop | iteration |
| continue | skip for specific condition | iteration |
| def | make user defined function | structure |
| class | make user defined classes | structure |
| lambda | make anonymous function | structure |
| with | execute code within context manager's scope | structure |
| as | alias for something | structure |
| pass | used for making empty structures(declaration) | structure |
| return | get value(s) from function, get out of function | returning keyword |
| yield | yields values instead of returning (are called generators) | returning keyword |
| import | import libraries/modules/packages | import |
| from | import specific function/classes from modules/packages | import |
| try | this block will be tried to get executed | exception handling |
| except | is any exception/error has occured it'll be executed | exception handling |
| finally | It'll be executed no matter exception occurs or not | exception handling |
| raise | throws any specific error/exception | exception handling |
| assert | throws an AssertionError if condition is false | exception handling |
| async | used to define asynchronous functions/co-routines | asynchronous programming |
| await | used to specify a point when control is taken back | asynchronous programming |
| del | deletes/unsets any user defined data | variable handling |
| global | used to access variables defined outside of function | variable handling |
| nonlocal | modify variables from different scopes | variable handling |
<br>
## Operators
<br>
| Operator | Description |
|-|-|
| ( ) | grouping parenthesis, function call, tuple declaration |
| [ ] | array indexing, also declaring lists etc.|
| ! | relational not, complement, ! a yields true or false |
| ~ | bitwise not, ones complement, ~a |
| \- | unary minus, - a |
| \+ | unary plus, + a |
| \* | multiply, a * b |
| / | divide, a / b |
| % | modulo, a % b |
| \+ | add, a + b |
| \- | subtract, a - b |
| << | shift left, left operand is shifted left by right operand bits (multiply by 2) |
| \>> | shift right, left operand is shifted right by right operand bits (divide by 2) |
| < | less than, result is true or false, a %lt; b
| <= | less than or equal, result is true or false, a <= b
| \> | greater than, result is true or false, a > b
| \>= | greater than or equal, result is true or false, a >= b
| == | equal, result is true or false, a == b
| != | not equal, result is true or false, a != b
| & | bitwise and, a & b
| ^ | bitwise exclusive or XOR, a ^ b
| \| | bitwise or, a | b
| &&, and | relational and, result is true or false, a < b && c >= d
| \|\|, or | relational or, result is true or false, a < b \|\| c >= d |
| = | store or assignment |
| += | add and store |
| -= | subtract and store |
| *= | multiply and store |
| /= | divide and store|
| %= | modulo and store|
| <<= | shift left and store|
| \>>= | shift right and store|
| &= | bitwise and and store|
| ^= | bitwise exclusive or and store|
| \|= | bitwise or and store|
| , | separator as in ( y=x,z=++x )|
### Basic Data Structures
### List
- List is a collection which is ordered and changeable. Allows duplicate members.
- Lists are created using square brackets:
```python
thislist = ["apple", "banana", "cherry"]
```
- List items are ordered, changeable, and allow duplicate values.
- List items are indexed, the first item has index `[0]`, the second item has index `[1]` etc.
- The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
- To determine how many items a list has, use the `len()` function.
- A list can contain different data types:
```python
list1 = ["abc", 34, True, 40, "male"]
```
- It is also possible to use the list() constructor when creating a new list
```python
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
```
- pop() function removes the last value in the given list by default.
```python
thislist = ["apple", "banana", "cherry"]
print(thislist.pop()) # cherry
print(thislist.pop(0)) #apple
```
### Tuple
- Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
- A tuple is a collection which is ordered and unchangeable.
- Tuples are written with round brackets.
```python
thistuple = ("apple", "banana", "cherry")
```
- Tuple items are ordered, unchangeable, and allow duplicate values.
- Tuple items are indexed, the first item has index `[0]`, the second item has index `[1]` etc.
- When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.
- Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
- Since tuple are indexed, tuples can have items with the same value:
- Tuples allow duplicate values:
```python
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
```
- To determine how many items a tuple has, use the `len()`function:
```python
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
```
- To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
```python
thistuple = ("apple",)
print(type(thistuple))
# NOT a tuple
thistuple = ("apple")
print(type(thistuple))
```
- It is also possible to use the tuple() constructor to make a tuple.
```python
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
```
### Set
- Set is a collection which is unordered and unindexed. No duplicate members.
- A set is a collection which is both unordered and unindexed.
```python
thisset = {"apple", "banana", "cherry"}
```
- Set items are unordered, unchangeable, and do not allow duplicate values.
- Unordered means that the items in a set do not have a defined order.
- Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
- Sets are unchangeable, meaning that we cannot change the items after the set has been created.
- Duplicate values will be ignored.
- To determine how many items a set has, use the `len()` method.
```python
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
```
- Set items can be of any data type:
```python
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
set4 = {"abc", 34, True, 40, "male"}
```
- It is also possible to use the `set()` constructor to make a set.
```python
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
```
- frozenset() is just an immutable version of Set. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.
```python
set1 = {"apple", "banana", "cherry"}
frzset=frozenset(set1)
print(frzset)
```
### Dictionary
- Dictionary is a collection which is unordered and changeable. No duplicate members.
- Dictionaries are used to store data values in key:value pairs.
- Dictionaries are written with curly brackets, and have keys and values:
```python
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
```
- Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
```python
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
```
- Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
- Dictionaries cannot have two items with the same key.
- Duplicate values will overwrite existing values.
- To determine how many items a dictionary has, use the `len()` function.
```python
print(len(thisdict))
```
- The values in dictionary items can be of any data type
```python
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
```
- pop() Function is used to remove a specific value from a dictionary. You can only use key bot the value. Unlike Lists you have to give a value to this function
```python
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.pop("model")
print(x)# Mustang
print(car)#{'brand': 'Ford', 'year': 1964}
```
### Conditional branching
```python
if condition:
pass
elif condition2:
pass
else:
pass
```
### Loops
Python has two primitive loop commands:
1. while loops
2. for loops
#### While loop
- With the `while` loop we can execute a set of statements as long as a condition is true.
- Example: Print i as long as i is less than 6
```python
i = 1
while i < 6:
print(i)
i += 1
```
- The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1.
- With the `break` statement we can stop the loop even if the while condition is true
- With the continue statement we can stop the current iteration, and continue with the next.
- With the else statement we can run a block of code once when the condition no longer is true.
#### For loop
- A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
- This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
- With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
```python
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
```
- The for loop does not require an indexing variable to set beforehand.
- To loop through a set of code a specified number of times, we can use the range() function.
- The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
- The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3).
- The else keyword in a for loop specifies a block of code to be executed when the loop is finished.
A nested loop is a loop inside a loop.
- The "inner loop" will be executed one time for each iteration of the "outer loop":
```python
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
```
- for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.
```python
for x in [0, 1, 2]:
pass
```
### Function definition
```python
def function_name():
return
```
### Function call
```python
function_name()
```
* We need not to specify the return type of the function.
* Functions by default return `None`
* We can return any datatype.
+39
View File
@@ -0,0 +1,39 @@
##############################################################################
# AWS
##############################################################################
# General
aws help
aws --version # Show the current AWS CLI version
aws configure # Configure your AWS Key ID, AWS Secret, default region and default output format for the AWS CLI
aws configure --profile <profile_name> # Configure using the profile name. By default, the list of profile is stored in ~/.aws.credentials (Linux and MacOS)
# EC2
## We need to specify a region to use ec2 commands. We can configure a default region with "aws configure" or set the AWS_DEFAULT_REGION environment variable before the command line
## Example: AWS_DEFAULT_REGION=us-east-1 aws ec2 describe-instances
aws ec2 describe-instances # Desribe all instances in the current region
aws ec2 describe-instances --instance-ids <instance_id_1> <instance_id_2> # Describe specific instances by their IDs
aws ec2 describe-instances --filters Name=<instance_name> # Filter and describe instances by name
aws ec2 start-instances --instance-ids <instance_id_1> <instance_id_2> # Start previously stopped instances by their IDs
aws ec2 stop-instances --instance-ids <instance_id_1> <instance_id_2> # Stop running instances by their IDs
aws ec2 terminate-instances --instance-ids <instance_id_1> <instance_id_2> # Shutdown the specific instances by their IDs
# S3
## To specify the root directory of a S3 bucket, use this syntax: s3://<bucket_name>
aws s3 ls # List S3 objects and common prefixes under a prefix or all S3 buckets
aws s3 ls s3://<bucket_name> # List objects and common prefixes under a specified bucket and prefix
aws s3 mb s3://<bucket_name> # Create a specific S3 bucket
aws s3 rb s3://<bucket_name> # Remove an empty specific S3 bucket by name
aws s3 mv <local_file_path> s3://<bucket_name>/<destination_file_path> # Move a file in local_file_path to a specific bucket in destination_file_path
## Example: aws s3 mv text.txt s3://mybucket/text.txt
aws s3 mv s3://<bucket_name_1> s3://<bucket_name_2> --recursive # Move all objects from bucket_name_1 to bucket_name_2
aws s3 sync <source> <target> # Sync all contents from source to a target directory. This will copy and update all missing or outdated files or objects between source and target
## Examples: aws s3 sync . s3://mybucket
## aws s3 sync s3://bucket_1 s3://bucket_2
aws s3 sync <source> <target> --delete # Sync all contents from source to target, but this will remove all missing files and objects from the target that are not present in source
+115
View File
@@ -0,0 +1,115 @@
#!/bin/bash
##############################################################################
# BASICS
##############################################################################
# help
curl -h # help
curl --help # same as -h
curl --manual # whole man page
# verbose
curl -v # verbose
curl -vv # even more verbose
# redirect output to the file
curl http://url/file > file
# write to file instead of stdout
curl -o file http://url/file
curl --output file http://url/file
# write output to a file named as the remote file
curl -o file http://url/file
curl --output file http://url/file
# execute remote script
bash <(curl -s http://url/myscript.sh)
# download headers
curl -I url # display header
# basic authentification
curl --user username:password http://example.com/
curl -u username:password http://example.com/
# SSL
# -k, --insecure allow insecure server connections when using SSL
curl -k https://server_with_self_signed_cert/endpoint
curl --insecure https://server_with_self_signed_cert/endpoint
# HTTP request
# -X, --request <command> specify request command to use
# example:
curl -X GET http://url/endpoint
# HTTP header
# -H, --header <header/@file> pass custom header(s) to server
# example:
curl -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36' http://url/endpoing
# HTTP POST data
# -d, --data <data> HTTP POST data
# -d, --data @data HTTP POST data from file
# example:
curl -d '{json}' -H 'Content-Type: application/json' http://url/endpoint
# config file
curl -K file #
#or # Read config from a file
curl --config file #
$HOME/.curlrc # Default config file in UNIX-like systems
##############################################################################
# WRITE OUT PARAMETERS
##############################################################################
# -w, --write-out <format> Use output FORMAT after completion
# example:
curl -w %{size_header} --silent -o /dev/null http://gogle.com # print size of header when you accessing google.com
# FORMAT supported:
# %{content_type} # shows the Content-Type of the requested document, if there was any.
# %{filename_effective} # shows the ultimate filename that curl writes out to.
# This is only meaningful if curl is told to write to a file with
# the --remote-name or --output option. It's most useful in combination
# with the --remote-header-name option.
# %{ftp_entry_path} # shows the initial path curl ended up in when logging on to the remote FTP server.
# %{response_code} # shows the numerical response code that was found in the last transfer.
# %{http_connect} # shows the numerical code that was found in the last response (from a proxy)
# to a curl CONNECT request.
# %{local_ip} # shows the IP address of the local end of the most recently done connection—can
# be either IPv4 or IPv6
# %{local_port} # shows the local port number of the most recently made connection
# %{num_connects} # shows the number of new connects made in the recent transfer.
# %{num_redirects} # shows the number of redirects that were followed in the request.
# %{redirect_url} # shows the actual URL a redirect would take you to when an HTTP request
# was made without -L to follow redirects.
# %{remote_ip} # shows the remote IP address of the most recently made connection—can be
# either IPv4 or IPv6.
# %{remote_port} # shows the remote port number of the most recently made connection.
# %{size_download} # shows the total number of bytes that were downloaded.
# %{size_header} # shows the total number of bytes of the downloaded headers.
# %{size_request} # shows the total number of bytes that were sent in the HTTP request.
# %{size_upload} # shows the total number of bytes that were uploaded.
# %{speed_download} # shows the average download speed that curl measured for the complete download
# in bytes per second.
# %{speed_upload} # shows the average upload speed that curl measured for the complete upload in
# bytes per second.
# %{ssl_verify_result} # shows the result of the SSL peer certificate verification that was requested.
# 0 means the verification was successful.
# %{time_appconnect} # shows the time, in seconds, it took from the start until the SSL/SSH/etc connect/handshake
# to the remote host was completed.
# %{time_connect} # shows the time, in seconds, it took from the start until the TCP connect to the remote
# host (or proxy) was completed.
# %{time_namelookup} # shows the time, in seconds, it took from the start until the name resolving was completed.
# %{time_pretransfer} # shows the time, in seconds, it took from the start until the file transfer was just about
# to begin. This includes all pre-transfer commands and negotiations that are specific to
# the particular protocol(s) involved.
# %{time_redirect} # shows the time, in seconds, it took for all redirection steps including name lookup, connect,
# pre-transfer and transfer before the final transaction was started. time_redirect shows
# the complete execution time for multiple redirections.
# %{time_starttransfer} # shows the time, in seconds, it took from the start until the first byte was just about to
# be transferred. This includes time_pretransfer and also the time the server needed
# to calculate the result.
# %{time_total} # shows the total time, in seconds, that the full operation lasted. The time will be displayed
# with millisecond resolution.
# %{url_effective} # shows the URL that was fetched last. This is particularly meaningful if you have told curl
# to follow Location: headers (with -L)
+91
View File
@@ -0,0 +1,91 @@
##############################################################################
# DOCKER
##############################################################################
docker init # Creates Docker-related starter files
docker build -t friendlyname . # Create image using this directory's Dockerfile
docker run -p 4000:80 friendlyname # Run "friendlyname" mapping port 4000 to 80
docker run -d -p 4000:80 friendlyname # Same thing, but in detached mode
docker exec -it [container-id] bash # Enter a running container
docker ps # See a list of all running containers
docker stop <hash> # Gracefully stop the specified container
docker ps -a # See a list of all containers, even the ones not running
docker kill <hash> # Force shutdown of the specified container
docker rm <hash> # Remove the specified container from this machine
docker rm -f <hash> # Remove force specified container from this machine
docker rm $(docker ps -a -q) # Remove all containers from this machine
docker images -a # Show all images on this machine
docker rmi <imagename> # Remove the specified image from this machine
docker rmi $(docker images -q) # Remove all images from this machine
docker logs <container-id> -f # Live tail a container's logs
docker login # Log in this CLI session using your Docker credentials
docker tag <image> username/repository:tag # Tag <image> for upload to registry
docker push username/repository:tag # Upload tagged image to registry
docker run username/repository:tag # Run image from a registry
docker system prune # Remove all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes. (Docker 17.06.1-ce and superior)
docker system prune -a # Remove all unused containers, networks, images not just dangling ones (Docker 17.06.1-ce and superior)
docker volume prune # Remove all unused local volumes
docker network prune # Remove all unused networks
##############################################################################
# DOCKER COMPOSE
##############################################################################
docker-compose up # Create and start containers
docker-compose up -d # Create and start containers in detached mode
docker-compose down # Stop and remove containers, networks, images, and volumes
docker-compose logs # View output from containers
docker-compose restart # Restart all service
docker-compose pull # Pull all image service
docker-compose build # Build all image service
docker-compose config # Validate and view the Compose file
docker-compose scale <service_name>=<replica> # Scale special service(s)
docker-compose top # Display the running processes
docker-compose run -rm -p 2022:22 web bash # Start web service and runs bash as its command, remove old container.
##############################################################################
# DOCKER SERVICES
##############################################################################
docker service create <options> <image> <command> # Create new service
docker service inspect --pretty <service_name> # Display detailed information Service(s)
docker service ls # List Services
docker service ps # List the tasks of Services
docker service scale <service_name>=<replica> # Scale special service(s)
docker service update <options> <service_name> # Update Service options
##############################################################################
# DOCKER STACK
##############################################################################
docker stack ls # List all running applications on this Docker host
docker stack deploy -c <composefile> <appname> # Run the specified Compose file
docker stack services <appname> # List the services associated with an app
docker stack ps <appname> # List the running containers associated with an app
docker stack rm <appname> # Tear down an application
##############################################################################
# DOCKER MACHINE
##############################################################################
docker-machine create --driver virtualbox myvm1 # Create a VM (Mac, Win7, Linux)
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1 # Win10
docker-machine env myvm1 # View basic information about your node
docker-machine ssh myvm1 "docker node ls" # List the nodes in your swarm
docker-machine ssh myvm1 "docker node inspect <node ID>" # Inspect a node
docker-machine ssh myvm1 "docker swarm join-token -q worker" # View join token
docker-machine ssh myvm1 # Open an SSH session with the VM; type "exit" to end
docker-machine ssh myvm2 "docker swarm leave" # Make the worker leave the swarm
docker-machine ssh myvm1 "docker swarm leave -f" # Make master leave, kill swarm
docker-machine start myvm1 # Start a VM that is currently not running
docker-machine stop $(docker-machine ls -q) # Stop all running VMs
docker-machine rm $(docker-machine ls -q) # Delete all VMs and their disk images
docker-machine scp docker-compose.yml myvm1:~ # Copy file to node's home dir
docker-machine ssh myvm1 "docker stack deploy -c <file> <app>" # Deploy an app
+66
View File
@@ -0,0 +1,66 @@
##############################################################################
# DRUSH
# Install: https://www.drush.org/install/
# Usage: https://www.drush.org/usage/
##############################################################################
cache clear (cc) # Clear all caches.
cron # Run all cron hooks.
disable (dis) # Disable one or more modules.
download (dl) # Download core Drupal and projects like CCK, Zen, etc.
enable (en) # Enable one or more modules.
eval # Evaluate arbitrary php code after bootstrapping Drupal.
help # Print this help message. Use --filter to limit command list to one command file (e.g. --filter=pm)
info # Release information for a project
installcore (ic) # Install Drupal core via the specified install profile. Note that updating core with Drush is not yet available. See http://drupal.org/node/434944.
refresh (rf) # Refresh update status information script Runs the given php script(s) after a full Drupal bootstrap. NOTE: you can't supply absolute paths to the script e.g. ~/Desktop/script.php won't work Desktop/script.php will
sql cli (sqlc) # Open a SQL command-line interface using Drupal?s credentials.
sql conf # Print database connection details.
sql connect # A string for connecting to the DB.
sql dump # Exports the Drupal DB as SQL using mysqldump.
sql load # Copy source database to target database.
sql query (sqlq) # Execute a query against the site database.
status (st) # Provides a birds-eye view of the current Drupal installation, if any.
statusmodules (sm) # Show module enabled/disabled status
sync # Rsync the Drupal tree to/from another server using ssh.
test clean # Delete leftover tables and files from prior test runs.
test mail # Run all tests and mail the results to your team.
uninstall # Uninstall one or more modules.
update (up) # Update your project code and apply any database updates required (update.php)
updatecode (upc) # Update your project code. Moves existing project files to the backup directory specified in the config.
updatedb (updb) # Execute the update.php process from the command line.
variable delete (vdel) # Delete a variable.
variable get (vget) # Get a list of some or all site variables and values.
variable set (vset) # Set a variable.
watchdog delete (wd) # Delete all messages or only those of a specified type.
watchdog show (ws) # Shows recent watchdog log messages. Optionally filter for a specific type.
+13
View File
@@ -0,0 +1,13 @@
/* *******************************************************************************************
* ELASTICSEARCH
* https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html
* https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html
* ******************************************************************************************* */
sudo service elasticsearch status -l // Check elasticsearch status
sudo service kibana restart // Restart kibana
sudo service elasticsearch restart // Restart elasticsearch
brew services elasticsearch-full restart
sudo /usr/share/elasticsearch/bin/elasticsearch --version // Check ElasticSearch version
sudo /usr/share/kibana/bin/kibana --version // Check kibana version
+282
View File
@@ -0,0 +1,282 @@
# EMMET
*The essential toolkit for web-developers*
## Introduction
Emmet is a productivity toolkit for web developers that uses expressions to generate HTML snippets.
## Installation
Normally, installation for Emmet should be a straight-forward process from the package-manager, as most of the modern text editors support Emmet. If you have difficulty setting up emmet with your editor and wish to check Emmet is supported by your favourite editor or not, you can check it from here. [Emmet Installation instructions](https://emmet.io/download/)
## Usage
You can use Emmet in two ways:
* Tab Expand Way: Type your emmet code and press `Tab` key
* Interactive Method: Press `alt + ctrl + Enter` and start typing your expressions. This should automatically generate HTML snippets on the fly.
__This cheatsheet will assume that you press `Tab` after each expressions.__
## HTML
### Generating HTML 5 DOCTYPE
`html:5`
Will generate
```HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>
```
### Child items
Child items are created using `>`
`ul>li>p`
```html
<ul>
<li>
<p></p>
</li>
</ul>
```
### Sibling Items
Sibling items are created using `+`
`html>head+body`
```html
<html>
<head></head>
<body>
</body>
</html>
```
### Multiplication
Items can be multiplied by `*`
`ul>li*5`
```html
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
```
### Grouping
Items can be grouped together using `()`
`table>(tr>th*5)+tr>t*5`
```html
<table>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<t></t>
<t></t>
<t></t>
<t></t>
<t></t>
</tr>
</table>
```
### Class and ID
Class and Id in Emmet can be done using `.` and `#`
`div.heading`
```html
<div class="heading"></div>
```
`div#heading`
```html
<div id="heading"></div>
```
ID and Class can also be combined together
`div#heading.center`
```html
<div id="heading" class="center"></div>
```
### Adding Content inside tags
Contents inside tags can be added using `{}`
`h1{Emmet is awesome}+h2{Every front end developers should use this}+p{This is paragraph}*2`
```HTML
<h1>Emmet is awesome</h1>
<h2>Every front end developers should use this</h2>
<p>This is paragraph</p>
<p>This is paragraph</p>
```
### Attributes inside HTML tags
Attributes can be added using `[]`
`a[href=https://google.com data-toggle=something target=_blank]`
```HTML
<a href="https://google.com" data-toggle="something" target="_blank"></a>
```
### Numbering
Numbering can be done using `$`
You can use this inside tag or contents.
`h${This is so awesome $}*6`
```HTML
<h1>This is so awesome 1</h1>
<h2>This is so awesome 2</h2>
<h3>This is so awesome 3</h3>
<h4>This is so awesome 4</h4>
<h5>This is so awesome 5</h5>
<h6>This is so awesome 6</h6>
```
Use `@-` to reverse the Numbering
`img[src=image$$@-.jpg]*5`
```HTML
<img src="image05.jpg" alt="">
<img src="image04.jpg" alt="">
<img src="image03.jpg" alt="">
<img src="image02.jpg" alt="">
<img src="image01.jpg" alt="">
```
To start the numbering from specific number, use this way
`img[src=emmet$@100.jpg]*5`
```HTML
<img src="emmet100.jpg" alt="">
<img src="emmet101.jpg" alt="">
<img src="emmet102.jpg" alt="">
<img src="emmet103.jpg" alt="">
<img src="emmet104.jpg" alt="">
```
## Tips
* Use `:` to expand known abbreviations
`input:date`
```HTML
<input type="date" name="" id="">
```
`form:post`
```HTML
<form action="" method="post"></form>
```
`link:css`
```html
<link rel="stylesheet" href="style.css">
```
* Building Navbar
`.navbar>ul>li*3>a[href=#]{Item $@-}`
```HTML
<div class="navbar">
<ul>
<li><a href="#">Item 3</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 1</a></li>
</ul>
</div>
```
## CSS
Emmet works surprisingly well with css as well.
* `f:l`
```css
float: left;
```
You can also use any options n/r/l
* `pos:a­`
```css
position: absolute;
```
Also use any options, pos:a/r/f
* `d:n/b­/f/­i/ib`
`d:ib`
```css
display: inline-block;
```
* You can use `m` for margin and `p` for padding followed by direction
`mr` -> `margin-right`
`pr` -> `padding-right`
* `@f` will result in
```css
@font-face {
font-family:;
src:url();
}
```
You can also use these shorthands
| Shorthand | Description |
| ----------- | ----------- |
| z | z-index |
| w | width |
| h | height |
| fz | font-size |
| ff | font-family |
| fw | font-weight |
| @lh | line-height |
| maw | max-width |
| mah | max-height |
| miw | min-width |
| mih | min-width |
| ! | !important |
| @f | font-face |
| @op | opacity |
| @lh | line-height |
| @op | opacity |
+140
View File
@@ -0,0 +1,140 @@
# Firebase CLI Guide
Firebase CLI (Command Line Interface) is a powerful tool that allows developers to interact with Firebase services and manage their Firebase projects directly from the command line. It provides a convenient and efficient way to deploy projects, manage databases, configure authentication, and more, streamlining the development and deployment processes.
## Installation
To use the Firebase CLI, you need to have Node.js and npm (Node Package Manager) installed on your system. Follow the steps below to install the Firebase CLI:
1. Install Node.js and npm by downloading the installer from the [official Node.js website](https://nodejs.org/en/download/) and following the installation instructions for your operating system.
2. Once Node.js and npm are installed, open your terminal or command prompt and run the following command to install the Firebase CLI globally:
```
npm install -g firebase-tools
```
This command will download and install the Firebase CLI package from the npm registry.
3. After the installation is complete, you can verify that the Firebase CLI is installed correctly by running the following command:
```
firebase --version
```
If the installation was successful, you will see the version number of the Firebase CLI printed in the terminal.
Congratulations! You have successfully installed the Firebase CLI.
## Usage
The Firebase CLI allows you to interact with Firebase services and manage your Firebase projects from the command line. Here are some common tasks you can perform using the Firebase CLI:
- Initialize a new Firebase project in your current directory.
- Deploy your Firebase project to Firebase hosting.
- Manage Firebase Authentication, Realtime Database, Cloud Firestore, Cloud Functions, and other Firebase services.
- Configure Firebase project settings.
- Interact with Firebase emulators for local development and testing.
To use the Firebase CLI, open your terminal or command prompt and run the `firebase` command followed by the desired command and options.
Here's an example of the basic usage:
```
firebase <command> [options]
```
Replace `<command>` with the specific Firebase command you want to execute, and `[options]` with any additional options or flags required for that command.
For more detailed usage information, you can run the following command:
```
firebase help
```
This command will display the available Firebase commands and provide detailed information about each command.
## Commands
Here are the commonly used Firebase CLI commands along with a brief explanation, syntax, and an example for each command:
- `firebase init`: Initializes a new Firebase project in the current directory.
- Syntax: `firebase init [options]`
- Example: `firebase init hosting` initializes Firebase Hosting for the current project.
- `firebase deploy`: Deploys your Firebase project to Firebase hosting or other Firebase services.
- Syntax: `firebase deploy [options]`
- Example: `firebase deploy --only hosting` deploys only the Firebase Hosting content.
- `firebase serve`: Starts local development servers and Firebase emulators.
- Syntax: `firebase serve [options]`
- Example: `firebase serve --only functions,hosting` starts the Firebase emulators for functions and hosting.
- `firebase login`: Authenticates the Firebase CLI with your Firebase account.
- Syntax: `firebase login [options]`
- Example: `firebase login --no-localhost` initiates an interactive login session without connecting to localhost.
- `firebase logout`: Logs out from the Firebase CLI.
- Syntax: `firebase logout [options]`
- Example: `firebase logout` logs out the currently authenticated user.
- `firebase use`: Sets the active Firebase project for the current directory.
- Syntax: `firebase use <project_id> [options]`
- Example: `firebase use my-project` sets "my-project" as the active Firebase project.
- `firebase functions`: Interacts with Firebase Cloud Functions.
- Syntax: `firebase functions:command [options]`
- Example: `firebase functions:delete [function_name]` deletes all functions that match the specified name in all regions.
- `firebase database`: Interacts with Firebase Realtime Database.
- Syntax: `firebase database:command [options]`
- Example: `firebase database:get /users` retrieves data from the Firebase Realtime Database.
- `firebase firestore`: Interacts with Firebase Cloud Firestore.
- Syntax: `firebase firestore:command [options]`
- Example: `firebase firestore:delete collection/document` deletes a document from the Firestore database.
- `firebase auth`: Interacts with Firebase Authentication.
- Syntax: `firebase auth:command [options]`
- Example: `firebase auth:export users.csv` exports user data to a CSV file.
- `firebase hosting`: Interacts with Firebase Hosting.
- Syntax: `firebase hosting:command [options]`
- Example: `firebase hosting:disable` disables Firebase Hosting for the current project.
- `firebase remoteconfig`: Interacts with Firebase Remote Config.
- Syntax: `firebase remoteconfig:command [options]`
- Example: `firebase remoteconfig:get template` retrieves the Remote Config template.
- `firebase ext`: Interacts with Firebase Extensions.
- Syntax: `firebase ext:command [options]`
- Example: `firebase ext:install firebase/delete-user-data` installs the Firebase Extension named "firebase/delete-user-data".
- `firebase appdistribution`: Interacts with Firebase App Distribution.
- Syntax: `firebase appdistribution:command [options]`
- Example: `firebase appdistribution:testers:add` Adds testers to the project.
- `firebase use --add`: Adds an existing Firebase project to the current directory
- Syntax: `firebase use --add`
- Example: `firebase use --add` interactively adds an existing Firebase project.
- `firebase projects:create`: Creates a new Firebase project.
- Syntax: `firebase projects:create [options]`
- Example: `firebase projects:create --display-name "My Project"` creates a new Firebase project with the given display name.
These are just a few examples of the available commands. You can explore more commands and their options by running `firebase help` or visiting the [official Firebase CLI documentation](https://firebase.google.com/docs/cli).
+178
View File
@@ -0,0 +1,178 @@
# GCLOUD SDK AND TOOLBELT CHEATSHEET
## GCP BASICS
- `Check Version and Settings`: gcloud version, gcloud info, gcloud components list
- `Init Profile`: gcloud init This will ask you to open an OpenID URL
- `List all zones`: gcloud compute zones list
- `Upgrade local SDK`: gcloud components update, gcloud components update --version 219.0.1
## BUCKET BASICS
- `List all buckets and files`: gsutil ls, gsutil ls -lh gs://<bucket-name>
- `Download file`: gsutil cp gs://<bucket-name>/<dir-path>/package-1.1.tgz .
- `Upload file`: gsutil cp <filename> gs://<bucket-name>/<directory>/
- `Cat file`: gsutil cat gs://<bucket-name>/<filepath>/
- `Delete file`: gsutil rm gs://<bucket-name>/<filepath>
- `Move file`: gsutil mv <src-filepath> gs://<bucket-name>/<directory>/<dest-filepath>
- `Copy folder`: gsutil cp -r ./conf gs://<bucket-name>/
- `Show disk usage`: gsutil du -h gs://<bucket-name>/<directory>/
- `Create bucket`: gsutil mb gs://<bucket-name>
- `Caculate file sha1sum`: gsha1sum syslog-migration-10.0.2.tgz, shasum syslog-migration-10.0.2.tgz
- `Gsutil help`: gsutil help, gsutil help cp, gsutil help options
## GCP PROJECT
- `List projects `: gcloud config list, gcloud config list project
- `Show project info `: gcloud compute project-info describe
- `Switch project `: gcloud config set project <project-id>
## GKE
- `Display a list of credentialed accounts `: gcloud auth list
- `Set the active account `: gcloud config set account <ACCOUNT>
- `Set kubectl context `: gcloud container clusters get-credentials <cluster-name>
- `Change region `: gcloud config set compute/region us-west
- `Change zone `: gcloud config set compute/zone us-west1-b
- `List all container clusters `: gcloud container clusters list
## IAM
- `Authenticate client `: gcloud auth activate-service-account --key-file <key-file>
- `Display a list of credentialed accounts `: gcloud auth list
- `Set the active account `: gcloud config set account <ACCOUNT>
- `Auth to GCP Container Registry `: gcloud auth configure-docker
- `Print token for active account `: gcloud auth print-access-token, gcloud auth print-refresh-token
- `Revoke previous generated credential `: gcloud auth <application-default> revoke
## BUCKET SECURITY
- `Make all files readable `: gsutil -m acl set -R -a public-read gs://<bucket-name>/
- `Config auth `: gsutil config -a
- `Grant bucket access `: gsutil iam ch user:denny@gmail.com:objectCreator,objectViewer gs://<bucket-name>
- `Remove bucket access `: gsutil iam ch -d user:denny@gmail.com:objectCreator,objectViewer gs://<bucket-name>
## VM
- `List all instances `: gcloud compute instances list, gcloud compute instance-templates list
- `Show instance info `: gcloud compute instances describe "<instance-name>" --project "<project-name>" --zone "us-west2-a"
- `Stop an instance `: gcloud compute instances stop instance-2
- `Start an instance `: gcloud compute instances start instance-2
- `Create an instance `: gcloud compute instances create vm1 --image image-1 --tags test --zone "<zone>" --machine-type f1-micro
- `SSH to instance `: gcloud compute ssh --project "<project-name>" --zone "<zone-name>" "<instance-name>"
- `Download files `: gcloud compute copy-files example-instance:~/REMOTE-DIR ~/LOCAL-DIR --zone us-central1-a
- `Upload files `: gcloud compute copy-files ~/LOCAL-FILE-1 example-instance:~/REMOTE-DIR --zone us-central1-a
## DISKS & VOLUMES
- `List all disks `: gcloud compute disks list
- `List all disk types `: gcloud compute disk-types list
- `List all snapshots `: gcloud compute snapshots list
- `Create snapshot `: gcloud compute disks snapshot <diskname> --snapshotname <name1> --zone $zone
## NETWORK
- `List all networks `: gcloud compute networks list
- `Detail of one network `: gcloud compute networks describe <network-name> --format json
- `Create network `: gcloud compute networks create <network-name>
- `Create subnet `: gcloud compute networks subnets create subnet1 --network net1 --range 10.5.4.0/24
- `Get a static ip `: gcloud compute addresses create --region us-west2-a vpn-1-static-ip
- `List all ip addresses `: gcloud compute addresses list
- `Describe ip address `: gcloud compute addresses describe <ip-name> --region us-central1
- `List all routes `: gcloud compute routes list
## DNS
- `List of all record-sets in my zone `: gcloud dns record-sets list --zone my_zone
- `List first 10 DNS records `: gcloud dns record-sets list --zone my_zone --limit=10
## FIREWALL
- `List all firewall rules `: gcloud compute firewall-rules list
- `List all forwarding rules `: gcloud compute forwarding-rules list
- `Describe one firewall rule `: gcloud compute firewall-rules describe <rule-name>
- `Create one firewall rule `: gcloud compute firewall-rules create my-rule --network default --allow tcp:9200 tcp:3306
- `Update one firewall rule `: gcloud compute firewall-rules update default --network default --allow tcp:9200 tcp:9300
## IMAGES & CONTAINERS
- `List all images `: gcloud compute images list
- `List all container clusters `: gcloud container clusters list
- `Set kubectl context `: gcloud container clusters get-credentials <cluster-name>
## RDS
- `List all sql instances `: gcloud sql instances list
## SERVICES
- `List my backend services `: gcloud compute backend-services list
- `List all my health check endpoints `: gcloud compute http-health-checks list
- `List all URL maps `: gcloud compute url-maps list
+175
View File
@@ -0,0 +1,175 @@
git init # initiates git in the current directory
git remote add origin https://github.com/repo_name.git # add remote reposiory
git clone <address> # creates a git repo from given address (get the address from your git-server)
git clone <address> -b <branch_name> <path/to/directory> # clones a git repo from the address into the given directory and checkout's the given branch
git clone <address> -b <branch_name> --single-branch # Clones a single branch
git add <file_name> # adds(stages) file.txt to the git
git add * # adds(stages) all new modifications, deletions, creations to the git
git reset file.txt # Removes file.txt from the stage
git reset --hard # Throws away all your uncommitted changes, hard reset files to HEAD
git reset --soft <commit_id> # moves the head pointer
git reset --mixed <commit_id> # moves the head pointer and then copies the files from the commit it is now pointing to the staging area,
# the default when no argument is provided
git reset -hard <commit_id> # moves the head pointer and then copies the files from the commit it is now pointing to the staging area
# and working directory thus, throw away all uncommitted changes
# git reset
# 1. Move HEAD and current branch
# 2. Reset the staging area
# 3. Reset the working area
# --soft = (1)
# --mixed = (1) & (2) (default)
# --hard = (1) & (2) & (3)
git rm file.txt # removes file.txt both from git and file system
git rm --cached file.txt # only removes file.txt both from git index
git status # shows the modifications and stuff that are not staged yet
git branch # shows all the branches (current branch is shown with a star)
git branch -a # shows all the branches local and remote
git branch my-branch # creates my-branch
git branch -d my-branch # deletes my-branch
git checkout my-branch # switches to my-branch
git merge my-branch # merges my-branch to current branch
git push origin --delete my-branch # delete remote branch
git branch -m <new-branch-name> # rename the branch
git checkout --orphan <branch_name> # checkout a branch with no commit history
git branch -vv # list all branches and their upstreams, as well as last commit on branch
git branch -a # List all local and remote branches
git cherry-pick <commit_id> # merge the specified commit
git cherry-pick <commit_id_A>^..<commit_id_B> # pick the entire range of commits where A is older than B ( the ^ is for including A as well )
git remote # shows the remotes
git remote -v # shows the remote for pull and push
git remote add my-remote <address> # creates a remote (get the address from your git-server)
git remote rm my-remote # Remove a remote
git log # shows the log of commits
# git log by default uses less command so you can use these: f=next page, b=prev page, search=/<query>, n=next match, p=prev match, q=quit
git log --no-pager # shows the log of commits without less command
git log --oneline # shows the log of commits, each commit in a single line
git log --oneline --graph --decorate # shows the log of commits, each commit in a single line with graph
git log --since=<time> # shows the log of commits since given time
git log -- <file_name>
git log -p <file_name> # change over time for a specific file
git log <Branch1> ^<Branch2> # lists commit(s) in branch1 that are not in branch2
git log -n <x> # lists the last x commits
git log -n <x> --oneline # lists the last x commits, each commit in single line
git grep --heading --line-number '<string/regex>' # Find lines matching the pattern in tracked files
git log --grep='<string/regex>' # Search Commit log
git reflog # record when the tips of branches and other references were updated in the local repository.
git ls-files # show information about files in the index and the working tree
git commit -m "msg" # commit changes with a msg
git commit -m "title" -m "description" # commit changes with a title and description
git commit --amend # combine staged changes with the previous commit, or edit the previous commit message without changing its snapshot
git commit --amend --no-edit # amends a commit without changing its commit message
git commit --amend --author='Author Name <email@address.com>' # Amend the author of a commit
git push my-remote my-branch # pushes the commits to the my-remote in my-branch (does not push the tags)
git revert <commit-id> # Undo a commit by creating a new commit
git show # shows one or more objects (blobs, trees, tags and commits).
git diff # show changes between commits, commit and working tree
git diff HEAD #show changes between working directory vs last commit
git diff --staged HEAD #show changes between stage area vs last commit
git diff --color # show colored diff
git diff --staged # Shows changes staged for commit
git tag # shows all the tags
git tag -a v1.0 -m "msg" # creates an annotated tag
git show v1.0 # shows the description of version-1.0 tag
git tag --delete v1.0 # deletes the tag in local directory
git push --delete my-remote v1.0 # deletes the tag in my-remote (be carefore to not delete a branch)
git push my-remote my-branch v1.0 # push v1.0 tag to my-remote in my-branch
git fetch --tags # pulls the tags from remote
git pull my-remote my-branch # pulls and tries to merge my-branch from my-remote to the current branch git pull = git fetch && get merge
git stash # stashes the staged and unstaged changes (git status will be clean after it)
git stash -u # stash everything including new untracked files (but not .gitignore)
git stash save "msg" # stash with a msg
git stash list # list all stashes
git stash pop # delete the recent stash and applies it
git stash pop stash@{2} # delete the {2} stash and applies it
git stash show # shows the description of stash
git stash apply # keep the stash and applies it to the git
git stash branch my-branch stash@{1} # creates a branch from your stash
git stash drop stash@{1} # deletes the {1} stash
git stash clear # clears all the stash
git rebase -i <commit_id> # Rebase commits from a commit ID
git rebase --abort # Abort a running rebase
git rebase --continue # Continue rebasing after fixing all conflicts
git clean -f # clean untracked files permanently
git clean -f -d/git clean -fd # To remove directories permanently
git clean -f -X/git clean -fX # To remove ignored files permanently
git clean -f -x/git clean -fx # To remove ignored and non-ignored files permanently
git clean -d --dry-run # shows what would be deleted
git config --global --list # lists the git configuration for all repos
git config --global --edit # opens an editor to edit the git config file
git config --global alias.<handle> <command> # add git aliases to speed up workflow , eg.
# if handle is st and command is status then running git st would execute git status
git config --global core.editor <editor_name> # config default editor
git archive <branch_name> --format=zip --outpute=./<archive_name>.zip # create an archive of files from a named tree
.gitignore
# is a file including names of stuff that you don"t want to be staged or tracked.
# You usually keep your local files like database, media, etc here.
# You can find good resources online about ignoring specific files in your project files.
# .gitignore is also get ignored
.git
# is a hidden directory in repo directory including git files. It is created after "git init".
# Some useful notes:
# Better Commit messages:
# Key to Effective Debugging
# For the commit message to help in debugging effectively, ensure that it is short and use an imperative
# mood (spoken or written as if giving a command or instruction) when constructing them.
# Also use feature tense for commit messages.
# The first word in your commit message should be one of these:
# Add
# Create
# Refactor
# Fix
# Release
# Document
# Modify
# Update
# Remove
# Delete etc...
# About resetting:
# Use git revert instead of git reset in shared repositories
# git revert creates a new commit that introduces the opposite changes from the specified commit.
# Revert does not change history the original commit stays in the repository
# Difference between ~ and ^ in git:
# > ^ or ^n
# >no args: == ^1: the first parent commit
# >n: the nth parent commit
# > ~ or ~n
# >no args: == ~1: the first commit back, following 1st parent
# >n: number of commits back, following only 1st parent
# note: ^ and ~ can be combined
# Some tools to improve git skill by visualizing it:
# https://git-school.github.io/visualizing-git/
# https://learngitbranching.js.org/
+118
View File
@@ -0,0 +1,118 @@
# ##############################################################################
##### HEROKU TOOLBELT COMPLETE GUIDE ###########################################
################################################################################
# Installing Heroku toolbelt using command line
# For MacOS...
brew tap heroku/brew && brew install heroku
# For Ubuntu...
sudo snap install --classic heroku
# Other installation methods are
curl https://cli-assets.heroku.com/install.sh | sh # only for unix based systems, windows incompatible as it needs sudo
curl https://cli-assets.heroku.com/install-ubuntu.sh | sh # Ubuntu/Debian apt-get
yay -S heroku-cli # Arch linux, Note: This package is community maintained not by heroku
npm install -g heroku # This installation method is required for users on ARM and BSD...
############
# Verifying your installation
heroku --version
# Let's get started with heroku
heroku login # To login into the heroku toolbelt with your heroku account, this will open browser for you.
heroku login -i # If you prefer to stay in the command line environment, then you can execute this command
# Now navigate to your desired directory and create a blank heroku application
cd ~/myapp
heorku create
# If you are facing login issues, try to execute the following command
mv ~/.netrc ~/.netrc.backup
heroku login
# Uninstalling the heroku CLI
# For macOS
rm -rf /usr/local/heroku /usr/local/lib/heroku /usr/local/bin/heroku ~/.local/share/heroku ~/Library/Caches/heroku
# or you can try the below command also on macOS
brew uninstall heroku
rm -rf ~/.local/share/heroku ~/Library/Caches/heroku
# For Linux (Standalone installs)
rm /usr/local/bin/heroku
rm -rf /usr/local/lib/heroku /usr/local/heroku
rm -rf ~/.local/share/heroku ~/.cache/heroku
# For Linux (Debian and Ubuntu installs)
sudo apt-get remove heroku heroku-toolbelt
sudo rm /etc/apt/sources.list.d/heroku.list
#####################################################################################################
### Managing and deploying applications on Heroku (Using Git) ###################################
#####################################################################################################
cd myapp # Changing into the project directory
git init # Initializing the project into a git repository
git add -f example.json # Adding a perticular content of the project into the repository this will include the content from .gitignore
git add . # Adding all the contents of the project into the repository excluding .gitignore content
git commit -m "My first commit" # Commiting the content to the repository
heroku create appname # Creating a new application on Heroku here ( appname ) represent the name u give to your app
git remote -v # verifying that the remote is set to the heroku
heroku git:remote -a thawing-inlet-61413 # For an existing heroku app, you can add remote to the application
git remote rename heroku heroku-staging # renaming remotes
git push heroku master # Deploying code to the heroku application
git push heroku master --force # Force Pushing to heroku ( required if the remote contain works that u do not have locally )
git push heroku testbranch:master # Deploying code from a non-master branch to the heroku application
heroku create --ssh-git # ssh git transport for the application instead of https
git config --global url.ssh://git@heroku.com/.insteadOf https://git.heroku.com/ # For using ssh always
git config --global --remove-section url.ssh://git@heroku.com/ # To remove this rewrite setting run the command
#####################################################################################################
### Managing and deploying applications on Heroku (Using Docker) ###################################
#####################################################################################################
# Setting stack of your app to a Container
heroku stack:set container
heroku container:login # Login to the container resistry
git clone https://github.com/heroku/alpinehelloworld.git # Get sample code by cloning into the following repository
heroku create appname # Creating a heroku application here ( appname ) represent the name u give to your app
heroku container:push web # Build the image and push to Container Registry
heroku container:push --recursive # Pushing from the root directory of the project in recursive manner
heroku container:push web worker --recursive # Building the image and pushing to container resistry in recursive manner
heroku container:release web # Releasing the image to your application
heroku open # Open the application in the browser
+179
View File
@@ -0,0 +1,179 @@
# Kubernetes
* PDF: https://sematext.com/kubernetes-cheat-sheet/
* WEBSITE: https://kubernetes.io/
* DOCUMENTATION: https://kubernetes.io/docs/home
## Client Configuration
* Setup autocomplete in bash; bash-completion package should be installed first
```
source <(kubectl completion bash)
```
* View Kubernetes config
```
kubectl config view
```
* View specific config items by json path
```
kubectl config view -o jsonpath='{.users[?(@.name == "k8s")].user.password}'
```
* Set credentials for `foo.kuberntes.com`
```
kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword
```
* Set active namespace
```
kubectl config set-context --current --namespace=namespace_name
```
## Viewing, Finding resources
* List all services in the namespace
```
kubectl get services
```
* List all pods in all namespaces in wide format
```
kubectl get pods -o wide --all-namespaces
```
* List all pods in json (or yaml) format
```
kubectl get pods -o json
```
* Describe resource details (node, pod, svc)
```
kubectl describe nodes my-node
```
* List services sorted by name
```
kubectl get services --sort-by=.metadata.name
```
* List pods sorted by restart count
```
kubectl get pods --sort-by='.status.containerStatuses[0].restartCount'
```
* Rolling update pods for frontend-v1
```
kubectl rolling-update frontend-v1 -f frontend-v2.json
```
* Scale a replicaset named 'foo' to 3
```
kubectl scale --replicas=3 rs/foo
```
* Scale a resource specified in "foo.yaml" to 3
```
kubectl scale --replicas=3 -f foo.yaml
```
* Execute a command in every pod / replica
```
for i in 0 1; do kubectl exec foo-$i -- sh -c 'echo $(hostname) > /usr/share/nginx/html/index.html'; done
```
## Manage Resources
* Get documentation for pod or service
```
kubectl explain pods,svc
```
* Create resource(s) like pods, services or daemonsets
```
kubectl create -f ./my-manifest.yaml
```
* Apply a configuration to a resource
```
kubectl apply -f ./my-manifest.yaml
```
* Start a single instance of Nginx
```
kubectl run nginx --image=nginx
```
* Create a secret with several keys
```
cat <<EOF | kubectl create -f -
apiVersion: v1
kind: Secret
metadata:
name: mysecret
type: Opaque
data:
password: $(echo "s33msi4" | base64)
username: $(echo "jane"| base64)
EOF
```
* Delete a resource
```
kubectl delete -f ./my-manifest.yaml
```
## Monitoring & Logging
* Deploy Heapster from Github repository
```
kubectl create -f deploy/kube-config/standalone/
```
* Show metrics for nodes
```
kubectl top node
```
* Show metrics for pods
```
kubectl top pod
```
* Show metrics for a given pod and its containers
```
kubectl top pod pod_name --containers
```
* Dump pod logs (stdout)
```
kubectl logs pod_name
```
* Stream pod container logs (stdout, multi-container case)
```
kubectl logs -f pod_name -c my-container
```
## Interacting with running pods
* Run command in pod
```
kubectl exec pod_name -- command_name
```
* Run command in pod with multiple containers
```
kubectl exec pod_name -c container_name -- command_name
```
* Get terminal of pod
```
kubectl exec -it pod_name /bin/sh
```
* Get terminal of a container running in pod with multiple containers
```
kubectl exec -it pod_name -c container_name /bin/sh
```
+1
View File
@@ -0,0 +1 @@
sudo lsof -i -P | grep LISTEN # List all processes running on a specific port
+250
View File
@@ -0,0 +1,250 @@
# *****************************************************************************
# SECTIONS OF THE BOXFILE
# *****************************************************************************
# Boxfiles consist of a handful of sections or "nodes": run.config, deploy.config, web, worker, data.
# These are covered in detail in the next few docs, but here are some quick descriptions:
# run.config - Defines the build, environment, and configuration for web and worker components.
# deploy.config - Defines deploy hooks and possible code transformations.
# web - Defines settings unique to each web component.
# worker - Defines settings unique to each worker component.
# data - Defines settings unique to a specific data component.
# *****************************************************************************
# RUN.CONFIG
# https://docs.nanobox.io/boxfile/run-config/
# *****************************************************************************
run.config:
# Engine
engine: engine-name
# Configuration used by the engine
engine.config:
runtime: ruby-2.3
# Contents of these dirs to be cached inside of Nanobox
cache_dirs:
- vendor
- packages
# Extra Packages (in addition to what the engine installs)
extra_packages:
- nodejs
- newrelic
# Dev Packages
dev_packages:
- psutils
# Build Triggers - Changes to these files automatically
# trigger a new build the next time a build is required.
build_triggers:
- Gemfile
- Gemfile.lock
- package.json
# Additions to $PATH
extra_path_dirs:
- vendor/bin
# Custom commands to prepare the environment
extra_steps:
- npm install
# Enable filesystem watcher
fs_watch: true
# *****************************************************************************
# DEPLOY.CONFIG
# https://docs.nanobox.io/boxfile/deploy-config/
# *****************************************************************************
deploy.config:
# Custom commands to prepare the production environment
extra_steps:
- mv config-prod.yml config.yml
# Run after your code has been deployed to your live app,
# but before everything is locked down with read-only permissions and distributed into new containers/servers.
transform:
- 'sed -i /HOST/$DATA_DB_HOST/g config/database.xml'
- 'if [ "$ENV" = "prod" ]; then mv config-prod.yml config.yml; fi'
# Run command on any one instance of web.main component before activation
before_live:
web.main:
- 'bundle exec rake clear-cache'
# Run command on all instances of web.main component before activation
before_live_all:
web.main:
- 'bundle exec rake register-nodes'
# Run command on any one instance of web.main component after activation
after_live:
worker.mail:
- 'bundle exec rake prime-cache'
# Run command on all instances of web.main component after activation
after_live_all:
worker.mail:
- 'bundle exec rake prime-local-cache'
# Set a timeout for your deploy hooks
hook_timeout: 300
# *****************************************************************************
# WEB
# https://docs.nanobox.io/boxfile/web/
# *****************************************************************************
web.site:
# Start Command
start: start-command
# Stop Config
stop: stop-command
stop_force: false
stop_timeout: 60
# Current Working Directory
cwd: directory
# Routing
routes:
- 'sub:/path/'
- '/admin/'
# Port Mapping
ports:
- tcp:21:3420
- udp:53:3000
# Network Storage
network_dirs:
data.files:
- path/to/directoryA
- path/to/directoryB
data.unfs:
- path/to/directoryC
# Writable Dirs
writable_dirs:
- path/to/dirA
- path/to/dirB
# Custom Logs
log_watch:
app[error]: /app/path/to/error.log
# Cron
cron:
- id: flush_cache
schedule: '0 0 * * *'
command: rm -rf app/cache/*
- id: echo_msg
schedule: '*/3 */2 1-3 2,6,7 2'
command: echo i\'m a little teapot
# Only provision component locally
local_only: true
# *****************************************************************************
# WORKER
# https://docs.nanobox.io/boxfile/worker/
# *****************************************************************************
worker.jobs:
# Start Command
start: ruby worker.rb
# Stop Config
stop: stop-command
stop_force: false
stop_timeout: 30
# Current Working Directory
cwd: directory
# Network Storage
network_dirs:
data.storage1:
- path/to/directoryA
- path/to/directoryB
data.storage2:
- path/to/directoryC
# Writable Dirs
writable_dirs:
- path/to/dirA
- path/to/dirB
# Custom Logs
log_watch:
job[error]: /app/path/to/error.log
# Cron
cron:
- id: flush_cache
schedule: '0 0 * * *'
command: rm -rf app/cache/*
- id: echo_msg
schedule: '*/3 */2 1-3 2,6,7 2'
command: echo i\'m a little teapot
# Only provision component locally
local_only: true
# *****************************************************************************
# DATA
# https://docs.nanobox.io/boxfile/data/
# *****************************************************************************
data.db:
# Image
image: nanobox/mysql:5.6
# Config Options Exposed by the Image
config:
plugins:
- federated
- audit_log
event_scheduler: 'Off'
# Cron
cron:
- id: backup
schedule: '0 0 * * *'
command: 'bash /path/to/scripts/backup.sh'
- id: echo_msg
schedule: '*/3 */2 1-3 2,6,7 2'
command: 'echo i\'m a little teapot'
# Extra Packages (in addition to what the image installs)
extra_packages:
- perl
- curl
# Additions to $PATH
extra_path_dirs:
- /custom/bin
# Custom commands to prepare the environment
extra_steps:
- wget -o /path/to/scripts/cron.sh http://example.com/cron.sh
# Only provision component locally
local_only: true

Some files were not shown because too many files have changed in this diff Show More