Compare commits
771 Commits
nuxt
..
cf532daa66
| Author | SHA1 | Date | |
|---|---|---|---|
| cf532daa66 | |||
| 81eeb36a07 | |||
| 3ff3cc0cdd | |||
| 64d33cf36d | |||
| 8249479622 | |||
| 65ad8bf5d3 | |||
| dba33d6681 | |||
| a0ef3812d3 | |||
| 4fdd5ce25e | |||
| 750c44ed33 | |||
| 88e5be6e4b | |||
| 2f9037b24e | |||
| 0931c8fc67 | |||
| 3c2016f645 | |||
| 10872e02d1 | |||
| 365b4f72b7 | |||
| 0f74ebe37b | |||
| bf4c0379f2 | |||
| 2aee46f169 | |||
| 22977d5ca1 | |||
| a2c99c9674 | |||
| 559d03ecf3 | |||
| bea751612a | |||
| 4fdd37d875 | |||
| d143c60246 | |||
| 44371217a9 | |||
| d63d75bb28 | |||
| 94087440e5 | |||
| 8557d4f3d8 | |||
| f8d75a7ccf | |||
| 5ff48033e1 | |||
| 6c3b6ee90e | |||
| 7e9e6af408 | |||
| 0ee3753e2f | |||
| dd94d3aa70 | |||
| 9d8c46566b | |||
| 8ec2267167 | |||
| cb9ca87a4b | |||
| ec7afa056b | |||
| 47ff229fcd | |||
| 4c1540a448 | |||
| 5bbef08e46 | |||
| bf8cc22dae | |||
| b095a3534d | |||
| 463d563edf | |||
| 6f67bf688e | |||
| 335c178141 | |||
| 313ecb8d53 | |||
| 936500c032 | |||
| 908e4a11c7 | |||
| 153d665c53 | |||
| ab8f391f60 | |||
| 7c9fb9e945 | |||
| 28c89f1a3b | |||
| eb59197c8d | |||
| 2137ac0559 | |||
| 5b44f78be2 | |||
| 44727dec60 | |||
| bb482c05bb | |||
| 707a1a22e2 | |||
| d85a74febf | |||
| a8b0e9978c | |||
| 8dac93f947 | |||
| 30566a3a9f | |||
| 4c3bde64f9 | |||
| c197c1e906 | |||
| 3bd1097f99 | |||
| 3b578313c3 | |||
| 9edc51c045 | |||
| c958d3b39a | |||
| 8b92343e9e | |||
| 13b8d8b72d | |||
| 94a3376844 | |||
| 4ea99284cb | |||
| 92c29be4bb | |||
| c84099568f | |||
| e72dd6a956 | |||
| 3028f3ba76 | |||
| 55afd60d33 | |||
| fdb11164f1 | |||
| 4c1da007c0 | |||
| acb515c171 | |||
| c245e58730 | |||
| 1b6b59947a | |||
| 6b29cb5c71 | |||
| 7c9ebfc0be | |||
| d5b2d4abb6 | |||
| 014126e4d7 | |||
| cc3cb1bc11 | |||
| 08ad0bea19 | |||
| e1e779509c | |||
| 45dc3252bb | |||
| 32d5770fb4 | |||
| 271d4ef931 | |||
| 734a77342f | |||
| d7fb65e5c5 | |||
| 704b8ecd39 | |||
| 14d53d31c8 | |||
| 5dc55f1a83 | |||
| e668f3c19c | |||
| 40303cb79f | |||
| f0b87463ed | |||
| a580e2d175 | |||
| 4a0d72fc35 | |||
| d66d0db292 | |||
| 92c6c88716 | |||
| 09602e03fd | |||
| 9ff4eb1d9c | |||
| 94694884dc | |||
| 8b81bc13fd | |||
| 4f44c24030 | |||
| c64afd2158 | |||
| 31b098ac63 | |||
| 71e45aa43e | |||
| dbc5b69dc8 | |||
| ae5f62c7f8 | |||
| 01cbe6f0bd | |||
| b885d645fe | |||
| b6537404c7 | |||
| ba760faecd | |||
| 32ed1e33f0 | |||
| d787d6cf8d | |||
| b443850b2a | |||
| d32e1a7fc4 | |||
| 31690932c5 | |||
| a2d51368dc | |||
| 1836f22a54 | |||
| 78022a5e95 | |||
| a751a64a01 | |||
| 2fe2e8d2f9 | |||
| 5ba6b5e93f | |||
| f668201688 | |||
| e17d236bee | |||
| 3c1dab9dda | |||
| 1c6d4ee480 | |||
| 23488da297 | |||
| 2021c90140 | |||
| d4fe30f94b | |||
| 2fa3e1b155 | |||
| 862c113892 | |||
| 106d656567 | |||
| b995f9e2c4 | |||
| e775f8e675 | |||
| 8008c44d49 | |||
| b9be6c4cbc | |||
| 24faa1e1c1 | |||
| 859556dc1f | |||
| 9731e6841b | |||
| 81add6e07b | |||
| 3efedb4ded | |||
| f0d26648ae | |||
| d6ba64e4b9 | |||
| d8d6fa49c0 | |||
| a37345dc55 | |||
| 5afbb2dd0f | |||
| 7148273bc4 | |||
| b2e4dd2b91 | |||
| 5fa1f190c1 | |||
| e1828cbe2c | |||
| 05f8c9ee01 | |||
| 283257b750 | |||
| b6dc8fb718 | |||
| f806fefafb | |||
| 016c07af64 | |||
| e591db15a3 | |||
| 7ccf0d3a92 | |||
| 1030d6737d | |||
| 7989cb9a6f | |||
| 53ad5697e8 | |||
| cff39967e1 | |||
| 336ef76baa | |||
| 81a237ae9f | |||
| 46f2b2e3a1 | |||
| db0520dc23 | |||
| 27d1831c27 | |||
| 2c92735c4f | |||
| 987b708b36 | |||
| 7fdab9da66 | |||
| 89761b71da | |||
| 641fa33773 | |||
| 75ed33d564 | |||
| d04175dd56 | |||
| 9b89b3136a | |||
| 61f5d0359f | |||
| 9349857693 | |||
| 609f229542 | |||
| 3775de44b5 | |||
| d3a4a69ce9 | |||
| 75eab8746b | |||
| 61cd930585 | |||
| 47675c4fa3 | |||
| 1de769e598 | |||
| b7726cf471 | |||
| ea8e8cd900 | |||
| 5e0c76a63e | |||
| 2ab007e2a3 | |||
| d590c82ecb | |||
| be167bc112 | |||
| 32586c3fcf | |||
| 731020d2e4 | |||
| f59ffcfa93 | |||
| 0c37900ef0 | |||
| 1643b90b9e | |||
| 3201fb52f5 | |||
| 52e94ebc3c | |||
| 61813a4812 | |||
| 08ffddee57 | |||
| c689d6cbbf | |||
| a0ed757c9a | |||
| 54147873d8 | |||
| 1ecb0b8a54 | |||
| d41b6bb7da | |||
| 1f021560e2 | |||
| 8a58903ad1 | |||
| e6cdab4c5d | |||
| fa869f5dd2 | |||
| b010a3436f | |||
| 5af126a834 | |||
| 02bdc8f1df | |||
| 484d17d7e7 | |||
| a5b2db95f2 | |||
| 20594479f3 | |||
| 2ded33ce9e | |||
| 6f10eb9335 | |||
| 5502ffd277 | |||
| 6d88c3db05 | |||
| ad8febdfe2 | |||
| 517ce0ea59 | |||
| f13ec4ac2a | |||
| 640bdfc7fd | |||
| 4d237c2a57 | |||
| ad1d39b9dd | |||
| fee6bc10ed | |||
| 133bf721ce | |||
| e963b93ded | |||
| 8b1ae69f76 | |||
| 6a18dc96f1 | |||
| 456df7dbe9 | |||
| 849ade7392 | |||
| a6ff7b33d1 | |||
| d00eb3352c | |||
| 9dc86ca020 | |||
| 6749197e76 | |||
| 8f8dd58758 | |||
| e8be8df3d6 | |||
| 0b10cb93d6 | |||
| fd07239b2b | |||
| 0ca7c26953 | |||
| 571dedea7f | |||
| b731f9f149 | |||
| 2bd53d642d | |||
| fa678c61ac | |||
| f67969bcd5 | |||
| 62efe852d1 | |||
| 9025748f03 | |||
| 0c65389ebd | |||
| 25fa495060 | |||
| 7cc8640251 | |||
| 284db700fb | |||
| 3b591063c0 | |||
| 00918e7080 | |||
| 69d3cf7abb | |||
| b35cf4043d | |||
| f8eb132e2f | |||
| 4d9adef433 | |||
| 7a5d523e80 | |||
| 08af064a39 | |||
| b8e818c1a4 | |||
| d2e6e17e9e | |||
| 1495ca6ab9 | |||
| 7c8d3339a9 | |||
| 7eb73eaf50 | |||
| abc93ca13c | |||
| 328b62fcb8 | |||
| 9a571c5ffe | |||
| 25e170d887 | |||
| f49d6e026b | |||
| 8d9071dff6 | |||
| 11f5b5b6c8 | |||
| 850e7b56f2 | |||
| b888d801db | |||
| a69efb19bb | |||
| 8a1b3c86ce | |||
| e4930c1e2f | |||
| 9b6ed3bffa | |||
| abed550112 | |||
| 499ce17202 | |||
| 5f2ce01663 | |||
| b70c19b739 | |||
| e7ccca4a90 | |||
| c2295bf7e4 | |||
| 114f38ea97 | |||
| fbbaaa6f0a | |||
| d89e4aed41 | |||
| ef7aab4ab8 | |||
| 665830f2bf | |||
| 69a7080ab6 | |||
| 1bdf7b8a56 | |||
| 64d2004dcc | |||
| 7b4b3306c0 | |||
| f966187fe7 | |||
| f3849c72d9 | |||
| 2c0805a4a6 | |||
| d2b44bed00 | |||
| bf63539aa7 | |||
| 78a1128dff | |||
| 3983651d8f | |||
| 6e7dc502d2 | |||
| 8168181146 | |||
| 27202646b5 | |||
| eb7f97c535 | |||
| e69c95694e | |||
| 35039d583f | |||
| 0199acf956 | |||
| b52da9aa7e | |||
| b0c3c912db | |||
| d0452250dc | |||
| 8ec2450866 | |||
| 490b5c1f59 | |||
| a3e8091ca2 | |||
| 94f2ad38fa | |||
| 53438bfd1c | |||
| d0b259d262 | |||
| b310c4b285 | |||
| 576452d67e | |||
| 9bff9c9c99 | |||
| 09145624f5 | |||
| 7546157094 | |||
| 494adccb87 | |||
| 627cc06a0f | |||
| 0b29b9bb54 | |||
| 577f507189 | |||
| 727f636651 | |||
| 6ed61dd6ad | |||
| e8af65049d | |||
| 330e60d307 | |||
| f7ce5d0f49 | |||
| 190aa8a295 | |||
| a578ea612f | |||
| 92ef8999de | |||
| 2c7445ee21 | |||
| 330f8970f4 | |||
| b7d5f219aa | |||
| 25ec9ee6b0 | |||
| 893be71f40 | |||
| d9ade96c1c | |||
| dc1f5bda1a | |||
| 90fd9e5872 | |||
| 087b076040 | |||
| 3f451ea5f4 | |||
| e592128bd3 | |||
| 267e4cc1de | |||
| eef88d09e1 | |||
| 2d5dcd1ff0 | |||
| 01576657fe | |||
| 43f33e5ac0 | |||
| 47a5e3cb7b | |||
| 56229c1a46 | |||
| 8c35714275 | |||
| 3063b14961 | |||
| 59b886f3de | |||
| aeace17659 | |||
| 54c206f63d | |||
| a821fe9d12 | |||
| 2a18405341 | |||
| 9f5a51f11f | |||
| e3e212be25 | |||
| f305520707 | |||
| 4217db8c62 | |||
| 026729934f | |||
| b2aaf18e17 | |||
| 8580ca1973 | |||
| 45bf363110 | |||
| 2269417161 | |||
| 296c01b279 | |||
| 919c839e24 | |||
| 52c05c5cf4 | |||
| 5a558f6f60 | |||
| 10c84a7691 | |||
| b994cac48a | |||
| c293a96a12 | |||
| c5464a8232 | |||
| c4a179267f | |||
| 2a8409ed54 | |||
| c2e320b3d3 | |||
| d514e86e11 | |||
| 1716f3f575 | |||
| 7937ffea53 | |||
| c7ad1bf574 | |||
| c5faec60ef | |||
| c882af50b7 | |||
| 0a88f6209f | |||
| b525056ac8 | |||
| 873782d90a | |||
| b3444b6a31 | |||
| 08f4e886d6 | |||
| e28a4a9cec | |||
| 6c27bf77de | |||
| a0aa12efa7 | |||
| 21a99e7bd6 | |||
| 3f4277fafe | |||
| 5f0b94b7c2 | |||
| 4aa6588b3d | |||
| 65f7f7fda3 | |||
| 0aea889c05 | |||
| 5b2794a35e | |||
| 66c417155a | |||
| 394910144d | |||
| 7473bd427d | |||
| 12e8b98f33 | |||
| ab94980dd5 | |||
| b7a5aa284c | |||
| 393164662c | |||
| d0c4d84c72 | |||
| d9ff0ab379 | |||
| ea73801d9b | |||
| c3ad4a15ab | |||
| de864ea195 | |||
| 029e2b44b2 | |||
| 6fe0435c77 | |||
| aa8b4efb86 | |||
| d2c01dccd4 | |||
| f0fae838f8 | |||
| 52e18e5933 | |||
| 7915beb1d6 | |||
| 1eec2b0273 | |||
| c946fe9b67 | |||
| 32a915da58 | |||
| 1df7874d1d | |||
| 03581585cf | |||
| a552f052d1 | |||
| 926b0cb279 | |||
| 56d8d41136 | |||
| b473bf3c66 | |||
| d309cb8546 | |||
| 166ca58ac3 | |||
| 1bdc64dcf1 | |||
| 3aff588350 | |||
| 70e7886997 | |||
| 4042809cde | |||
| 710ec22c52 | |||
| c3861473e8 | |||
| 841dc6ce33 | |||
| ac2dca8860 | |||
| c77151fb31 | |||
| a38e141789 | |||
| dfe3d9c173 | |||
| 92b9bd8403 | |||
| 12e5e7747e | |||
| d9eee18d87 | |||
| 68933acade | |||
| 7d7afdd218 | |||
| bde96af436 | |||
| 75058411bb | |||
| c6251b8fd9 | |||
| 432c2c8bec | |||
| 81eae536b6 | |||
| 1dfacb674a | |||
| b5923b7b59 | |||
| dd8dbbfe48 | |||
| 7536d71c8d | |||
| ba836197c6 | |||
| c396e8470c | |||
| 020b3fc0f6 | |||
| 461ae708cc | |||
| dfd1be5c7a | |||
| 4e10d483d3 | |||
| 949563b81e | |||
| e5d1451172 | |||
| 29e2ad39ad | |||
| 94fe7a0acf | |||
| a54791651f | |||
| 08338adb42 | |||
| c93d3ba9f8 | |||
| bb2465e318 | |||
| afad9d57c6 | |||
| 4476c4c068 | |||
| 4bf211eca5 | |||
| dbb804db47 | |||
| f0b8bfd000 | |||
| 692d02541c | |||
| 21a257f4cf | |||
| 29819a501c | |||
| 9760107f15 | |||
| 792127225d | |||
| b8cc65da79 | |||
| 0efbdbbf90 | |||
| 5f47884190 | |||
| f12fe74e26 | |||
| e9242e41d1 | |||
| 6d47c4b9e2 | |||
| 2db929607b | |||
| 8d89aa9bbc | |||
| bff426a62f | |||
| 63b0213e57 | |||
| ac8c757aa7 | |||
| b7f89c8d79 | |||
| 746afa5649 | |||
| 0d757dc98d | |||
| 14832b1be4 | |||
| d02b880d4a | |||
| 41c2ad6117 | |||
| f1eaddaa1e | |||
| 177ff62007 | |||
| a990a380c9 | |||
| 8019c0b96f | |||
| 0983d1723a | |||
| 0e2d63f30b | |||
| 559363f740 | |||
| 4aad09caaa | |||
| 38550db0c3 | |||
| 25d27efdc9 | |||
| 7c78a91d7f | |||
| e560ca4a1c | |||
| b0ddf7b1c9 | |||
| 9a9efdd665 | |||
| 0c5250d320 | |||
| 57bb08b828 | |||
| b9c6d28445 | |||
| 9ab6a07d5b | |||
| 2c2b2fe384 | |||
| 87df4a5bff | |||
| 59496b6a36 | |||
| 1eb798ba5c | |||
| 56cb46a209 | |||
| 787b086ff5 | |||
| 66a85f340b | |||
| 83a91ce2d3 | |||
| a3b9824c4c | |||
| 0b2dbf425c | |||
| 743e49ff6c | |||
| 122d5eed2d | |||
| b539d713b7 | |||
| 9ceff1bca6 | |||
| e0e1c82dde | |||
| ab5f2e7290 | |||
| e999e91942 | |||
| faaebc08c9 | |||
| 5c895d9d08 | |||
| a0782c770a | |||
| b6a3aa4d0b | |||
| a19dfeb523 | |||
| 7e12b71adb | |||
| 2dbd8cced5 | |||
| 65619d86e8 | |||
| 6dc05a7733 | |||
| 1b3101926b | |||
| 20e8f9c9b1 | |||
| 689efabdcd | |||
| 0fc96efd89 | |||
| 7a0defd436 | |||
| 38957bd2be | |||
| 69684835b3 | |||
| 44e9641f78 | |||
| 6482a577f5 | |||
| d97ae72eba | |||
| cc19e07269 | |||
| 5429e1d64a | |||
| 46f33f030e | |||
| 93264ac0e9 | |||
| d5fc4fceb5 | |||
| 5ce0c7a9ab | |||
| 90a3cec714 | |||
| 40ea7c3283 | |||
| 65bbc18233 | |||
| 98fe3cd912 | |||
| 0bc06946bb | |||
| db7b569476 | |||
| 9f9e769d85 | |||
| 04469e3842 | |||
| a04bda35d4 | |||
| 5991111e75 | |||
| 14051c5e7b | |||
| 21ceaa7fea | |||
| ddd96eab4c | |||
| d812620767 | |||
| e39a88b6f1 | |||
| e0312bbd19 | |||
| 741a0c73bf | |||
| 50acfb734e | |||
| 6480be44b2 | |||
| e27ba13f0a | |||
| 6bfa05d8ae | |||
| c31f42ef9b | |||
| a7c584d8d5 | |||
| e5209dbd7e | |||
| 54b0413a0b | |||
| e9bbc71cfc | |||
| 5644030132 | |||
| 491be5a8dc | |||
| 164c13f813 | |||
| dfa30d8776 | |||
| 6265188ee4 | |||
| 387d6c3d48 | |||
| 6ac16cc7e2 | |||
| 6bae53f688 | |||
| e76a374d90 | |||
| 4aa2700721 | |||
| f1fcc20a94 | |||
| 9eb7d05caf | |||
| 9a1caa363a | |||
| 1c42d02878 | |||
| 3c963586cf | |||
| 712903ad4e | |||
| 4c8bb1752b | |||
| f5da645f6e | |||
| 8cc75917df | |||
| 54f4bb9e1f | |||
| a724efd0b5 | |||
| 41afb9ce31 | |||
| 07ddc8414a | |||
| eeb4ab5b23 | |||
| 8e872d4d93 | |||
| 6c299e00ec | |||
| 4c880cf48e | |||
| 2625199e02 | |||
| 674fc5d190 | |||
| e3f84cd5dd | |||
| ab0940a4bf | |||
| c456873b44 | |||
| 714d8233d0 | |||
| c68eb1439b | |||
| 488e7a7460 | |||
| 47e2960126 | |||
| fcc980ddc6 | |||
| 49e8d23425 | |||
| 0d408416b8 | |||
| abc1512346 | |||
| 5615c4ca85 | |||
| 8de7573c16 | |||
| 2ef26d3c39 | |||
| 3e7c440853 | |||
| 514d5a1823 | |||
| 7399f975c8 | |||
| 9a6984369d | |||
| 16619f2e28 | |||
| 23877a3c82 | |||
| 889cd60ac1 | |||
| 1dcb38b883 | |||
| 8dbf559bdb | |||
| 97f4043e86 | |||
| 08179d5961 | |||
| 80f89ad98c | |||
| 394f046e77 | |||
| dca4f0d99a | |||
| 945738c992 | |||
| 86e5c7e10e | |||
| b370cc0400 | |||
| 4458bf3822 | |||
| 032f698f2d | |||
| a538a5dfdd | |||
| 90ee1fbdf7 | |||
| 9a04ba0ef4 | |||
| 71645edf5f | |||
| 3877873002 | |||
| 4e4d66405d | |||
| 1564a59aa2 | |||
| 12fbb4bdce | |||
| 48390e96fe | |||
| ba0c6df3c1 | |||
| 70a3fa3ebd | |||
| 21583aa127 | |||
| 16acbfdfa4 | |||
| 17520bae35 | |||
| 928f739577 | |||
| ef808c91de | |||
| 5791c29ab6 | |||
| ad661bbb3d | |||
| 528b6d3e93 | |||
| f31fdaaf1b | |||
| 1b9a0ce80c | |||
| 0422661584 | |||
| ba3551ccf1 | |||
| 0853046c3c | |||
| 3f6c5c757b | |||
| c618bf1fe5 | |||
| 0c397e5cf4 | |||
| d2680863a6 | |||
| d4f57e56d1 | |||
| 888638b885 | |||
| e33f0611ab | |||
| 166b1c54cf | |||
| 2607ae1339 | |||
| 9156790867 | |||
| 71e8218423 | |||
| 55ab00dc43 | |||
| 21d69febf4 | |||
| f54d9905d1 | |||
| 0178e87d76 | |||
| 069057de7e | |||
| 4152fc728a | |||
| eab3159fbb | |||
| 6bfd78f5e5 | |||
| 22613b2185 | |||
| 34124c1731 | |||
| 450f2db40b | |||
| 0f941d5534 | |||
| d20f3f8118 | |||
| 278aa31c11 | |||
| 54a5df7c84 | |||
| 9014e77b04 | |||
| 5ca2ac5b5d | |||
| 3b95bd4319 | |||
| 0d8e5eb628 | |||
| 365c219df2 | |||
| 66fafbcf09 | |||
| 1b35284c09 | |||
| aed6bb63b6 | |||
| 0bd368ff75 | |||
| a27ab16eb9 | |||
| 0f21201295 | |||
| 27c5b74667 | |||
| 1b7838f0e6 | |||
| bdde87d6af | |||
| 22e0b5b399 | |||
| 71d9b7be01 | |||
| 00697934e9 | |||
| 5db2e1fd4d | |||
| 2cd1e38b0e | |||
| caaa62d139 | |||
| dc306a3364 | |||
| c368ad3b06 | |||
| 1c56375806 | |||
| cec31441e7 | |||
| 0892c8d365 | |||
| d05ed80faa | |||
| 745643557b | |||
| 18d68e86a3 | |||
| a4e4b2fff5 | |||
| 1b63ec86e7 | |||
| 012b11138a | |||
| 892f04f1ab | |||
| 88879d285c | |||
| de879e3f10 | |||
| 87657c1c4b | |||
| 360b734404 | |||
| fd83adda70 | |||
| 9b88a9d406 | |||
| d31a41c683 | |||
| d43e737e1b | |||
| 848911f5bc | |||
| 4b0da67c73 | |||
| b04042f56a | |||
| e49a31edf8 | |||
| 708173004a | |||
| d3c1292b09 | |||
| 909378aa3e | |||
| 6c98441553 | |||
| 0206d6f099 | |||
| 575c1bc653 | |||
| 25c104915d | |||
| a6c52438bd | |||
| 5c488dab02 | |||
| f4ec8cd116 | |||
| 80b7301534 | |||
| 4cd93d84f8 | |||
| f912b540b8 | |||
| 84fe55ed6b | |||
| 35ac733b20 | |||
| d80605ac6b | |||
| 6f663cc828 | |||
| ec5e178ec6 | |||
| ac36666864 | |||
| 48c8cd1d58 | |||
| 3ecdf8a4f8 | |||
| c352686998 | |||
| 213feaef6d | |||
| f557653039 | |||
| 234241a6cf | |||
| ccb9f907d5 | |||
| 2b43adf72c |
@@ -1,458 +0,0 @@
|
||||
{
|
||||
"exclude": [".git/**", "node_modules/**", "bower_components/**"],
|
||||
"always-semicolon": true,
|
||||
"block-indent": " ",
|
||||
"color-case": "upper",
|
||||
"color-shorthand": false,
|
||||
"element-case": "lower",
|
||||
"eof-newline": true,
|
||||
"leading-zero": true,
|
||||
"quotes": "double",
|
||||
"remove-empty-rulesets": true,
|
||||
"sort-order-fallback": "abc",
|
||||
"space-after-colon": " ",
|
||||
"space-after-combinator": " ",
|
||||
"space-after-opening-brace": "\n",
|
||||
"space-after-selector-delimiter": "\n",
|
||||
"space-before-closing-brace": "\n",
|
||||
"space-before-combinator": " ",
|
||||
"space-between-declarations": "\n",
|
||||
"space-before-opening-brace": " ",
|
||||
"space-before-selector-delimiter": "",
|
||||
"strip-spaces": true,
|
||||
"tab-size": true,
|
||||
"unitless-zero": true,
|
||||
"vendor-prefix-align": true,
|
||||
"sort-order": [
|
||||
[
|
||||
"position",
|
||||
"top",
|
||||
"right",
|
||||
"bottom",
|
||||
"left",
|
||||
"z-index",
|
||||
"display",
|
||||
"visibility",
|
||||
"float",
|
||||
"clear",
|
||||
"overflow",
|
||||
"-ms-overflow-x",
|
||||
"-ms-overflow-y",
|
||||
"overflow-x",
|
||||
"overflow-y",
|
||||
"-webkit-overflow-scrolling",
|
||||
"clip",
|
||||
"grid",
|
||||
"grid-area",
|
||||
"grid-auto-columns",
|
||||
"grid-auto-flow",
|
||||
"grid-auto-rows",
|
||||
"grid-column",
|
||||
"grid-column-end",
|
||||
"grid-column-gap",
|
||||
"grid-column-start",
|
||||
"grid-gap",
|
||||
"grid-row",
|
||||
"grid-row-end",
|
||||
"grid-row-gap",
|
||||
"grid-row-start",
|
||||
"grid-template",
|
||||
"grid-template-areas",
|
||||
"grid-template-columns",
|
||||
"grid-template-rows",
|
||||
"-webkit-align-content",
|
||||
"-ms-flex-line-pack",
|
||||
"align-content",
|
||||
"-webkit-box-align",
|
||||
"-moz-box-align",
|
||||
"-webkit-align-items",
|
||||
"align-items",
|
||||
"-ms-flex-align",
|
||||
"-webkit-align-self",
|
||||
"-ms-flex-item-align",
|
||||
"-ms-grid-row-align",
|
||||
"align-self",
|
||||
"-webkit-box-flex",
|
||||
"-webkit-flex",
|
||||
"-moz-box-flex",
|
||||
"-ms-flex",
|
||||
"flex",
|
||||
"-webkit-flex-flow",
|
||||
"-ms-flex-flow",
|
||||
"flex-flow",
|
||||
"-webkit-flex-basis",
|
||||
"-ms-flex-preferred-size",
|
||||
"flex-basis",
|
||||
"-webkit-box-orient",
|
||||
"-webkit-box-direction",
|
||||
"-webkit-flex-direction",
|
||||
"-moz-box-orient",
|
||||
"-moz-box-direction",
|
||||
"-ms-flex-direction",
|
||||
"flex-direction",
|
||||
"-webkit-flex-grow",
|
||||
"-ms-flex-positive",
|
||||
"flex-grow",
|
||||
"-webkit-flex-shrink",
|
||||
"-ms-flex-negative",
|
||||
"flex-shrink",
|
||||
"-webkit-flex-wrap",
|
||||
"-ms-flex-wrap",
|
||||
"flex-wrap",
|
||||
"-webkit-box-pack",
|
||||
"-moz-box-pack",
|
||||
"-ms-flex-pack",
|
||||
"-webkit-justify-content",
|
||||
"justify-content",
|
||||
"justify-items",
|
||||
"-webkit-box-ordinal-group",
|
||||
"-webkit-order",
|
||||
"-moz-box-ordinal-group",
|
||||
"-ms-flex-order",
|
||||
"order",
|
||||
"-webkit-box-sizing",
|
||||
"-moz-box-sizing",
|
||||
"box-sizing",
|
||||
"margin",
|
||||
"margin-top",
|
||||
"margin-right",
|
||||
"margin-bottom",
|
||||
"margin-left",
|
||||
"padding",
|
||||
"padding-top",
|
||||
"padding-right",
|
||||
"padding-bottom",
|
||||
"padding-left",
|
||||
"min-width",
|
||||
"min-height",
|
||||
"max-width",
|
||||
"max-height",
|
||||
"width",
|
||||
"height",
|
||||
"outline",
|
||||
"outline-width",
|
||||
"outline-style",
|
||||
"outline-color",
|
||||
"outline-offset",
|
||||
"border",
|
||||
"border-spacing",
|
||||
"border-collapse",
|
||||
"border-width",
|
||||
"border-style",
|
||||
"border-color",
|
||||
"border-top",
|
||||
"border-top-width",
|
||||
"border-top-style",
|
||||
"border-top-color",
|
||||
"border-right",
|
||||
"border-right-width",
|
||||
"border-right-style",
|
||||
"border-right-color",
|
||||
"border-bottom",
|
||||
"border-bottom-width",
|
||||
"border-bottom-style",
|
||||
"border-bottom-color",
|
||||
"border-left",
|
||||
"border-left-width",
|
||||
"border-left-style",
|
||||
"border-left-color",
|
||||
"-webkit-border-radius",
|
||||
"-moz-border-radius",
|
||||
"border-radius",
|
||||
"-webkit-border-top-left-radius",
|
||||
"-moz-border-radius-topleft",
|
||||
"border-top-left-radius",
|
||||
"-webkit-border-top-right-radius",
|
||||
"-moz-border-radius-topright",
|
||||
"border-top-right-radius",
|
||||
"-webkit-border-bottom-right-radius",
|
||||
"-moz-border-radius-bottomright",
|
||||
"border-bottom-right-radius",
|
||||
"-webkit-border-bottom-left-radius",
|
||||
"-moz-border-radius-bottomleft",
|
||||
"border-bottom-left-radius",
|
||||
"-webkit-border-image",
|
||||
"-moz-border-image",
|
||||
"-o-border-image",
|
||||
"border-image",
|
||||
"-webkit-border-image-source",
|
||||
"-moz-border-image-source",
|
||||
"-o-border-image-source",
|
||||
"border-image-source",
|
||||
"-webkit-border-image-slice",
|
||||
"-moz-border-image-slice",
|
||||
"-o-border-image-slice",
|
||||
"border-image-slice",
|
||||
"-webkit-border-image-width",
|
||||
"-moz-border-image-width",
|
||||
"-o-border-image-width",
|
||||
"border-image-width",
|
||||
"-webkit-border-image-outset",
|
||||
"-moz-border-image-outset",
|
||||
"-o-border-image-outset",
|
||||
"border-image-outset",
|
||||
"-webkit-border-image-repeat",
|
||||
"-moz-border-image-repeat",
|
||||
"-o-border-image-repeat",
|
||||
"border-image-repeat",
|
||||
"-webkit-border-top-image",
|
||||
"-moz-border-top-image",
|
||||
"-o-border-top-image",
|
||||
"border-top-image",
|
||||
"-webkit-border-right-image",
|
||||
"-moz-border-right-image",
|
||||
"-o-border-right-image",
|
||||
"border-right-image",
|
||||
"-webkit-border-bottom-image",
|
||||
"-moz-border-bottom-image",
|
||||
"-o-border-bottom-image",
|
||||
"border-bottom-image",
|
||||
"-webkit-border-left-image",
|
||||
"-moz-border-left-image",
|
||||
"-o-border-left-image",
|
||||
"border-left-image",
|
||||
"-webkit-border-corner-image",
|
||||
"-moz-border-corner-image",
|
||||
"-o-border-corner-image",
|
||||
"border-corner-image",
|
||||
"-webkit-border-top-left-image",
|
||||
"-moz-border-top-left-image",
|
||||
"-o-border-top-left-image",
|
||||
"border-top-left-image",
|
||||
"-webkit-border-top-right-image",
|
||||
"-moz-border-top-right-image",
|
||||
"-o-border-top-right-image",
|
||||
"border-top-right-image",
|
||||
"-webkit-border-bottom-right-image",
|
||||
"-moz-border-bottom-right-image",
|
||||
"-o-border-bottom-right-image",
|
||||
"border-bottom-right-image",
|
||||
"-webkit-border-bottom-left-image",
|
||||
"-moz-border-bottom-left-image",
|
||||
"-o-border-bottom-left-image",
|
||||
"border-bottom-left-image",
|
||||
"background",
|
||||
"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader",
|
||||
"background-color",
|
||||
"background-image",
|
||||
"background-attachment",
|
||||
"background-position",
|
||||
"-ms-background-position-x",
|
||||
"-ms-background-position-y",
|
||||
"background-position-x",
|
||||
"background-position-y",
|
||||
"-webkit-background-clip",
|
||||
"-moz-background-clip",
|
||||
"background-clip",
|
||||
"background-origin",
|
||||
"-webkit-background-size",
|
||||
"-moz-background-size",
|
||||
"-o-background-size",
|
||||
"background-size",
|
||||
"background-repeat",
|
||||
"box-decoration-break",
|
||||
"-webkit-box-shadow",
|
||||
"-moz-box-shadow",
|
||||
"box-shadow",
|
||||
"color",
|
||||
"table-layout",
|
||||
"caption-side",
|
||||
"empty-cells",
|
||||
"list-style",
|
||||
"list-style-position",
|
||||
"list-style-type",
|
||||
"list-style-image",
|
||||
"quotes",
|
||||
"content",
|
||||
"counter-increment",
|
||||
"counter-reset",
|
||||
"-ms-writing-mode",
|
||||
"vertical-align",
|
||||
"text-align",
|
||||
"-webkit-text-align-last",
|
||||
"-moz-text-align-last",
|
||||
"-ms-text-align-last",
|
||||
"text-align-last",
|
||||
"text-decoration",
|
||||
"text-emphasis",
|
||||
"text-emphasis-position",
|
||||
"text-emphasis-style",
|
||||
"text-emphasis-color",
|
||||
"text-indent",
|
||||
"-ms-text-justify",
|
||||
"text-justify",
|
||||
"text-outline",
|
||||
"text-transform",
|
||||
"text-wrap",
|
||||
"-ms-text-overflow",
|
||||
"text-overflow",
|
||||
"text-overflow-ellipsis",
|
||||
"text-overflow-mode",
|
||||
"text-shadow",
|
||||
"text-rendering",
|
||||
"white-space",
|
||||
"word-spacing",
|
||||
"-ms-word-wrap",
|
||||
"word-wrap",
|
||||
"-ms-word-break",
|
||||
"word-break",
|
||||
"-moz-tab-size",
|
||||
"-o-tab-size",
|
||||
"tab-size",
|
||||
"-webkit-hyphens",
|
||||
"-moz-hyphens",
|
||||
"hyphens",
|
||||
"letter-spacing",
|
||||
"font",
|
||||
"font-weight",
|
||||
"font-style",
|
||||
"font-variant",
|
||||
"font-size-adjust",
|
||||
"font-stretch",
|
||||
"font-size",
|
||||
"font-family",
|
||||
"font-feature-settings",
|
||||
"src",
|
||||
"line-height",
|
||||
"opacity",
|
||||
"-ms-filter:\\'progid:DXImageTransform.Microsoft.Alpha",
|
||||
"filter:progid:DXImageTransform.Microsoft.Alpha(Opacity",
|
||||
"-ms-interpolation-mode",
|
||||
"-webkit-filter",
|
||||
"-ms-filter",
|
||||
"filter",
|
||||
"resize",
|
||||
"nav-index",
|
||||
"nav-up",
|
||||
"nav-right",
|
||||
"nav-down",
|
||||
"nav-left",
|
||||
"-webkit-user-drag",
|
||||
"-webkit-transition",
|
||||
"-moz-transition",
|
||||
"-ms-transition",
|
||||
"-o-transition",
|
||||
"transition",
|
||||
"-webkit-transition-delay",
|
||||
"-moz-transition-delay",
|
||||
"-ms-transition-delay",
|
||||
"-o-transition-delay",
|
||||
"transition-delay",
|
||||
"-webkit-transition-timing-function",
|
||||
"-moz-transition-timing-function",
|
||||
"-ms-transition-timing-function",
|
||||
"-o-transition-timing-function",
|
||||
"transition-timing-function",
|
||||
"-webkit-transition-duration",
|
||||
"-moz-transition-duration",
|
||||
"-ms-transition-duration",
|
||||
"-o-transition-duration",
|
||||
"transition-duration",
|
||||
"-webkit-transition-property",
|
||||
"-moz-transition-property",
|
||||
"-ms-transition-property",
|
||||
"-o-transition-property",
|
||||
"transition-property",
|
||||
"-webkit-transform",
|
||||
"-moz-transform",
|
||||
"-ms-transform",
|
||||
"-o-transform",
|
||||
"transform",
|
||||
"-webkit-transform-origin",
|
||||
"-moz-transform-origin",
|
||||
"-ms-transform-origin",
|
||||
"-o-transform-origin",
|
||||
"transform-origin",
|
||||
"-webkit-animation",
|
||||
"-moz-animation",
|
||||
"-ms-animation",
|
||||
"-o-animation",
|
||||
"animation",
|
||||
"-webkit-animation-name",
|
||||
"-moz-animation-name",
|
||||
"-ms-animation-name",
|
||||
"-o-animation-name",
|
||||
"animation-name",
|
||||
"-webkit-animation-duration",
|
||||
"-moz-animation-duration",
|
||||
"-ms-animation-duration",
|
||||
"-o-animation-duration",
|
||||
"animation-duration",
|
||||
"animation-fill-mode",
|
||||
"-webkit-animation-play-state",
|
||||
"-moz-animation-play-state",
|
||||
"-ms-animation-play-state",
|
||||
"-o-animation-play-state",
|
||||
"animation-play-state",
|
||||
"-webkit-animation-timing-function",
|
||||
"-moz-animation-timing-function",
|
||||
"-ms-animation-timing-function",
|
||||
"-o-animation-timing-function",
|
||||
"animation-timing-function",
|
||||
"-webkit-animation-delay",
|
||||
"-moz-animation-delay",
|
||||
"-ms-animation-delay",
|
||||
"-o-animation-delay",
|
||||
"animation-delay",
|
||||
"-webkit-animation-iteration-count",
|
||||
"-moz-animation-iteration-count",
|
||||
"-ms-animation-iteration-count",
|
||||
"-o-animation-iteration-count",
|
||||
"animation-iteration-count",
|
||||
"-webkit-animation-direction",
|
||||
"-moz-animation-direction",
|
||||
"-ms-animation-direction",
|
||||
"-o-animation-direction",
|
||||
"animation-direction",
|
||||
"pointer-events",
|
||||
"unicode-bidi",
|
||||
"direction",
|
||||
"-webkit-columns",
|
||||
"-moz-columns",
|
||||
"columns",
|
||||
"-webkit-column-span",
|
||||
"-moz-column-span",
|
||||
"column-span",
|
||||
"-webkit-column-width",
|
||||
"-moz-column-width",
|
||||
"column-width",
|
||||
"-webkit-column-count",
|
||||
"-moz-column-count",
|
||||
"column-count",
|
||||
"-webkit-column-fill",
|
||||
"-moz-column-fill",
|
||||
"column-fill",
|
||||
"-webkit-column-gap",
|
||||
"-moz-column-gap",
|
||||
"column-gap",
|
||||
"-webkit-column-rule",
|
||||
"-moz-column-rule",
|
||||
"column-rule",
|
||||
"-webkit-column-rule-width",
|
||||
"-moz-column-rule-width",
|
||||
"column-rule-width",
|
||||
"-webkit-column-rule-style",
|
||||
"-moz-column-rule-style",
|
||||
"column-rule-style",
|
||||
"-webkit-column-rule-color",
|
||||
"-moz-column-rule-color",
|
||||
"column-rule-color",
|
||||
"break-before",
|
||||
"break-inside",
|
||||
"break-after",
|
||||
"page-break-before",
|
||||
"page-break-inside",
|
||||
"page-break-after",
|
||||
"orphans",
|
||||
"widows",
|
||||
"-ms-zoom",
|
||||
"zoom",
|
||||
"max-zoom",
|
||||
"min-zoom",
|
||||
"user-select",
|
||||
"user-zoom",
|
||||
"orientation",
|
||||
"cursor"
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
# editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.md]
|
||||
trim_trailing_whitespace = false
|
||||
@@ -1,19 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
env: {
|
||||
browser: true,
|
||||
node: true
|
||||
},
|
||||
parserOptions: {
|
||||
parser: "babel-eslint"
|
||||
},
|
||||
extends: [
|
||||
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
|
||||
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
|
||||
"plugin:vue/essential"
|
||||
],
|
||||
// required to lint *.vue files
|
||||
plugins: ["vue"],
|
||||
// add your custom rules here
|
||||
rules: {}
|
||||
};
|
||||
@@ -1,14 +1,8 @@
|
||||
# System
|
||||
# Miscelleaneous
|
||||
.DS_Store
|
||||
|
||||
# Editor
|
||||
.vscode
|
||||
# Editors
|
||||
.vscode/
|
||||
|
||||
# Dependencies
|
||||
node_modules
|
||||
|
||||
# Logs
|
||||
npm-debug.log
|
||||
|
||||
# Nuxt build
|
||||
.nuxt
|
||||
# Vim
|
||||
*.swp
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
. "$(dirname "$0")/_/husky.sh"
|
||||
|
||||
npx --no -- commitlint --edit ""
|
||||
@@ -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.
|
||||
@@ -1,22 +1,148 @@
|
||||
# Awesome Cheatsheets
|
||||
[](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.
|
||||
<p align=center>
|
||||
<a href="https://trendshift.io/repositories/5584" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5584" alt="LeCoupa%2Fawesome-cheatsheets | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||
</p>
|
||||
|
||||
## Build Setup
|
||||
[](https://awesome.re) [](https://github.com/LeCoupa/awesome-cheatsheets/blob/master/LICENSE)
|
||||
|
||||
```bash
|
||||
# install dependencies
|
||||
$ npm install # Or yarn install
|
||||
**WEBSITE DIRECTORY**: [Available here](https://lecoupa.github.io/awesome-cheatsheets/).
|
||||
|
||||
# serve with hot reload at localhost:3000
|
||||
$ npm run dev
|
||||
> 📚 Awesome cheatsheets for popular programming languages, frameworks and development tools. They include everything you should know in one single file.
|
||||
|
||||
# build for production and launch server
|
||||
$ npm run build
|
||||
$ npm start
|
||||
## 🤔 Why Awesome-Cheatsheets?
|
||||
|
||||
# generate static project
|
||||
$ npm run generate
|
||||
```
|
||||
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.
|
||||
|
||||
For detailed explanation on how things work, checkout the [Nuxt.js docs](https://github.com/nuxt/nuxt.js).
|
||||
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)
|
||||
- [Typescript](languages/typescript.md)
|
||||
|
||||
</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)
|
||||
|
||||
#### Typescript
|
||||
|
||||
- [Typescript](frontend/typescript.ts)
|
||||
</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)
|
||||
|
||||
#### 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>
|
||||
|
||||
|
After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 42 KiB |
@@ -1,302 +0,0 @@
|
||||
/* *************************************************************************
|
||||
LIBRARIES > BALLOON
|
||||
Based on https://github.com/kazzkiq/balloon.css
|
||||
************************************************************************* */
|
||||
|
||||
/* *************************************************************************
|
||||
* BALLOON > VARIABLES
|
||||
* ************************************************************************* */
|
||||
|
||||
$balloon-bg: fade-out(#111, 0.05);
|
||||
$balloon-base-size: 10px;
|
||||
$balloon-arrow-height: 6px;
|
||||
|
||||
/* *************************************************************************
|
||||
* BALLOON > MIXINS
|
||||
* ************************************************************************* */
|
||||
|
||||
@mixin svg-arrow($color, $position: up) {
|
||||
$degrees: 0;
|
||||
$height: 6px;
|
||||
$width: 18px;
|
||||
|
||||
@if ($position == down) {
|
||||
$degrees: 180 18 6;
|
||||
} @else if ($position == left) {
|
||||
$degrees: -90 18 18;
|
||||
$width: 6px;
|
||||
$height: 18px;
|
||||
} @else if ($position == right) {
|
||||
$degrees: 90 6 6;
|
||||
$width: 6px;
|
||||
$height: 18px;
|
||||
}
|
||||
|
||||
background: no-repeat
|
||||
url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http://www.w3.org/2000/svg%22%20width%3D%22#{$width * 2}%22%20height%3D%22#{$height * 2}%22%3E%3Cpath%20fill%3D%22#{$color}%22%20transform%3D%22rotate(#{$degrees})%22%20d%3D%22M2.658,0.000%20C-13.615,0.000%2050.938,0.000%2034.662,0.000%20C28.662,0.000%2023.035,12.002%2018.660,12.002%20C14.285,12.002%208.594,0.000%202.658,0.000%20Z%22/%3E%3C/svg%3E");
|
||||
background-size: 100% auto;
|
||||
width: $width;
|
||||
height: $height;
|
||||
}
|
||||
|
||||
@mixin transition($args...) {
|
||||
-webkit-transition: $args;
|
||||
-moz-transition: $args;
|
||||
-ms-transition: $args;
|
||||
-o-transition: $args;
|
||||
transition: $args;
|
||||
}
|
||||
|
||||
@mixin transform($val) {
|
||||
-webkit-transform: $val;
|
||||
-moz-transform: $val;
|
||||
-ms-transform: $val;
|
||||
transform: $val;
|
||||
}
|
||||
|
||||
@mixin transform-origin($val) {
|
||||
-webkit-transform-origin: $val;
|
||||
-moz-transform-origin: $val;
|
||||
-ms-transform-origin: $val;
|
||||
transform-origin: $val;
|
||||
}
|
||||
|
||||
@mixin opacity($trans) {
|
||||
filter: alpha(opactiy=($trans * 100));
|
||||
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=#{$trans * 100})";
|
||||
-moz-opacity: $trans;
|
||||
-khtml-opacity: $trans;
|
||||
opacity: $trans;
|
||||
}
|
||||
|
||||
@mixin base-effects() {
|
||||
@include opacity(0);
|
||||
pointer-events: none;
|
||||
@include transition(all 0.05 ease-out 0.05);
|
||||
}
|
||||
|
||||
/* *************************************************************************
|
||||
* BALLOON > STYLES
|
||||
* ************************************************************************* */
|
||||
|
||||
// IE 11 button bugfix
|
||||
button[data-balloon] {
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
[data-balloon] {
|
||||
position: relative; // alt. absolute or fixed
|
||||
|
||||
&:after {
|
||||
@include base-effects();
|
||||
|
||||
font-size: $balloon-base-size + 2;
|
||||
background: $balloon-bg;
|
||||
border-radius: 4px;
|
||||
color: #ffffff;
|
||||
content: attr(data-balloon);
|
||||
padding: 0.5em 1em;
|
||||
position: absolute;
|
||||
white-space: nowrap;
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
&:before {
|
||||
@include svg-arrow($balloon-bg);
|
||||
@include base-effects();
|
||||
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&[data-balloon-visible] {
|
||||
&:before,
|
||||
&:after {
|
||||
@include opacity(1);
|
||||
|
||||
pointer-events: auto;
|
||||
}
|
||||
}
|
||||
|
||||
&.font-awesome:after {
|
||||
font-family: FontAwesome;
|
||||
}
|
||||
|
||||
&[data-balloon-break] {
|
||||
&:after {
|
||||
white-space: pre;
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-pos="up"] {
|
||||
&:after {
|
||||
@include transform(translate(-50%, 10px));
|
||||
@include transform-origin(top);
|
||||
|
||||
bottom: 100%;
|
||||
left: 50%;
|
||||
margin-bottom: 5px + $balloon-arrow-height;
|
||||
}
|
||||
&:before {
|
||||
@include transform(translate(-50%, 10px));
|
||||
@include transform-origin(top);
|
||||
|
||||
bottom: 100%;
|
||||
left: 50%;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&[data-balloon-visible] {
|
||||
&:after {
|
||||
@include transform(translate(-50%, 0));
|
||||
}
|
||||
|
||||
&:before {
|
||||
@include transform(translate(-50%, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-pos="down"] {
|
||||
&:after {
|
||||
@include transform(translate(-50%, -10px));
|
||||
|
||||
left: 50%;
|
||||
margin-top: 5px + $balloon-arrow-height;
|
||||
top: 100%;
|
||||
}
|
||||
|
||||
&:before {
|
||||
@include svg-arrow($balloon-bg, "down");
|
||||
@include transform(translate(-50%, -10px));
|
||||
|
||||
left: 50%;
|
||||
margin-top: 5px;
|
||||
top: 100%;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&[data-balloon-visible] {
|
||||
&:after {
|
||||
@include transform(translate(-50%, 0));
|
||||
}
|
||||
|
||||
&:before {
|
||||
@include transform(translate(-50%, 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-pos="left"] {
|
||||
&:after {
|
||||
@include transform(translate(10px, -50%));
|
||||
|
||||
margin-right: 5px + $balloon-arrow-height;
|
||||
right: 100%;
|
||||
top: 50%;
|
||||
}
|
||||
|
||||
&:before {
|
||||
@include svg-arrow($balloon-bg, "left");
|
||||
@include transform(translate(10px, -50%));
|
||||
|
||||
margin-right: 5px;
|
||||
right: 100%;
|
||||
top: 50%;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&[data-balloon-visible] {
|
||||
&:after {
|
||||
@include transform(translate(0, -50%));
|
||||
}
|
||||
|
||||
&:before {
|
||||
@include transform(translate(0, -50%));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-pos="right"] {
|
||||
&:after {
|
||||
@include transform(translate(-10px, -50%));
|
||||
|
||||
left: 100%;
|
||||
margin-left: 5px + $balloon-arrow-height;
|
||||
top: 50%;
|
||||
}
|
||||
|
||||
&:before {
|
||||
@include svg-arrow($balloon-bg, "right");
|
||||
@include transform(translate(-10px, -50%));
|
||||
|
||||
left: 100%;
|
||||
margin-left: 5px;
|
||||
top: 50%;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&[data-balloon-visible] {
|
||||
&:after {
|
||||
@include transform(translate(0, -50%));
|
||||
}
|
||||
|
||||
&:before {
|
||||
@include transform(translate(0, -50%));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-length="small"] {
|
||||
&:after {
|
||||
white-space: normal;
|
||||
width: 80px;
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-length="medium"] {
|
||||
&:after {
|
||||
white-space: normal;
|
||||
width: 150px;
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-length="large"] {
|
||||
&:after {
|
||||
white-space: normal;
|
||||
width: 260px;
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-length="xlarge"] {
|
||||
&:after {
|
||||
white-space: normal;
|
||||
width: 380px;
|
||||
|
||||
@media screen and (max-width: 768px) {
|
||||
white-space: normal;
|
||||
width: 90vw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-length="fit"] {
|
||||
&:after {
|
||||
white-space: normal;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
&[data-balloon-type="sidebar"] {
|
||||
&:after {
|
||||
font-size: $balloon-base-size + 3;
|
||||
border-radius: 2px;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/* **************************************************************************
|
||||
SETTINGS > COLORS
|
||||
To get the color name: http://veli.ee/colorpedia/?c=354052
|
||||
************************************************************************** */
|
||||
|
||||
// Black
|
||||
$black: #000000;
|
||||
$ebony-clay: #273142;
|
||||
$mirage: #1b2431;
|
||||
$mirage2: #171e29;
|
||||
$oxford-blue: #313d4f;
|
||||
|
||||
// White
|
||||
$white: #ffffff;
|
||||
@@ -1,282 +0,0 @@
|
||||
/**************************************************************************
|
||||
TOOLS > SASS MQ
|
||||
https://github.com/sass-mq/sass-mq/blob/master/_mq.scss
|
||||
***************************************************************************/
|
||||
|
||||
@charset "UTF-8"; // Fixes an issue where Ruby locale is not set properly
|
||||
// See https://github.com/sass-mq/sass-mq/pull/10
|
||||
|
||||
/// Base font size on the `<body>` element
|
||||
/// @type Number (unit)
|
||||
$mq-base-font-size: 16px !default;
|
||||
|
||||
/// Responsive mode
|
||||
///
|
||||
/// Set to `false` to enable support for browsers that do not support @media queries,
|
||||
/// (IE <= 8, Firefox <= 3, Opera <= 9)
|
||||
///
|
||||
/// You could create a stylesheet served exclusively to older browsers,
|
||||
/// where @media queries are rasterized
|
||||
///
|
||||
/// @example scss
|
||||
/// // old-ie.scss
|
||||
/// $mq-responsive: false;
|
||||
/// @import 'main'; // @media queries in this file will be rasterized up to $mq-static-breakpoint
|
||||
/// // larger breakpoints will be ignored
|
||||
///
|
||||
/// @type Boolean
|
||||
/// @link https://github.com/sass-mq/sass-mq#responsive-mode-off Disabled responsive mode documentation
|
||||
$mq-responsive: true !default;
|
||||
|
||||
/// Breakpoint list
|
||||
///
|
||||
/// Name your breakpoints in a way that creates a ubiquitous language
|
||||
/// across team members. It will improve communication between
|
||||
/// stakeholders, designers, developers, and testers.
|
||||
///
|
||||
/// @type Map
|
||||
/// @link https://github.com/sass-mq/sass-mq#seeing-the-currently-active-breakpoint Full documentation and examples
|
||||
$mq-breakpoints: (
|
||||
mobile: 320px,
|
||||
tablet: 740px,
|
||||
desktop: 980px,
|
||||
wide: 1300px,
|
||||
superwide: 1800px
|
||||
) !default;
|
||||
|
||||
/// Static breakpoint (for fixed-width layouts)
|
||||
///
|
||||
/// Define the breakpoint from $mq-breakpoints that should
|
||||
/// be used as the target width for the fixed-width layout
|
||||
/// (i.e. when $mq-responsive is set to 'false') in a old-ie.scss
|
||||
///
|
||||
/// @example scss
|
||||
/// // tablet-only.scss
|
||||
/// //
|
||||
/// // Ignore all styles above tablet breakpoint,
|
||||
/// // and fix the styles (e.g. layout) at tablet width
|
||||
/// $mq-responsive: false;
|
||||
/// $mq-static-breakpoint: tablet;
|
||||
/// @import 'main'; // @media queries in this file will be rasterized up to tablet
|
||||
/// // larger breakpoints will be ignored
|
||||
///
|
||||
/// @type String
|
||||
/// @link https://github.com/sass-mq/sass-mq#adding-custom-breakpoints Full documentation and examples
|
||||
$mq-static-breakpoint: desktop !default;
|
||||
|
||||
/// Show breakpoints in the top right corner
|
||||
///
|
||||
/// If you want to display the currently active breakpoint in the top
|
||||
/// right corner of your site during development, add the breakpoints
|
||||
/// to this list, ordered by width, e.g. (mobile, tablet, desktop).
|
||||
///
|
||||
/// @type map
|
||||
$mq-show-breakpoints: () !default;
|
||||
|
||||
/// Customize the media type (e.g. `@media screen` or `@media print`)
|
||||
/// By default sass-mq uses an "all" media type (`@media all and …`)
|
||||
///
|
||||
/// @type String
|
||||
/// @link https://github.com/sass-mq/sass-mq#changing-media-type Full documentation and examples
|
||||
$mq-media-type: all !default;
|
||||
|
||||
/// Convert pixels to ems
|
||||
///
|
||||
/// @param {Number} $px - value to convert
|
||||
/// @param {Number} $base-font-size ($mq-base-font-size) - `<body>` font size
|
||||
///
|
||||
/// @example scss
|
||||
/// $font-size-in-ems: mq-px2em(16px);
|
||||
/// p { font-size: mq-px2em(16px); }
|
||||
///
|
||||
/// @requires $mq-base-font-size
|
||||
/// @returns {Number}
|
||||
@function mq-px2em($px, $base-font-size: $mq-base-font-size) {
|
||||
@if unitless($px) {
|
||||
@warn "Assuming #{$px} to be in pixels, attempting to convert it into pixels.";
|
||||
@return mq-px2em($px * 1px, $base-font-size);
|
||||
} @else if unit($px) == em {
|
||||
@return $px;
|
||||
}
|
||||
@return ($px / $base-font-size) * 1em;
|
||||
}
|
||||
|
||||
/// Get a breakpoint's width
|
||||
///
|
||||
/// @param {String} $name - Name of the breakpoint. One of $mq-breakpoints
|
||||
///
|
||||
/// @example scss
|
||||
/// $tablet-width: mq-get-breakpoint-width(tablet);
|
||||
/// @media (min-width: mq-get-breakpoint-width(desktop)) {}
|
||||
///
|
||||
/// @requires {Variable} $mq-breakpoints
|
||||
///
|
||||
/// @returns {Number} Value in pixels
|
||||
@function mq-get-breakpoint-width($name, $breakpoints: $mq-breakpoints) {
|
||||
@if map-has-key($breakpoints, $name) {
|
||||
@return map-get($breakpoints, $name);
|
||||
} @else {
|
||||
@warn "Breakpoint #{$name} wasn't found in $breakpoints.";
|
||||
}
|
||||
}
|
||||
|
||||
/// Media Query mixin
|
||||
///
|
||||
/// @param {String | Boolean} $from (false) - One of $mq-breakpoints
|
||||
/// @param {String | Boolean} $until (false) - One of $mq-breakpoints
|
||||
/// @param {String | Boolean} $and (false) - Additional media query parameters
|
||||
/// @param {String} $media-type ($mq-media-type) - Media type: screen, print…
|
||||
///
|
||||
/// @ignore Undocumented API, for advanced use only:
|
||||
/// @ignore @param {Map} $breakpoints ($mq-breakpoints)
|
||||
/// @ignore @param {String} $static-breakpoint ($mq-static-breakpoint)
|
||||
///
|
||||
/// @content styling rules, wrapped into a @media query when $responsive is true
|
||||
///
|
||||
/// @requires {Variable} $mq-media-type
|
||||
/// @requires {Variable} $mq-breakpoints
|
||||
/// @requires {Variable} $mq-static-breakpoint
|
||||
/// @requires {function} mq-px2em
|
||||
/// @requires {function} mq-get-breakpoint-width
|
||||
///
|
||||
/// @link https://github.com/sass-mq/sass-mq#responsive-mode-on-default Full documentation and examples
|
||||
///
|
||||
@mixin mq(
|
||||
$from: false,
|
||||
$until: false,
|
||||
$and: false,
|
||||
$media-type: $mq-media-type,
|
||||
$breakpoints: $mq-breakpoints,
|
||||
$responsive: $mq-responsive,
|
||||
$static-breakpoint: $mq-static-breakpoint
|
||||
) {
|
||||
$min-width: 0;
|
||||
$max-width: 0;
|
||||
$media-query: "";
|
||||
|
||||
// From: this breakpoint (inclusive)
|
||||
@if $from {
|
||||
@if type-of($from) == number {
|
||||
$min-width: mq-px2em($from);
|
||||
} @else {
|
||||
$min-width: mq-px2em(mq-get-breakpoint-width($from, $breakpoints));
|
||||
}
|
||||
}
|
||||
|
||||
// Until: that breakpoint (exclusive)
|
||||
@if $until {
|
||||
@if type-of($until) == number {
|
||||
$max-width: mq-px2em($until);
|
||||
} @else {
|
||||
$max-width: mq-px2em(mq-get-breakpoint-width($until, $breakpoints)) -
|
||||
0.01em;
|
||||
}
|
||||
}
|
||||
|
||||
// Responsive support is disabled, rasterize the output outside @media blocks
|
||||
// The browser will rely on the cascade itself.
|
||||
@if $responsive == false {
|
||||
$static-breakpoint-width: mq-get-breakpoint-width(
|
||||
$static-breakpoint,
|
||||
$breakpoints
|
||||
);
|
||||
$target-width: mq-px2em($static-breakpoint-width);
|
||||
|
||||
// Output only rules that start at or span our target width
|
||||
@if (
|
||||
$and ==
|
||||
false and
|
||||
$min-width <=
|
||||
$target-width and
|
||||
($until == false or $max-width >= $target-width)
|
||||
) {
|
||||
@content;
|
||||
}
|
||||
}
|
||||
|
||||
// Responsive support is enabled, output rules inside @media queries
|
||||
@else {
|
||||
@if $min-width != 0 {
|
||||
$media-query: "#{$media-query} and (min-width: #{$min-width})";
|
||||
}
|
||||
@if $max-width != 0 {
|
||||
$media-query: "#{$media-query} and (max-width: #{$max-width})";
|
||||
}
|
||||
@if $and {
|
||||
$media-query: "#{$media-query} and #{$and}";
|
||||
}
|
||||
|
||||
// Remove unnecessary media query prefix 'all and '
|
||||
@if ($media-type == "all" and $media-query != "") {
|
||||
$media-type: "";
|
||||
$media-query: str-slice(unquote($media-query), 6);
|
||||
}
|
||||
|
||||
@media #{$media-type + $media-query} {
|
||||
@content;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a breakpoint
|
||||
///
|
||||
/// @param {String} $name - Name of the breakpoint
|
||||
/// @param {Number} $width - Width of the breakpoint
|
||||
///
|
||||
/// @requires {Variable} $mq-breakpoints
|
||||
///
|
||||
/// @example scss
|
||||
/// @include mq-add-breakpoint(tvscreen, 1920px);
|
||||
/// @include mq(tvscreen) {}
|
||||
@mixin mq-add-breakpoint($name, $width) {
|
||||
$new-breakpoint: (
|
||||
$name: $width
|
||||
);
|
||||
$mq-breakpoints: map-merge($mq-breakpoints, $new-breakpoint) !global;
|
||||
}
|
||||
|
||||
/// Show the active breakpoint in the top right corner of the viewport
|
||||
/// @link https://github.com/sass-mq/sass-mq#seeing-the-currently-active-breakpoint
|
||||
///
|
||||
/// @param {List} $show-breakpoints ($mq-show-breakpoints) - List of breakpoints to show in the top right corner
|
||||
/// @param {Map} $breakpoints ($mq-breakpoints) - Breakpoint names and sizes
|
||||
///
|
||||
/// @requires {Variable} $mq-breakpoints
|
||||
/// @requires {Variable} $mq-show-breakpoints
|
||||
///
|
||||
/// @example scss
|
||||
/// // Show breakpoints using global settings
|
||||
/// @include mq-show-breakpoints;
|
||||
///
|
||||
/// // Show breakpoints using custom settings
|
||||
/// @include mq-show-breakpoints((L, XL), (S: 300px, L: 800px, XL: 1200px));
|
||||
@mixin mq-show-breakpoints(
|
||||
$show-breakpoints: $mq-show-breakpoints,
|
||||
$breakpoints: $mq-breakpoints
|
||||
) {
|
||||
body:before {
|
||||
background-color: #fcf8e3;
|
||||
border-bottom: 1px solid #fbeed5;
|
||||
border-left: 1px solid #fbeed5;
|
||||
color: #c09853;
|
||||
font: small-caption;
|
||||
padding: 3px 6px;
|
||||
pointer-events: none;
|
||||
position: fixed;
|
||||
right: 0;
|
||||
top: 0;
|
||||
z-index: 3;
|
||||
|
||||
// Loop through the breakpoints that should be shown
|
||||
@each $show-breakpoint in $show-breakpoints {
|
||||
$width: mq-get-breakpoint-width($show-breakpoint, $breakpoints);
|
||||
@include mq($show-breakpoint, $breakpoints: $breakpoints) {
|
||||
content: "#{$show-breakpoint} ≥ #{$width} (#{mq-px2em($width)})";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@if length($mq-show-breakpoints) > 0 {
|
||||
@include mq-show-breakpoints;
|
||||
}
|
||||
@@ -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 it’s 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 doesn’t 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 doesn’t exist).
|
||||
Drive.append(relativePath, content, options = {}) // Append content to a file (creates a new file if path doesn’t 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 user’s 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.
|
||||
@@ -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 user’s 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
|
||||
@@ -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`
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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);
|
||||
@@ -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.
|
||||
@@ -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 app’s 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, you’ll 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) {})
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = {extends: ['@commitlint/config-conventional']}
|
||||
@@ -1,139 +0,0 @@
|
||||
<!-- *************************************************************************
|
||||
TEMPLATE
|
||||
************************************************************************* -->
|
||||
|
||||
<template lang="pug">
|
||||
.c-base-cheatsheet
|
||||
a(
|
||||
:href="link"
|
||||
class="c-base-cheatsheet__link"
|
||||
target="_blank"
|
||||
)
|
||||
img(
|
||||
:src="baseUrl + '/images/components/BaseCheatsheet/' + thumbnail"
|
||||
class="c-base-cheatsheet__thumbnail"
|
||||
)
|
||||
|
||||
.c-base-cheatsheet__content
|
||||
a(
|
||||
:href="link"
|
||||
class="c-base-cheatsheet__name"
|
||||
target="_blank"
|
||||
) The {{ name }} Cheatsheet
|
||||
|
||||
.c-base-cheatsheet__share
|
||||
base-share(
|
||||
v-for="network in networks"
|
||||
@click="onShare"
|
||||
:key="network"
|
||||
:network="network"
|
||||
class="c-base-cheatsheet__network"
|
||||
)
|
||||
</template>
|
||||
|
||||
<!-- *************************************************************************
|
||||
SCRIPT
|
||||
************************************************************************* -->
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
link: {
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
name: {
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
thumbnail: {
|
||||
type: String,
|
||||
required: true
|
||||
}
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
// --> STATE <--
|
||||
baseUrl: process.env.baseUrl,
|
||||
|
||||
// --> COMPONENTS <--
|
||||
networks: ["Facebook", "Twitter", "LinkedIn", "Telegram"]
|
||||
};
|
||||
},
|
||||
|
||||
methods: {
|
||||
onShare(network) {
|
||||
const link = this.link;
|
||||
const socialNetwork = network.toLowerCase();
|
||||
const technology = this.name;
|
||||
let url = "";
|
||||
let message = encodeURIComponent(
|
||||
`Check this awesome cheatsheet about ${technology}: ${link} #${technology.toLowerCase()} #cheatsheet`
|
||||
);
|
||||
|
||||
if (socialNetwork === "facebook") {
|
||||
url = `https://www.facebook.com/sharer/sharer.php?u=${link}`;
|
||||
} else if (socialNetwork === "telegram") {
|
||||
url = `https://telegram.me/share/url?url=${link}&text=${message}`;
|
||||
} else if (socialNetwork === "twitter") {
|
||||
url = `https://twitter.com/intent/tweet?text=${message}`;
|
||||
} else if (socialNetwork === "linkedin") {
|
||||
url = `https://www.linkedin.com/shareArticle?mini=true&url=${link}&source=LinkedIn`;
|
||||
}
|
||||
|
||||
window.open(url);
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<!-- *************************************************************************
|
||||
STYLE
|
||||
************************************************************************* -->
|
||||
|
||||
<style lang="scss">
|
||||
$c: ".c-base-cheatsheet";
|
||||
|
||||
#{$c} {
|
||||
display: block;
|
||||
padding: 10px;
|
||||
border: 1px solid $oxford-blue;
|
||||
border-radius: 6px;
|
||||
background: $ebony-clay;
|
||||
|
||||
#{$c}__link {
|
||||
#{$c}__thumbnail {
|
||||
width: 100%;
|
||||
height: 160px;
|
||||
border-radius: 4px;
|
||||
user-select: none;
|
||||
}
|
||||
}
|
||||
|
||||
#{$c}__content {
|
||||
padding: 10px;
|
||||
text-align: left;
|
||||
|
||||
#{$c}__name {
|
||||
margin-bottom: 20px;
|
||||
color: $white;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
#{$c}__share {
|
||||
margin-top: 12px;
|
||||
display: flex;
|
||||
user-select: none;
|
||||
|
||||
#{$c}__network {
|
||||
margin-right: 6px;
|
||||
|
||||
&:last-of-type {
|
||||
margin-right: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,55 +0,0 @@
|
||||
<!-- *************************************************************************
|
||||
TEMPLATE
|
||||
************************************************************************* -->
|
||||
|
||||
<template lang="pug">
|
||||
.c-base-divider
|
||||
span.c-base-divider__category {{ category }}
|
||||
|
||||
hr.c-base-divider__line
|
||||
</template>
|
||||
|
||||
<!-- *************************************************************************
|
||||
SCRIPT
|
||||
************************************************************************* -->
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
category: {
|
||||
name: String,
|
||||
required: true
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<!-- *************************************************************************
|
||||
STYLE
|
||||
************************************************************************* -->
|
||||
|
||||
<style lang="scss">
|
||||
$c: ".c-base-divider";
|
||||
|
||||
#{$c} {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
#{$c}__category {
|
||||
margin-right: 20px;
|
||||
color: $white;
|
||||
text-align-last: left;
|
||||
text-transform: uppercase;
|
||||
font-weight: bold;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
#{$c}__line {
|
||||
flex: 1;
|
||||
display: block;
|
||||
height: 1px;
|
||||
border: 0;
|
||||
border-top: 1px solid $oxford-blue;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,63 +0,0 @@
|
||||
<!-- *************************************************************************
|
||||
TEMPLATE
|
||||
************************************************************************* -->
|
||||
|
||||
<template lang="pug">
|
||||
div(
|
||||
:data-balloon="'Share on ' + network"
|
||||
class="c-base-share"
|
||||
data-balloon-pos="up"
|
||||
data-balloon-type="mini"
|
||||
)
|
||||
img(
|
||||
@click="onClick"
|
||||
:src="baseUrl + '/images/components/BaseShare/' + network.toLowerCase() + '.svg'"
|
||||
class="c-base-share__image"
|
||||
)
|
||||
</template>
|
||||
|
||||
<!-- *************************************************************************
|
||||
SCRIPT
|
||||
************************************************************************* -->
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
network: {
|
||||
type: String,
|
||||
required: true
|
||||
}
|
||||
},
|
||||
|
||||
data() {
|
||||
return {
|
||||
// --> STATE <--
|
||||
baseUrl: process.env.baseUrl
|
||||
};
|
||||
},
|
||||
|
||||
methods: {
|
||||
onClick() {
|
||||
this.$emit("click", this.network);
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<!-- *************************************************************************
|
||||
STYLE
|
||||
************************************************************************* -->
|
||||
|
||||
<style lang="scss">
|
||||
$c: ".c-base-share";
|
||||
|
||||
#{$c} {
|
||||
display: inline-block;
|
||||
|
||||
#{$c}__image {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,70 +0,0 @@
|
||||
<!-- *************************************************************************
|
||||
TEMPLATE
|
||||
************************************************************************* -->
|
||||
|
||||
<template lang="pug">
|
||||
a(
|
||||
class="c-the-copyright"
|
||||
href="https://twitter.com/LeCoupa"
|
||||
target="_blank"
|
||||
)
|
||||
span.c-the-copyright__name By LeCoupa
|
||||
|
||||
img(
|
||||
:src="baseUrl + '/images/common/lecoupa.jpg'"
|
||||
class="c-the-copyright__picture"
|
||||
)
|
||||
</template>
|
||||
|
||||
<!-- *************************************************************************
|
||||
SCRIPT
|
||||
************************************************************************* -->
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
// --> STATE <--
|
||||
baseUrl: process.env.baseUrl
|
||||
};
|
||||
},
|
||||
|
||||
methods: {
|
||||
onClick() {
|
||||
console.log("onClick");
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<!-- *************************************************************************
|
||||
STYLE
|
||||
************************************************************************* -->
|
||||
|
||||
<style lang="scss">
|
||||
$c: ".c-the-copyright";
|
||||
|
||||
#{$c} {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 5px 10px;
|
||||
border-top: 1px solid $oxford-blue;
|
||||
border-left: 1px solid $oxford-blue;
|
||||
border-top-left-radius: 4px;
|
||||
background-color: $mirage2;
|
||||
|
||||
#{$c}__name {
|
||||
margin-right: 6px;
|
||||
color: $white;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
#{$c}__picture {
|
||||
display: inline-block;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,113 +0,0 @@
|
||||
<!-- *************************************************************************
|
||||
TEMPLATE
|
||||
************************************************************************* -->
|
||||
|
||||
<template lang="pug">
|
||||
.c-the-github-buttons
|
||||
span.c-the-github-buttons__wrapper
|
||||
iframe(
|
||||
:src="'https://ghbtns.com/github-btn.html?user=' + user + '&repo=' + repo + '&type=star&count=true'"
|
||||
frameborder="0"
|
||||
scrolling="0"
|
||||
height="20px"
|
||||
class="c-the-github-buttons__button c-the-github-buttons__button--star"
|
||||
)
|
||||
|
||||
span.c-the-github-buttons__wrapper
|
||||
iframe(
|
||||
:src="'https://ghbtns.com/github-btn.html?user=' + user + '&repo=' + repo + '&type=watch&count=true&v=2'"
|
||||
frameborder="0"
|
||||
scrolling="0"
|
||||
height="20px"
|
||||
class="c-the-github-buttons__button c-the-github-buttons__button--watch"
|
||||
)
|
||||
|
||||
span.c-the-github-buttons__wrapper
|
||||
iframe(
|
||||
:src="'https://ghbtns.com/github-btn.html?user=' + user + '&repo=' + repo + '&type=fork&count=true'"
|
||||
frameborder="0"
|
||||
scrolling="0"
|
||||
height="20px"
|
||||
class="c-the-github-buttons__button c-the-github-buttons__button--fork"
|
||||
)
|
||||
|
||||
span.c-the-github-buttons__wrapper
|
||||
iframe(
|
||||
:src="'https://ghbtns.com/github-btn.html?user=' + user + '&type=follow&count=true'"
|
||||
frameborder="0"
|
||||
scrolling="0"
|
||||
height="20px"
|
||||
class="c-the-github-buttons__button c-the-github-buttons__button--follow"
|
||||
)
|
||||
</template>
|
||||
|
||||
<!-- *************************************************************************
|
||||
SCRIPT
|
||||
************************************************************************* -->
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
repo: {
|
||||
type: String,
|
||||
required: true
|
||||
},
|
||||
user: {
|
||||
type: String,
|
||||
required: true
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<!-- *************************************************************************
|
||||
STYLE
|
||||
************************************************************************* -->
|
||||
|
||||
<style lang="scss">
|
||||
$c: ".c-the-github-buttons";
|
||||
|
||||
#{$c} {
|
||||
#{$c}__wrapper {
|
||||
display: inline-block;
|
||||
margin-bottom: 10px;
|
||||
width: 100%;
|
||||
|
||||
#{$c}__button {
|
||||
margin: 0 auto;
|
||||
|
||||
&--star {
|
||||
width: 110px;
|
||||
}
|
||||
|
||||
&--watch {
|
||||
width: 110px;
|
||||
}
|
||||
|
||||
&--fork {
|
||||
width: 110px;
|
||||
}
|
||||
|
||||
&--follow {
|
||||
width: 160px;
|
||||
}
|
||||
|
||||
&:nth-last-of-type {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@include mq($from: tablet) {
|
||||
#{$c} {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
|
||||
#{$c}__wrapper {
|
||||
margin-bottom: 0;
|
||||
width: initial;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -1,63 +0,0 @@
|
||||
<!-- *************************************************************************
|
||||
TEMPLATE
|
||||
************************************************************************* -->
|
||||
|
||||
<template lang="pug">
|
||||
<a :href="link" class="github-corner" aria-label="View source on Github">
|
||||
<svg width="80" height="80" viewBox="0 0 250 250" style="fill:#fff; color:#1b2431; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
|
||||
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
|
||||
<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
|
||||
<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>
|
||||
</svg>
|
||||
</a>
|
||||
</template>
|
||||
|
||||
<!-- *************************************************************************
|
||||
SCRIPT
|
||||
************************************************************************* -->
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
link: {
|
||||
type: String,
|
||||
required: true
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<!-- *************************************************************************
|
||||
STYLE
|
||||
************************************************************************* -->
|
||||
|
||||
<style lang="scss">
|
||||
.github-corner:hover .octo-arm {
|
||||
animation: octocat-wave 560ms ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes octocat-wave {
|
||||
0%,
|
||||
100% {
|
||||
transform: rotate(0);
|
||||
}
|
||||
20%,
|
||||
60% {
|
||||
transform: rotate(-25deg);
|
||||
}
|
||||
40%,
|
||||
80% {
|
||||
transform: rotate(10deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 500px) {
|
||||
.github-corner:hover .octo-arm {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.github-corner .octo-arm {
|
||||
animation: octocat-wave 560ms ease-in-out;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -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 } })
|
||||
@@ -0,0 +1,84 @@
|
||||
# *****************************************************************************
|
||||
# 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
|
||||
|
||||
# *****************************************************************************
|
||||
# Database and Table Operations
|
||||
# *****************************************************************************
|
||||
|
||||
CREATE DATABASE database_name; # Create a new database
|
||||
DROP DATABASE database_name; # Delete a database
|
||||
CREATE TABLE table_name (column1 datatype, column2 datatype, ...); # Create a new table
|
||||
DROP TABLE table_name; # Delete a table
|
||||
SHOW TABLES; # Display all tables in the current database
|
||||
DESCRIBE table_name; # Show the structure of a table
|
||||
|
||||
# *****************************************************************************
|
||||
# Data Manipulation
|
||||
# *****************************************************************************
|
||||
|
||||
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...); # Insert data into a table
|
||||
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition; # Update existing data in a table
|
||||
DELETE FROM table_name WHERE condition; # Delete data from a table
|
||||
SELECT column1, column2, ... FROM table_name WHERE condition; # Select data from a table
|
||||
|
||||
# *****************************************************************************
|
||||
# Backup and Restore
|
||||
# *****************************************************************************
|
||||
|
||||
mysqldump -u username -p database_name table1 table2 > file.sql # Backup specific tables
|
||||
mysql -u username -p database_name < file.sql # Restore specific tables
|
||||
|
||||
# *****************************************************************************
|
||||
# User Management and Security
|
||||
# *****************************************************************************
|
||||
|
||||
REVOKE privilege_type ON database_name.table_name FROM 'username'@'hostname'; # Revoke privileges from a user
|
||||
DROP USER 'username'@'hostname'; # Delete a user
|
||||
ALTER USER 'username'@'hostname' IDENTIFIED BY 'newpassword'; # Reset a user's password
|
||||
|
||||
# *****************************************************************************
|
||||
# Performance and Maintenance
|
||||
# *****************************************************************************
|
||||
|
||||
OPTIMIZE TABLE table_name; # Optimize a table
|
||||
ANALYZE TABLE table_name; # Analyze a table for key distribution and storage optimization
|
||||
CHECK TABLE table_name; # Check a table for errors
|
||||
REPAIR TABLE table_name; # Repair a corrupted table
|
||||
|
||||
# *****************************************************************************
|
||||
# Advanced Queries
|
||||
# *****************************************************************************
|
||||
|
||||
SELECT ... FROM table1 JOIN table2 ON table1.column = table2.column; # Perform a join operation between two tables
|
||||
SELECT ... FROM (SELECT ... FROM table_name) AS subquery; # Use a subquery within another query
|
||||
SELECT column, COUNT(*) FROM table_name GROUP BY column; # Group results and use aggregate functions
|
||||
|
||||
# *****************************************************************************
|
||||
# System Information
|
||||
# *****************************************************************************
|
||||
|
||||
SELECT VERSION(); # Show the current version of MySQL
|
||||
SELECT User, Host FROM mysql.user; # List all current MySQL users
|
||||
|
||||
# *****************************************************************************
|
||||
# Miscellaneous
|
||||
# *****************************************************************************
|
||||
|
||||
SET GLOBAL general_log = 'ON'; # Enable query logging
|
||||
SHOW FULL PROCESSLIST; # Show the last queries executed in MySQL
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -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
|
||||
*/
|
||||
@@ -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}}([]);
|
||||
|
Before Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 82 KiB |
|
Before Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 21 KiB |
|
Before Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 32 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 24 KiB |
@@ -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 |
@@ -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 |
@@ -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 |
@@ -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 |
@@ -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 |
@@ -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 |
@@ -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 component’s 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: ...
|
||||
}
|
||||
@@ -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')()
|
||||
@@ -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 */
|
||||
|
||||
|
||||
|
||||
@@ -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/
|
||||
@@ -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 -->
|
||||
|
||||
|
||||
" " Quotation Marks - "
|
||||
& & Ampersand - &
|
||||
< < Less than sign - <
|
||||
> > Greater than sign - >
|
||||
  Non-breaking space
|
||||
© © Copyright Symbol - ©
|
||||
@ Ü @ symbol - @
|
||||
• ö Small bullet - .
|
||||
™ û Trademark Symbol - ™
|
||||
@@ -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 element’s 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, it’s 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, don’t 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 component’s 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 it’s 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 don’t use it in render(), it shouldn’t 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 component’s 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 doesn’t 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 doesn’t 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.'
|
||||
);
|
||||
}
|
||||
})
|
||||
};
|
||||
@@ -0,0 +1,670 @@
|
||||
/****************************
|
||||
* TYPESCRIPT CHEATSHEET - Quick Reference
|
||||
* Learn more: https://www.typescriptlang.org/docs/
|
||||
* Playground: https://www.typescriptlang.org/play
|
||||
* Handbook: https://www.typescriptlang.org/handbook/
|
||||
*
|
||||
* Table of contents
|
||||
* -------------------
|
||||
* 01 | Basic Types
|
||||
* 02 | Variables & Arrays
|
||||
* 03 | Functions
|
||||
* 04 | Objects & Interfaces
|
||||
* 05 | Classes
|
||||
* 06 | Generics
|
||||
* 07 | Union & Literal Types
|
||||
* 08 | Type Guards & Assertions
|
||||
* 09 | Utility Types
|
||||
* 10 | Enums
|
||||
* 11 | Modules
|
||||
* 12 | Advanced Types
|
||||
* 13 | Decorators
|
||||
* 14 | Configuration
|
||||
* 15 | Common Patterns
|
||||
*****************************/
|
||||
|
||||
/***************************
|
||||
------------ 01: Basic Types -----------
|
||||
*******************************/
|
||||
|
||||
// Primitive Types
|
||||
let str: string = "hello";
|
||||
let num: number = 42;
|
||||
let bool: boolean = true;
|
||||
let undef: undefined = undefined;
|
||||
let nul: null = null;
|
||||
|
||||
// Special Types
|
||||
let anything: any = "can be anything";
|
||||
let unknown: unknown = "type-safe any";
|
||||
let nothing: void = undefined;
|
||||
let never: never = (() => { throw new Error() })();
|
||||
|
||||
// Type Inference
|
||||
let auto = "TypeScript infers string";
|
||||
let nums = [1, 2, 3]; // number[]
|
||||
|
||||
/***************************
|
||||
------------ 02: Variables & Arrays -----------
|
||||
*******************************/
|
||||
|
||||
// Arrays
|
||||
let numbers: number[] = [1, 2, 3];
|
||||
let strings: Array<string> = ["a", "b"];
|
||||
let mixed: (string | number)[] = [1, "two"];
|
||||
|
||||
// Tuples
|
||||
let tuple: [string, number] = ["hello", 42];
|
||||
let namedTuple: [name: string, age: number] = ["John", 30];
|
||||
|
||||
// Destructuring
|
||||
let [first, second] = tuple;
|
||||
let [x, y, ...rest] = [1, 2, 3, 4, 5];
|
||||
|
||||
// Object Destructuring
|
||||
let {name, age} = {name: "John", age: 30};
|
||||
let {a: newName, b = 10} = {a: "value"}; // rename & default
|
||||
|
||||
/***************************
|
||||
------------ 03: Functions -----------
|
||||
*******************************/
|
||||
|
||||
// Function Declaration
|
||||
function add(x: number, y: number): number {
|
||||
return x + y;
|
||||
}
|
||||
|
||||
// Arrow Functions
|
||||
const multiply = (x: number, y: number): number => x * y;
|
||||
const greet = (name: string): void => console.log(`Hello ${name}`);
|
||||
|
||||
// Optional & Default Parameters
|
||||
function build(first: string, last?: string, age = 25): string {
|
||||
return `${first} ${last || ""} (${age})`;
|
||||
}
|
||||
|
||||
// Rest Parameters
|
||||
function sum(...nums: number[]): number {
|
||||
return nums.reduce((a, b) => a + b, 0);
|
||||
}
|
||||
|
||||
// Function Overloads
|
||||
function format(x: string): string;
|
||||
function format(x: number): string;
|
||||
function format(x: string | number): string {
|
||||
return x.toString();
|
||||
}
|
||||
|
||||
// Function Types
|
||||
type MathOp = (x: number, y: number) => number;
|
||||
const divide: MathOp = (x, y) => x / y;
|
||||
|
||||
/***************************
|
||||
------------ 04: Objects & Interfaces -----------
|
||||
*******************************/
|
||||
|
||||
// Object Types
|
||||
let person: {name: string, age: number} = {name: "John", age: 30};
|
||||
|
||||
// Interface
|
||||
interface User {
|
||||
readonly id: number;
|
||||
name: string;
|
||||
email?: string; // optional
|
||||
[key: string]: any; // index signature
|
||||
}
|
||||
|
||||
// Extending Interfaces
|
||||
interface Admin extends User {
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
// Multiple Inheritance
|
||||
interface Timestamped {
|
||||
createdAt: Date;
|
||||
}
|
||||
interface AdminUser extends User, Timestamped {
|
||||
role: "admin";
|
||||
}
|
||||
|
||||
// Function in Interface
|
||||
interface Calculator {
|
||||
add(x: number, y: number): number;
|
||||
subtract: (x: number, y: number) => number;
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 05: Classes -----------
|
||||
*******************************/
|
||||
|
||||
// Basic Class
|
||||
class Animal {
|
||||
public name: string;
|
||||
private age: number;
|
||||
protected species: string;
|
||||
readonly id: number;
|
||||
|
||||
constructor(name: string, age: number) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.species = "unknown";
|
||||
this.id = Math.random();
|
||||
}
|
||||
|
||||
speak(): void {
|
||||
console.log(`${this.name} makes a sound`);
|
||||
}
|
||||
}
|
||||
|
||||
// Inheritance
|
||||
class Dog extends Animal {
|
||||
breed: string;
|
||||
|
||||
constructor(name: string, age: number, breed: string) {
|
||||
super(name, age);
|
||||
this.breed = breed;
|
||||
}
|
||||
|
||||
speak(): void {
|
||||
console.log(`${this.name} barks`);
|
||||
}
|
||||
}
|
||||
|
||||
// Abstract Class
|
||||
abstract class Shape {
|
||||
abstract area(): number;
|
||||
|
||||
display(): void {
|
||||
console.log(`Area: ${this.area()}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Static Members
|
||||
class MathUtils {
|
||||
static PI = 3.14159;
|
||||
static circle(radius: number): number {
|
||||
return 2 * MathUtils.PI * radius;
|
||||
}
|
||||
}
|
||||
|
||||
// Getters/Setters
|
||||
class Person {
|
||||
private _age: number = 0;
|
||||
|
||||
get age(): number {
|
||||
return this._age;
|
||||
}
|
||||
|
||||
set age(value: number) {
|
||||
if (value >= 0) this._age = value;
|
||||
}
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 06: Generics -----------
|
||||
*******************************/
|
||||
|
||||
// Generic Functions
|
||||
function identity<T>(arg: T): T { return arg; }
|
||||
const result = identity<string>("hello");
|
||||
const inferred = identity(42); // T inferred as number
|
||||
|
||||
// Multiple Type Parameters
|
||||
function pair<T, U>(first: T, second: U): [T, U] {
|
||||
return [first, second];
|
||||
}
|
||||
|
||||
// Generic Interface
|
||||
interface Container<T> {
|
||||
value: T;
|
||||
getValue(): T;
|
||||
}
|
||||
|
||||
// Generic Class
|
||||
class Box<T> {
|
||||
contents: T;
|
||||
constructor(value: T) {
|
||||
this.contents = value;
|
||||
}
|
||||
}
|
||||
|
||||
// Constraints
|
||||
interface HasLength {
|
||||
length: number;
|
||||
}
|
||||
|
||||
function logLength<T extends HasLength>(arg: T): void {
|
||||
console.log(arg.length);
|
||||
}
|
||||
|
||||
// Keyof Constraint
|
||||
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
|
||||
return obj[key];
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 07: Union & Literal Types -----------
|
||||
*******************************/
|
||||
|
||||
// Union Types
|
||||
type StringOrNumber = string | number;
|
||||
type Status = "loading" | "success" | "error";
|
||||
|
||||
function process(id: string | number): void {
|
||||
if (typeof id === "string") {
|
||||
console.log(id.toUpperCase());
|
||||
} else {
|
||||
console.log(id.toFixed(2));
|
||||
}
|
||||
}
|
||||
|
||||
// Intersection Types
|
||||
type Person = {name: string};
|
||||
type Employee = {company: string};
|
||||
type Staff = Person & Employee; // has both properties
|
||||
|
||||
// Literal Types
|
||||
type Theme = "light" | "dark";
|
||||
type Port = 3000 | 8080 | 9000;
|
||||
type Success = true;
|
||||
|
||||
// Discriminated Unions
|
||||
interface Circle {
|
||||
kind: "circle";
|
||||
radius: number;
|
||||
}
|
||||
interface Square {
|
||||
kind: "square";
|
||||
sideLength: number;
|
||||
}
|
||||
type Shape = Circle | Square;
|
||||
|
||||
function area(shape: Shape): number {
|
||||
switch (shape.kind) {
|
||||
case "circle":
|
||||
return Math.PI * shape.radius ** 2;
|
||||
case "square":
|
||||
return shape.sideLength ** 2;
|
||||
}
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 08: Type Guards & Assertions -----------
|
||||
*******************************/
|
||||
|
||||
// Type Guards
|
||||
function isString(value: any): value is string {
|
||||
return typeof value === "string";
|
||||
}
|
||||
|
||||
function isNumber(value: any): value is number {
|
||||
return typeof value === "number";
|
||||
}
|
||||
|
||||
// Using Type Guards
|
||||
function process(value: string | number) {
|
||||
if (isString(value)) {
|
||||
console.log(value.toUpperCase()); // TypeScript knows it's string
|
||||
} else {
|
||||
console.log(value.toFixed(2)); // TypeScript knows it's number
|
||||
}
|
||||
}
|
||||
|
||||
// in operator
|
||||
type Fish = { swim: () => void };
|
||||
type Bird = { fly: () => void };
|
||||
|
||||
function move(animal: Fish | Bird) {
|
||||
if ("swim" in animal) {
|
||||
animal.swim(); // Fish
|
||||
} else {
|
||||
animal.fly(); // Bird
|
||||
}
|
||||
}
|
||||
|
||||
// instanceof
|
||||
function handleError(error: Error | string) {
|
||||
if (error instanceof Error) {
|
||||
console.log(error.message);
|
||||
} else {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
// Type Assertions
|
||||
let someValue: any = "hello world";
|
||||
let strLength = (someValue as string).length;
|
||||
// or: let strLength = (<string>someValue).length;
|
||||
|
||||
// Non-null Assertion
|
||||
let name: string | null = getName();
|
||||
let nameLength = name!.length; // Assert name is not null
|
||||
|
||||
/***************************
|
||||
------------ 09: Utility Types -----------
|
||||
*******************************/
|
||||
|
||||
interface Todo {
|
||||
title: string;
|
||||
description: string;
|
||||
completed: boolean;
|
||||
}
|
||||
|
||||
// Partial<T> - All properties optional
|
||||
type PartialTodo = Partial<Todo>;
|
||||
// {title?: string, description?: string, completed?: boolean}
|
||||
|
||||
// Required<T> - All properties required
|
||||
type RequiredTodo = Required<PartialTodo>;
|
||||
|
||||
// Readonly<T> - All properties readonly
|
||||
type ReadonlyTodo = Readonly<Todo>;
|
||||
|
||||
// Pick<T, K> - Select specific properties
|
||||
type TodoPreview = Pick<Todo, "title" | "completed">;
|
||||
|
||||
// Omit<T, K> - Exclude specific properties
|
||||
type TodoInfo = Omit<Todo, "completed">;
|
||||
|
||||
// Record<K, T> - Create object type
|
||||
type TodoStatus = Record<"pending" | "completed", Todo[]>;
|
||||
|
||||
// Exclude<T, U> - Remove types from union
|
||||
type NonString = Exclude<string | number | boolean, string>;
|
||||
// number | boolean
|
||||
|
||||
// Extract<T, U> - Extract types from union
|
||||
type StringOnly = Extract<string | number | boolean, string>;
|
||||
// string
|
||||
|
||||
// NonNullable<T> - Remove null/undefined
|
||||
type NonNullString = NonNullable<string | null | undefined>;
|
||||
// string
|
||||
|
||||
// ReturnType<T> - Get function return type
|
||||
function getName(): string { return "John"; }
|
||||
type NameType = ReturnType<typeof getName>; // string
|
||||
|
||||
// Parameters<T> - Get function parameters as tuple
|
||||
type GetNameParams = Parameters<typeof getName>; // []
|
||||
|
||||
/***************************
|
||||
------------ 10: Enums -----------
|
||||
*******************************/
|
||||
|
||||
// Numeric Enum
|
||||
enum Direction {
|
||||
Up, // 0
|
||||
Down, // 1
|
||||
Left, // 2
|
||||
Right // 3
|
||||
}
|
||||
|
||||
// String Enum
|
||||
enum Color {
|
||||
Red = "red",
|
||||
Green = "green",
|
||||
Blue = "blue"
|
||||
}
|
||||
|
||||
// Mixed Enum
|
||||
enum Mixed {
|
||||
No = 0,
|
||||
Yes = "yes"
|
||||
}
|
||||
|
||||
// Const Enum (inlined at compile time)
|
||||
const enum StatusCode {
|
||||
OK = 200,
|
||||
NotFound = 404,
|
||||
Error = 500
|
||||
}
|
||||
|
||||
// Usage
|
||||
let currentDirection = Direction.Up;
|
||||
let favoriteColor = Color.Blue;
|
||||
let status = StatusCode.OK;
|
||||
|
||||
/***************************
|
||||
------------ 11: Modules -----------
|
||||
*******************************/
|
||||
|
||||
// Named Exports
|
||||
export const PI = 3.14159;
|
||||
export function calculate(r: number): number {
|
||||
return PI * r * r;
|
||||
}
|
||||
export class Calculator {
|
||||
add(x: number, y: number): number { return x + y; }
|
||||
}
|
||||
|
||||
// Default Export
|
||||
export default class Logger {
|
||||
log(message: string): void {
|
||||
console.log(message);
|
||||
}
|
||||
}
|
||||
|
||||
// Re-exports
|
||||
export { Calculator as Calc } from "./calculator";
|
||||
export * from "./utilities";
|
||||
|
||||
// Import
|
||||
import Logger from "./logger"; // default import
|
||||
import { PI, calculate } from "./math"; // named imports
|
||||
import * as MathUtils from "./math"; // namespace import
|
||||
import { Calculator as Calc } from "./calculator"; // alias
|
||||
|
||||
// Dynamic Imports
|
||||
const module = await import("./dynamic-module");
|
||||
|
||||
/***************************
|
||||
------------ 12: Advanced Types -----------
|
||||
*******************************/
|
||||
|
||||
// Mapped Types
|
||||
type Nullable<T> = {
|
||||
[P in keyof T]: T[P] | null;
|
||||
};
|
||||
|
||||
type OptionalId<T> = {
|
||||
[P in keyof T]: P extends "id" ? T[P] | undefined : T[P];
|
||||
};
|
||||
|
||||
// Conditional Types
|
||||
type IsString<T> = T extends string ? true : false;
|
||||
type StringCheck = IsString<"hello">; // true
|
||||
|
||||
// Template Literal Types
|
||||
type EventName<T extends string> = `on${Capitalize<T>}`;
|
||||
type ClickEvent = EventName<"click">; // "onClick"
|
||||
|
||||
// Indexed Access Types
|
||||
type Person = { name: string; age: number; location: string };
|
||||
type PersonName = Person["name"]; // string
|
||||
type PersonKeys = keyof Person; // "name" | "age" | "location"
|
||||
|
||||
// Recursive Types
|
||||
type Json = string | number | boolean | null | Json[] | {[key: string]: Json};
|
||||
|
||||
/***************************
|
||||
------------ 13: Decorators -----------
|
||||
*******************************/
|
||||
|
||||
// Class Decorator
|
||||
function Component(name: string) {
|
||||
return function<T extends {new(...args: any[]): {}}>(constructor: T) {
|
||||
return class extends constructor {
|
||||
componentName = name;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@Component("MyComponent")
|
||||
class MyClass {}
|
||||
|
||||
// Method Decorator
|
||||
function Log(target: any, propertyName: string, descriptor: PropertyDescriptor) {
|
||||
const method = descriptor.value;
|
||||
descriptor.value = function(...args: any[]) {
|
||||
console.log(`Calling ${propertyName} with`, args);
|
||||
return method.apply(this, args);
|
||||
};
|
||||
}
|
||||
|
||||
class Service {
|
||||
@Log
|
||||
getData(): string {
|
||||
return "data";
|
||||
}
|
||||
}
|
||||
|
||||
// Property Decorator
|
||||
function MinLength(length: number) {
|
||||
return function(target: any, propertyName: string) {
|
||||
let value: string;
|
||||
|
||||
const getter = () => value;
|
||||
const setter = (newVal: string) => {
|
||||
if (newVal.length < length) {
|
||||
throw new Error(`${propertyName} must be at least ${length} chars`);
|
||||
}
|
||||
value = newVal;
|
||||
};
|
||||
|
||||
Object.defineProperty(target, propertyName, {
|
||||
get: getter,
|
||||
set: setter
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
class User {
|
||||
@MinLength(3)
|
||||
username: string;
|
||||
}
|
||||
|
||||
/***************************
|
||||
------------ 14: Configuration -----------
|
||||
*******************************/
|
||||
|
||||
// tsconfig.json
|
||||
/*
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2020", "DOM"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"moduleResolution": "node",
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"sourceMap": true,
|
||||
"declaration": true,
|
||||
"removeComments": true,
|
||||
"noImplicitAny": true,
|
||||
"noImplicitReturns": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
*/
|
||||
|
||||
// Compiler Options Quick Reference
|
||||
// --target: ES5, ES6, ES2017, ES2018, ES2019, ES2020, ESNext
|
||||
// --module: commonjs, amd, es2015, es2020, esnext, system, umd
|
||||
// --lib: ES5, ES6, ES2017, DOM, WebWorker, ScriptHost
|
||||
// --strict: Enable all strict type checking options
|
||||
|
||||
/***************************
|
||||
------------ 15: Common Patterns -----------
|
||||
*******************************/
|
||||
|
||||
// API Response Type
|
||||
interface ApiResponse<T> {
|
||||
data: T;
|
||||
status: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Event Handler Pattern
|
||||
type EventHandler<T = Event> = (event: T) => void;
|
||||
const onClick: EventHandler<MouseEvent> = (e) => console.log(e.clientX);
|
||||
|
||||
// Builder Pattern
|
||||
class QueryBuilder {
|
||||
private query = "";
|
||||
|
||||
select(fields: string): this {
|
||||
this.query += `SELECT ${fields} `;
|
||||
return this;
|
||||
}
|
||||
|
||||
from(table: string): this {
|
||||
this.query += `FROM ${table} `;
|
||||
return this;
|
||||
}
|
||||
|
||||
build(): string {
|
||||
return this.query.trim();
|
||||
}
|
||||
}
|
||||
|
||||
// Factory Pattern
|
||||
interface Shape { area(): number; }
|
||||
class Circle implements Shape {
|
||||
constructor(private radius: number) {}
|
||||
area(): number { return Math.PI * this.radius ** 2; }
|
||||
}
|
||||
|
||||
class ShapeFactory {
|
||||
static createCircle(radius: number): Shape {
|
||||
return new Circle(radius);
|
||||
}
|
||||
}
|
||||
|
||||
// Promise/Async Patterns
|
||||
type AsyncResult<T> = Promise<T | Error>;
|
||||
|
||||
async function fetchUser(id: number): Promise<User | null> {
|
||||
try {
|
||||
const response = await fetch(`/api/users/${id}`);
|
||||
return await response.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Type-safe Environment Variables
|
||||
interface Env {
|
||||
NODE_ENV: "development" | "production" | "test";
|
||||
PORT: number;
|
||||
DATABASE_URL: string;
|
||||
}
|
||||
|
||||
declare global {
|
||||
namespace NodeJS {
|
||||
interface ProcessEnv extends Env {}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* QUICK TIPS
|
||||
* ----------
|
||||
* • Use 'unknown' instead of 'any' when possible
|
||||
* • Prefer 'interface' for object shapes, 'type' for unions/computed types
|
||||
* • Enable strict mode in tsconfig.json
|
||||
* • Use const assertions: const colors = ['red', 'blue'] as const
|
||||
* • Prefer type guards over type assertions
|
||||
* • Use utility types instead of manual type manipulation
|
||||
* • Enable noImplicitAny for better type safety
|
||||
* • Use discriminated unions for complex state management
|
||||
*/
|
||||
@@ -0,0 +1,799 @@
|
||||
/* *******************************************************************************************
|
||||
* GLOBAL CONFIG
|
||||
* Vue.config is an object containing Vue’s 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 instance’s 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 element’s 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 it’s 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 component’s 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, it’s 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 component’s VNode has updated, but possibly before its
|
||||
// children have updated. The directive’s value may or may not have changed, but you can
|
||||
// skip unnecessary updates by comparing the binding’s 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 component’s VNode and the VNodes of its children have updated.
|
||||
componentUpdated: function (el, binding, vnode, oldVnode) {
|
||||
console.log('The component’s 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 parent’s $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 component’s 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 component’s 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 isn’t 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 there’s 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 doesn’t 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 don’t 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 listener’s callback function.
|
||||
vm.$emit(event, […args])
|
||||
|
||||
|
||||
/* *******************************************************************************************
|
||||
* INSTANCE METHODS > LIFECYCLE
|
||||
* https://vuejs.org/v2/api/#Instance-Methods-Lifecycle
|
||||
* ******************************************************************************************* */
|
||||
|
||||
|
||||
// If a Vue instance didn’t 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 you’ve changed some data to wait for the DOM update.
|
||||
// This is the same as the global Vue.nextTick, except that the callback’s 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 element’s textContent. -->
|
||||
// <!-- If you need to update the part of textContent, you should use {{ Mustache }} interpolations. -->
|
||||
|
||||
// <span v-text="msg"></span>
|
||||
|
||||
|
||||
// <!-- Updates the element’s 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>
|
||||
|
||||
|
||||
// <!-- Toggle’s the element’s 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 directive’s 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 Vue’s 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 component’s $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>
|
||||
@@ -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 occurrence 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 characters 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
|
||||
|
||||
TimeSpan(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
|
||||
alignment - Indicates minimum width (in characters) to display value
|
||||
format string - Contains the code which specifies 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 constructor 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, parameters are passed by value
|
||||
2. Passing by reference: ref, in and out modifiers
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@@ -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 */
|
||||
|
||||
@@ -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)
|
||||
@@ -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 you’ve pulled from your history if you’ve 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' # Light Gray
|
||||
DGrey='\033[0;90m' # Dark Gray
|
||||
LRed='\033[0;91m' # Light Red
|
||||
LGreen='\033[0;92m' # Light Green
|
||||
LYellow='\033[0;93m'# Light Yellow
|
||||
LBlue='\033[0;94m' # Light Blue
|
||||
LPurple='\033[0;95m'# Light Purple
|
||||
LCyan='\033[0;96m' # Light 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"
|
||||
@@ -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. Deferred commands are
|
||||
// ran 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 assigned 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 set
|
||||
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/>
|
||||
@@ -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 constructor 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
|
||||
```
|
||||
@@ -0,0 +1,103 @@
|
||||
/* *******************************************************************************************
|
||||
* 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.
|
||||
|
||||
// String methods
|
||||
String.charAt(index) // Returns the character at the specified index in a string.
|
||||
String.indexOf(character) // Returns the index of the first occurrence of a specified value in a string.
|
||||
String.substring(starting_index, ending_index) // Returns a new string that is a subset of the original string.
|
||||
String.substring(starting_index) // Returns a substring from starting index to last index of string.
|
||||
@@ -0,0 +1,604 @@
|
||||
<?php
|
||||
|
||||
// Exit the file, string inside get's echo'ed
|
||||
die("This file is not meant to be ran. ¯\_(ツ)_/¯");
|
||||
exit("This file is not meant 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 occurrence
|
||||
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 whitespace 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.*/
|
||||
@@ -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 occurred 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.
|
||||