3 Commits

Author SHA1 Message Date
Pranshu Chittora b9a15ece18 Merge 26ae159967 into 10872e02d1 2024-06-20 02:29:26 +00:00
pranshuchittora 26ae159967 Merge pull request #1 from pranshuchittora/pranshuchittora-1
Specified module importing path clearly
2018-07-29 10:22:58 +05:30
pranshuchittora a8a8b56ad7 Specified module importing path clearly 2018-07-29 10:22:08 +05:30
17 changed files with 191 additions and 1884 deletions
+20 -46
View File
@@ -1,29 +1,17 @@
<div align="center">
[![AWESOME CHEATSHEETS LOGO](_design/cover_github@2x.png)](https://lecoupa.github.io/awesome-cheatsheets/) [![AWESOME CHEATSHEETS LOGO](_design/cover_github@2x.png)](https://lecoupa.github.io/awesome-cheatsheets/)
<a href="https://trendshift.io/repositories/5584" target="_blank">
<img src="https://trendshift.io/api/badge/repositories/5584" alt="LeCoupa%2Fawesome-cheatsheets | Trendshift" width="250" height="55"/>
</a>
[![Awesome](https://awesome.re/badge.svg)](https://awesome.re) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/LeCoupa/awesome-cheatsheets/blob/master/LICENSE) [![Awesome](https://awesome.re/badge.svg)](https://awesome.re) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/LeCoupa/awesome-cheatsheets/blob/master/LICENSE)
**WEBSITE DIRECTORY**: [Available here](https://lecoupa.github.io/awesome-cheatsheets/) **WEBSITE DIRECTORY**: [Available here](https://lecoupa.github.io/awesome-cheatsheets/).
> 📚 Awesome cheatsheets for popular programming languages, frameworks and development tools. They include everything you should know in one single file. > 📚 Awesome cheatsheets for popular programming languages, frameworks and development tools. They include everything you should know in one single file.
</div>
---
## 🤔 Why Awesome-Cheatsheets? ## 🤔 Why Awesome-Cheatsheets?
I usually make a cheat sheet when I want to improve my skills in a programming language, a framework or a development tool. [I started doing these kinds of things a long time ago on Gist](https://gist.github.com/LeCoupa). To better keep track of the history and to let people contribute, I re-organized all of them into this single repository. Most of the content is coming from official documentation and some books I have read. I usually make a cheat sheet when I want to improve my skills in a programming language, a framework or a development tool. [I started doing these kinds of things a long time ago on Gist](https://gist.github.com/LeCoupa). To better keep track of the history and to let people contribute, I re-organized all of them into this single repository. Most of the content is coming from official documentation and some books I have read.
Feel free to take a look. You might learn new things. They have been designed to provide a quick way to assess your knowledge and to save you time. 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 ## 📚 Table of Contents
### 📃 Languages ### 📃 Languages
@@ -32,48 +20,46 @@ Feel free to take a look. You might learn new things. They have been designed to
<summary>View cheatsheets</summary> <summary>View cheatsheets</summary>
#### Command line interface #### Command line interface
- [Bash](languages/bash.sh) - [Bash](languages/bash.sh)
#### Imperative #### Imperative
- [C](languages/C.txt) - [C](languages/C.txt)
- [C#](languages/C%23.txt) - [C#](languages/C%23.txt)
- [Go](languages/golang.md) - [Go](languages/golang.md)
- [Java](languages/java.md) - [Java](languages/java.md)
- [PHP](languages/php.php) - [PHP](languages/php.php)
- [Python](languages/python.md) - [Python](languages/python.md)
- [XML](languages/XML.md)
#### Functional #### Functional
- [JavaScript](languages/javascript.js) - [JavaScript](languages/javascript.js)
- [Typescript](languages/typescript.md)
</details> </details>
---
### 📦 Backend ### 📦 Backend
<details> <details>
<summary>View cheatsheets</summary> <summary>View cheatsheets</summary>
#### PHP #### PHP
- [Laravel](backend/laravel.php) - [Laravel](backend/laravel.php)
#### Python #### Python
- [Django](backend/django.py) - [Django](backend/django.py)
#### JavaScript #### Javascript
- [Adonis.js](backend/adonis.js) - [Adonis.js](backend/adonis.js)
- [Express.js](backend/express.js) - [Express.js](backend/express.js)
- [Feathers.js](backend/feathers.js) - [Feathers.js](backend/feathers.js)
- [Moleculer](backend/moleculer.js) - [Moleculer](backend/moleculer.js)
- [Node.js](backend/node.js) - [Node.js](backend/node.js)
- [Sails.js](backend/sails.js) - [Sails.js](backend/sails.js)
</details>
</details>
---
### 🌐 Frontend ### 🌐 Frontend
@@ -81,20 +67,19 @@ Feel free to take a look. You might learn new things. They have been designed to
<summary>View cheatsheets</summary> <summary>View cheatsheets</summary>
#### Basics #### Basics
- [HTML5](frontend/html5.html) - [HTML5](frontend/html5.html)
- [CSS3](frontend/css3.css) - [CSS3](frontend/css3.css)
- [Typescript](frontend/typescript.ts)
#### Frameworks #### Frameworks
- [React.js](frontend/react.js) - [React.js](frontend/react.js)
- [Vue.js](frontend/vue.js) - [Vue.js](frontend/vue.js)
- [Tailwind.css](frontend/tailwind.css) - [Tailwind.css](frontend/tailwind.css)
- [Ember.js](frontend/ember.js) - [Ember.js](frontend/ember.js)
- [Angular (2+)](frontend/angular.js) - [Angular (2+)](frontend/angular.js)
- [AngularJS](frontend/angularjs.js) - [AngularJS](frontend/angularjs.js)
</details> </details>
---
### 🗃️ Databases ### 🗃️ Databases
@@ -102,15 +87,13 @@ Feel free to take a look. You might learn new things. They have been designed to
<summary>View cheatsheets</summary> <summary>View cheatsheets</summary>
#### SQL #### SQL
- [MySQL](databases/mysql.sh) - [MySQL](databases/mysql.sh)
#### NoSQL #### NoSQL
- [MongoDB](databases/mongodb.sh)
- [Redis](databases/redis.sh) - [Redis](databases/redis.sh)
</details>
</details>
---
### 🔧 Tools ### 🔧 Tools
@@ -118,6 +101,7 @@ Feel free to take a look. You might learn new things. They have been designed to
<summary>View cheatsheets</summary> <summary>View cheatsheets</summary>
#### Development #### Development
- [cURL](tools/curl.sh) - [cURL](tools/curl.sh)
- [Drush](tools/drush.sh) - [Drush](tools/drush.sh)
- [Elasticsearch](tools/elasticsearch.js) - [Elasticsearch](tools/elasticsearch.js)
@@ -130,35 +114,25 @@ Feel free to take a look. You might learn new things. They have been designed to
- [Xcode](tools/xcode.txt) - [Xcode](tools/xcode.txt)
#### Infrastructure #### Infrastructure
- [AWS CLI](tools/aws.sh) - [AWS CLI](tools/aws.sh)
- [Docker](tools/docker.sh) - [Docker](tools/docker.sh)
- [GCP CLI](tools/gcp.md)
- [Heroku CLI](tools/heroku.sh) - [Heroku CLI](tools/heroku.sh)
- [Kubernetes](tools/kubernetes.md) - [Kubernetes](tools/kubernetes.md)
- [macOS](tools/macos.sh)
- [Nanobox Boxfile](tools/nanobox_boxfile.yml) - [Nanobox Boxfile](tools/nanobox_boxfile.yml)
- [Nanobox CLI](tools/nanobox_cli.sh) - [Nanobox CLI](tools/nanobox_cli.sh)
- [Nginx](tools/nginx.sh) - [Nginx](tools/nginx.sh)
- [PM2](tools/pm2.sh) - [PM2](tools/pm2.sh)
- [Ubuntu](tools/ubuntu.sh) - [Ubuntu](tools/ubuntu.sh)
- [Firebase CLI](tools/firebase_cli.md) - [Firebase CLI](tools/firebase_cli.md)
</details>
</details>
---
## 🙌🏼 How to Contribute? ## 🙌🏼 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. 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 ## 👩‍💻👨‍💻 Our valuable Contributors
<div align="center"> <p align="center"><a href="https://github.com/LeCoupa/awesome-cheatsheets/graphs/contributors">
<a href="https://github.com/LeCoupa/awesome-cheatsheets/graphs/contributors">
<img src="https://contributors-img.web.app/image?repo=LeCoupa/awesome-cheatsheets" /> <img src="https://contributors-img.web.app/image?repo=LeCoupa/awesome-cheatsheets" />
</a> </a></p>
</div>
+1 -1
View File
@@ -73,7 +73,7 @@ ref(); // If you had previously unref()d a timer you can call ref() to explic
* http://nodejs.org/api/modules.html * http://nodejs.org/api/modules.html
* ******************************************************************************************* */ * ******************************************************************************************* */
// require() accepts a relative path of the given module w.r.t. the file you are importing it in.
var module = require('./module.js'); // Loads the module module.js in the same directory. 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.require('./another_module.js'); // load another_module as if require() was called from the module itself.
-96
View File
@@ -16,99 +16,3 @@ GRANT ALL PRIVILEGES ON prospectwith.* TO 'power'@'localhost' WITH GRANT OPTION;
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password'; # Create user 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 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
# *****************************************************************************
# Altering Table Structure
# *****************************************************************************
ALTER TABLE table_name ADD COLUMN column_name datatype; # Add a new column to an existing table
ALTER TABLE table_name MODIFY COLUMN column_name datatype; # Change the data type of a column
ALTER TABLE table_name RENAME COLUMN old_name TO new_name; # Rename a column (MySQL 8.0+)
ALTER TABLE table_name DROP COLUMN column_name; # Remove a column from a table
ALTER TABLE old_table_name RENAME TO new_table_name; # Rename an entire table
# *****************************************************************************
# Indexes (Performance Tuning)
# *****************************************************************************
CREATE INDEX idx_name ON table_name (column_name); # Create a standard index to speed up queries
CREATE UNIQUE INDEX idx_name ON table_name (column_name); # Create a unique index (no duplicate values)
SHOW INDEX FROM table_name; # List all indexes on a specific table
DROP INDEX idx_name ON table_name; # Remove an index from a table
EXPLAIN SELECT * FROM table_name WHERE condition; # Analyze how MySQL executes a query (Check index usage)
# *****************************************************************************
# Transactions (Data Integrity)
# *****************************************************************************
START TRANSACTION; # Begin a new transaction
COMMIT; # Save all changes made during the transaction
ROLLBACK; # Undo all changes if an error occurs before commit
SET AUTOCOMMIT = 0; # Disable automatic commits for the current session
SET AUTOCOMMIT = 1; # Re-enable automatic commits after finishing manual transactions
+47 -71
View File
@@ -43,14 +43,11 @@
.hidden /* display: none; */ .hidden /* display: none; */
.block /* display: block; */ .block /* display: block; */
.flow-root /* display: flow-root; */
.inline-block /* display: inline-block; */ .inline-block /* display: inline-block; */
.inline /* display: inline; */ .inline /* display: inline; */
.flex /* display: flex; */ .flex /* display: flex; */
.inline-flex /* display: inline-flex; */ .inline-flex /* display: inline-flex; */
.grid /* display: grid; */ .grid /* display: grid; */
.inline-grid /* display: inline-grid; */
.contents /* display: contents; */
.table /* display: table; */ .table /* display: table; */
.table-caption /* display: table-caption; */ .table-caption /* display: table-caption; */
.table-cell /* display: table-cell; */ .table-cell /* display: table-cell; */
@@ -71,6 +68,7 @@
.float-right /* float: right; */ .float-right /* float: right; */
.float-left /* float: left; */ .float-left /* float: left; */
.float-none /* float: none; */ .float-none /* float: none; */
.clearfix /* &::after { content: ""; display: table; clear: both; } */
/* /*
* Clear * Clear
@@ -132,6 +130,8 @@
.overflow-y-visible /* overflow-y: visible; */ .overflow-y-visible /* overflow-y: visible; */
.overflow-x-scroll /* overflow-x: scroll; */ .overflow-x-scroll /* overflow-x: scroll; */
.overflow-y-scroll /* overflow-y: scroll; */ .overflow-y-scroll /* overflow-y: scroll; */
.scrolling-touch /* -webkit-overflow-scrolling: touch; */
.scrolling-auto /* -webkit-overflow-scrolling: auto; */
/* /*
* Position * Position
@@ -219,7 +219,7 @@
* By default, only responsive variants are generated for flex-wrap utilities. * By default, only responsive variants are generated for flex-wrap utilities.
*/ */
.flex-nowrap /* flex-wrap: nowrap; */ .flex-no-wrap /* flex-wrap: nowrap; */
.flex-wrap /* flex-wrap: wrap; */ .flex-wrap /* flex-wrap: wrap; */
.flex-wrap-reverse /* flex-wrap: wrap-reverse; */ .flex-wrap-reverse /* flex-wrap: wrap-reverse; */
@@ -478,44 +478,44 @@
.gap-56 /* gap: 14rem; */ .gap-56 /* gap: 14rem; */
.gap-64 /* gap: 16rem; */ .gap-64 /* gap: 16rem; */
.gap-px /* gap: 1px; */ .gap-px /* gap: 1px; */
.gap-y-0 /* row-gap: 0; */ .row-gap-0 /* row-gap: 0; */
.gap-y-1 /* row-gap: 0.25rem; */ .row-gap-1 /* row-gap: 0.25rem; */
.gap-y-2 /* row-gap: 0.5rem; */ .row-gap-2 /* row-gap: 0.5rem; */
.gap-y-3 /* row-gap: 0.75rem; */ .row-gap-3 /* row-gap: 0.75rem; */
.gap-y-4 /* row-gap: 1rem; */ .row-gap-4 /* row-gap: 1rem; */
.gap-y-5 /* row-gap: 1.25rem; */ .row-gap-5 /* row-gap: 1.25rem; */
.gap-y-6 /* row-gap: 1.5rem; */ .row-gap-6 /* row-gap: 1.5rem; */
.gap-y-8 /* row-gap: 2rem; */ .row-gap-8 /* row-gap: 2rem; */
.gap-y-10 /* row-gap: 2.5rem; */ .row-gap-10 /* row-gap: 2.5rem; */
.gap-y-12 /* row-gap: 3rem; */ .row-gap-12 /* row-gap: 3rem; */
.gap-y-16 /* row-gap: 4rem; */ .row-gap-16 /* row-gap: 4rem; */
.gap-y-20 /* row-gap: 5rem; */ .row-gap-20 /* row-gap: 5rem; */
.gap-y-24 /* row-gap: 6rem; */ .row-gap-24 /* row-gap: 6rem; */
.gap-y-32 /* row-gap: 8rem; */ .row-gap-32 /* row-gap: 8rem; */
.gap-y-40 /* row-gap: 10rem; */ .row-gap-40 /* row-gap: 10rem; */
.gap-y-48 /* row-gap: 12rem; */ .row-gap-48 /* row-gap: 12rem; */
.gap-y-56 /* row-gap: 14rem; */ .row-gap-56 /* row-gap: 14rem; */
.gap-y-64 /* row-gap: 16rem; */ .row-gap-64 /* row-gap: 16rem; */
.gap-y-px /* row-gap: 1px; */ .row-gap-px /* row-gap: 1px; */
.gap-x-0 /* column-gap: 0; */ .col-gap-0 /* column-gap: 0; */
.gap-x-1 /* column-gap: 0.25rem; */ .col-gap-1 /* column-gap: 0.25rem; */
.gap-x-2 /* column-gap: 0.5rem; */ .col-gap-2 /* column-gap: 0.5rem; */
.gap-x-3 /* column-gap: 0.75rem; */ .col-gap-3 /* column-gap: 0.75rem; */
.gap-x-4 /* column-gap: 1rem; */ .col-gap-4 /* column-gap: 1rem; */
.gap-x-5 /* column-gap: 1.25rem; */ .col-gap-5 /* column-gap: 1.25rem; */
.gap-x-6 /* column-gap: 1.5rem; */ .col-gap-6 /* column-gap: 1.5rem; */
.gap-x-8 /* column-gap: 2rem; */ .col-gap-8 /* column-gap: 2rem; */
.gap-x-10 /* column-gap: 2.5rem; */ .col-gap-10 /* column-gap: 2.5rem; */
.gap-x-12 /* column-gap: 3rem; */ .col-gap-12 /* column-gap: 3rem; */
.gap-x-16 /* column-gap: 4rem; */ .col-gap-16 /* column-gap: 4rem; */
.gap-x-20 /* column-gap: 5rem; */ .col-gap-20 /* column-gap: 5rem; */
.gap-x-24 /* column-gap: 6rem; */ .col-gap-24 /* column-gap: 6rem; */
.gap-x-32 /* column-gap: 8rem; */ .col-gap-32 /* column-gap: 8rem; */
.gap-x-40 /* column-gap: 10rem; */ .col-gap-40 /* column-gap: 10rem; */
.gap-x-48 /* column-gap: 12rem; */ .col-gap-48 /* column-gap: 12rem; */
.gap-x-56 /* column-gap: 14rem; */ .col-gap-56 /* column-gap: 14rem; */
.gap-x-64 /* column-gap: 16rem; */ .col-gap-64 /* column-gap: 16rem; */
.gap-x-px /* column-gap: 1px; */ .col-gap-px /* column-gap: 1px; */
/* /*
* Grid Auto Flow * Grid Auto Flow
@@ -1153,8 +1153,8 @@
* By default, only responsive, hover and focus variants are generated for font weight utilities. * By default, only responsive, hover and focus variants are generated for font weight utilities.
*/ */
.font-thin /* font-weight: 100; */ .font-hairline /* font-weight: 100; */
.font-extralight /* font-weight: 200; */ .font-thin /* font-weight: 200; */
.font-light /* font-weight: 300; */ .font-light /* font-weight: 300; */
.font-normal /* font-weight: 400; */ .font-normal /* font-weight: 400; */
.font-medium /* font-weight: 500; */ .font-medium /* font-weight: 500; */
@@ -1479,7 +1479,7 @@
*/ */
.whitespace-normal /* white-space: normal; */ .whitespace-normal /* white-space: normal; */
.whitespace-nowrap /* white-space: nowrap; */ .whitespace-no-wrap /* white-space: nowrap; */
.whitespace-pre /* white-space: pre; */ .whitespace-pre /* white-space: pre; */
.whitespace-pre-line /* white-space: pre-line; */ .whitespace-pre-line /* white-space: pre-line; */
.whitespace-pre-wrap /* white-space: pre-wrap; */ .whitespace-pre-wrap /* white-space: pre-wrap; */
@@ -1902,6 +1902,7 @@
* By default, only responsive, hover and focus variants are generated for box shadow utilities. * By default, only responsive, hover and focus variants are generated for box shadow utilities.
*/ */
.shadow-xs /* box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05); */
.shadow-sm /* box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); */ .shadow-sm /* box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05); */
.shadow /* box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); */ .shadow /* box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); */
.shadow-md /* box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); */ .shadow-md /* box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); */
@@ -1909,34 +1910,9 @@
.shadow-xl /* box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); */ .shadow-xl /* box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); */
.shadow-2xl /* box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); */ .shadow-2xl /* box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25); */
.shadow-inner /* box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06); */ .shadow-inner /* box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.06); */
.shadow-outline /* box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.5); */
.shadow-none /* box-shadow: none; */ .shadow-none /* box-shadow: none; */
/*
* RING
* --------------------
* Utilities for creating outline rings with box-shadows.
* Replaced the old .shadow-outline utility.
*/
.ring-0 /* box-shadow: 0 0 0 0px; */
.ring-1 /* box-shadow: 0 0 0 1px; */
.ring-2 /* box-shadow: 0 0 0 2px; */
.ring-4 /* box-shadow: 0 0 0 4px; */
.ring-8 /* box-shadow: 0 0 0 8px; */
.ring /* box-shadow: 0 0 0 3px; */
.ring-inset /* --ring-inset: inset; */
.ring-transparent /* --ring-color: transparent; */
.ring-black /* --ring-color: #000; */
.ring-white /* --ring-color: #fff; */
.ring-current /* --ring-color: currentColor; */
.ring-offset-0 /* --ring-offset-width: 0px; */
.ring-offset-1 /* --ring-offset-width: 1px; */
.ring-offset-2 /* --ring-offset-width: 2px; */
.ring-offset-4 /* --ring-offset-width: 4px; */
.ring-offset-8 /* --ring-offset-width: 8px; */
/* /*
* OPACITY * OPACITY
* -------------------- * --------------------
-670
View File
@@ -1,670 +0,0 @@
/****************************
* 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
*/
+35 -35
View File
@@ -3,7 +3,7 @@ CHEATSHEET C#
1. Data Types 1. Data Types
Primitive Size Example Primitive Size Example
String 2 bytes/char s = "reference"; String 2 bytes/char s = "reference";
bool b = true; bool b = true;
char 2 bytes ch = 'a'; char 2 bytes ch = 'a';
@@ -16,20 +16,20 @@ CHEATSHEET C#
decimal 16 bytes val = 70.0M; decimal 16 bytes val = 70.0M;
2. Arrays 2. Arrays
2.1 Declaration 2.1 Declaration
//Initiliazed using a list defined with curly braces //Initiliazed using a list defined with curly braces
int[] nameArray = {100, 101, 102}; int[] nameArray = {100, 101, 102};
//Define an empty array //Define an empty array
int[] nameArray = new int[3]; // 3 rows and 2 columns int[] nameArray = new int[3]; // 3 rows and 2 columns
//To access a specific item in the array //To access a specific item in the array
int[] nameArray = new int[10]; int[] nameArray = new int[10];
int firstNumber = nameArray[0]; int firstNumber = nameArray[0];
nameArray[1] = 20; nameArray[1] = 20;
//Multidimensional arrays //Multidimensional arrays
int [,] matrix = new int [2,2] int [,] matrix = new int [2,2]
matrix[0,0] = 1; matrix[0,0] = 1;
@@ -40,26 +40,26 @@ CHEATSHEET C#
int[,] predefinedMatrix = new int[2,2] { { 1, 2 }, { 3, 4 } }; int[,] predefinedMatrix = new int[2,2] { { 1, 2 }, { 3, 4 } };
2.2 Array Operations 2.2 Array Operations
//Sort ascending //Sort ascending
Array.Sort(nameArray); Array.Sort(nameArray);
//Sort begins at element 6 and sorts 20 elements //Sort begins at element 6 and sorts 20 elements
Array.Sort(nameArray,6,20); Array.Sort(nameArray,6,20);
//Use 1 array as a key & sort 2 arrays //Use 1 array as a key & sort 2 arrays
string[] values = {"Juan", "Victor", "Elena"}; string[] values = {"Juan", "Victor", "Elena"};
string[] keys = {"Jimenez", "Martin", "Ortiz"}; string[] keys = {"Jimenez", "Martin", "Ortiz"};
Array.Sort(keys, values); Array.Sort(keys, values);
//Clear elements in array (array, first element, # elements) //Clear elements in array (array, first element, # elements)
Array.Clear(nameArray, 0, nameArray.Length); Array.Clear(nameArray, 0, nameArray.Length);
//Copy elements from one array to another //Copy elements from one array to another
Array.Copy(scr, target, numOfElements); Array.Copy(scr, target, numOfElements);
3. String Operations 3. String Operations
//To concatenate between strings, use the plus operator: //To concatenate between strings, use the plus operator:
string firstName = "Erin"; string firstName = "Erin";
string lastName = "Roger"; string lastName = "Roger";
@@ -68,27 +68,27 @@ CHEATSHEET C#
//To add one string to another, use the += operator: //To add one string to another, use the += operator:
string secondLastName = "Green"; string secondLastName = "Green";
string fullName += secondLastName; string fullName += secondLastName;
//ToString function //ToString function
//It converts an object to its string representation so that it is suitable for display //It converts an object to its string representation so that it is suitable for display
Object.ToString(); Object.ToString();
//String formatting //String formatting
//Each additional argument to the function can be referred to in the string using the brackets operator with the index number. //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); String.Format(String format, Object arg0);
format - A composite format string that includes one or more format items format - A composite format string that includes one or more format items
arg0 - The first or only object to format arg0 - The first or only object to format
//Substring //Substring
//Returns a part of the string, beginning from the index specified as the argument. Substring also accepts a maximum length for the 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);
String.Substring(beginAt, maximum); String.Substring(beginAt, maximum);
//Replace //Replace
string newStr = oldStr.Replace("old","new"); string newStr = oldStr.Replace("old","new");
//IndexOf //IndexOf
//Finds the first occurrence of a string in a larger string //Finds the first ocurrence of a string in a larger string
//Returns -1 if the string is not found //Returns -1 if the string is not found
String.IndexOf(val, start, num) String.IndexOf(val, start, num)
val - string to search for val - string to search for
@@ -102,7 +102,7 @@ CHEATSHEET C#
String.Split(Char[]); String.Split(Char[]);
//ToCharArray //ToCharArray
//Places selected characters in a string in a char array //Places selected characteres in a string in a char array
String str = "AaBbCcDd"; String str = "AaBbCcDd";
//create array of 8 vowels //create array of 8 vowels
var chars = str.ToCharArray(); var chars = str.ToCharArray();
@@ -132,11 +132,11 @@ CHEATSHEET C#
DateTime nextYear = DateTime.AddYears(1); DateTime nextYear = DateTime.AddYears(1);
6. TimeSpan 6. TimeSpan
6.1 TimeSpan Constructor 6.1 TimeSpan Constructor
TimeSpan(hour, minute, sec) TimpeSpan(hour, minute, sec)
TimeSpan timeS = new TimeSpan(10, 14, 50); TimeSpan timeS = new TimeSpan(10, 14, 50);
TimeSpan timeS_Hours = TimeSpan.FromDays(3640); TimeSpan timeS_Hours = TimeSpan.FromDays(3640);
@@ -144,8 +144,8 @@ CHEATSHEET C#
Format item syntax: {index[,alignment][:format string]} Format item syntax: {index[,alignment][:format string]}
index - Specifies element in list of values to which format is applied index - Specifies element in list of values to which format is applied
alignment - Indicates minimum width (in characters) to display value aligment - Indicates minimun width (in characters) to display value
format string - Contains the code which specifies the format of the displayed value format string - Contains the code which specififes the format of the displayed value
7.1 Numeric 7.1 Numeric
@@ -168,7 +168,7 @@ CHEATSHEET C#
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 -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: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) 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 8.1 Compiler Options Listed
Option Purpose Option Purpose
@@ -260,21 +260,21 @@ CHEATSHEET C#
10. Loop 10. Loop
10.1 While 10.1 While
while (condition) {body} while (condition) {body}
10.2 Do while 10.2 Do while
do {body} while condition; do {body} while condition;
10.3 For 10.3 For
for (initializer; termination condition; iteration;) { for (initializer; termination condition; iteration;) {
//statements //statements
} }
10.4 For each 10.4 For each
foreach (type identifier in collection) { foreach (type identifier in collection) {
//statements //statements
} }
@@ -293,7 +293,7 @@ CHEATSHEET C#
[access modifier] className (parameters) [:initializer] [access modifier] className (parameters) [:initializer]
initializer -base calls constructor in base class. initializer -base calls constructor in base class.
this calls constructor within class. this calls constuctor within class.
public class nameClass : Initializer { public class nameClass : Initializer {
public className(dataType param1 , dataType param2, ...) : base(param1, param2) public className(dataType param1 , dataType param2, ...) : base(param1, param2)
@@ -313,8 +313,8 @@ CHEATSHEET C#
abstract must be implemented by subclass abstract must be implemented by subclass
Passing parameters: Passing parameters:
1. By default, parameters are passed by value 1. By default, parametres are passed by value
2. Passing by reference: ref, in and out modifiers 2. Passing by reference: ref, in and out modifers
To pass a parameter by reference with the intent of changing the value, use the ref, or out keyword. To pass by reference with the intent of avoiding copying but not changing the value, use the in modifier 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
@@ -331,9 +331,9 @@ CHEATSHEET C#
12. Struct 12. Struct
12.1 Defining a structure 12.1 Defining a structure
[attribute][modifier] struct name [:interfaces] { struct-body } [attribute][modifier] struct name [:interfaces] { struct-body }
12.2 Class vs Structure 12.2 Class vs Structure
-> Classes are reference types and structs are value types -> Classes are reference types and structs are value types
@@ -378,7 +378,7 @@ CHEATSHEET C#
//To declare an event inside a class, first a delegate type for the event must be declared. //To declare an event inside a class, first a delegate type for the event must be declared.
public delegate string MyDelegate(string str); public delegate string MyDelegate(string str);
//The event itself is declared by using the event keyword //The event itself is declared by using the event keyword
event MyDelegate MyEvent; event MyDelegate MyEvent;
+6 -6
View File
@@ -31,11 +31,11 @@ Preprocessor directives:
Create and execute a program Create and execute a program
In Linux systems: In Linux systems:
1. Open up a terminal 1. Open up a terminal
2. Create the program: nano nameProgram.c 2. Create the program: nano nameProgram.c
3. Write the program and save it 3. Write the program and save it
4. gcc -o nameExecutable nameProgram.c 4. gcc -o nameExecutable nameProgram.c
32 Reserved words 32 Reserved words
@@ -106,8 +106,8 @@ Operators
( ) grouping parenthesis, function call ( ) grouping parenthesis, function call
[ ] array indexing, also [ ][ ] etc. [ ] array indexing, also [ ][ ] etc.
-> selector, structure pointer -> selector, structure pointer
. select structure element . select structure element
! relational not, complement, ! a yields true or false ! relational not, complement, ! a yields true or false
~ bitwise not, ones complement, ~ a ~ bitwise not, ones complement, ~ a
++ increment, pre or post to a variable ++ increment, pre or post to a variable
@@ -153,7 +153,7 @@ Operators
Operator precedence Operator precedence
More precedence More precedence
LR ( ) [ ] -> . x++ x-- LR ( ) [ ] -> . x++ x--
@@ -203,7 +203,7 @@ Function definition
type function_name(int a, float b, const char * ch,...) { function_body } type function_name(int a, float b, const char * ch,...) { function_body }
/* only parameters passed by address can are modified*/ /* only parameters passed by address can are modified*/
/* in the calling function, local copy can be modified*/ /* in the calling function, local copy can be modified*/
+1 -1
View File
@@ -11,7 +11,7 @@ XML uses a DTD to describe the data.
So the XML is a **Complement** to HTML. So the XML is a **Complement** to HTML.
* HTML: is used to format and display the same data. * 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. 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. Because of this, with XML, there is a full separation between data and presentation.
+14 -14
View File
@@ -46,7 +46,7 @@ CTRL+X then ( # start recording a keyboard macro
CTRL+X then ) # finish recording keyboard macro CTRL+X then ) # finish recording keyboard macro
CTRL+X then E # recall last recorded 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+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 CTRL+A then D # logout from screen but don't kill it, if any command exist, it will continue
BACKSPACE # deletes one character backward BACKSPACE # deletes one character backward
DELETE # deletes one character under cursor DELETE # deletes one character under cursor
@@ -94,7 +94,7 @@ cat <filename> # displays file raw content (will not be interpret
cat -n <filename> # shows number of lines cat -n <filename> # shows number of lines
nl <file.sh> # shows number of lines in file nl <file.sh> # shows number of lines in file
cat filename1 > filename2 # Copy filename1 to filename2 cat filename1 > filename2 # Copy filename1 to filename2
cat filename1 >> filename2 # merge two files texts together 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) 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) 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) head <filename> # outputs the first lines of file (default: 10 lines)
@@ -203,14 +203,14 @@ echo $$ # prints process ID of the current shell
echo $! # prints process ID of the most recently invoked background job echo $! # prints process ID of the most recently invoked background job
echo $? # displays the exit status of the last command echo $? # displays the exit status of the last command
read <varname> # reads a string from the input and assigns it to a variable 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 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) column -t <filename> # display info in pretty columns (often used with pipe)
let <varname> = <equation> # performs mathematical calculation using operators like +, -, *, /, % let <varname> = <equation> # performs mathematical calculation using operators like +, -, *, /, %
export VARNAME=value # defines an environment variable (will be available in subprocesses) export VARNAME=value # defines an environment variable (will be available in subprocesses)
export -f <funcname> # Exports function 'funcname' export -f <funcname> # Exports function 'funcname'
export var1="var1 value" # Export and assign in the same statement export var1="var1 value" # Export and assign in the same statement
export <varname> # Copy Bash variable export <varname> # Copy Bash variable
declare -x <varname> # Copy Bash variable declare -x <varname> # Copy Bash variable
array[0]=valA # how to define an array array[0]=valA # how to define an array
array[1]=valB array[1]=valB
@@ -507,9 +507,9 @@ function returntrap {
trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing
############################################################################## ##############################################################################
# COLORS AND BACKGROUNDS # COLORS AND BACKGROUNDS
############################################################################## ##############################################################################
# note: \e or \x1B also work instead of \033 # note: \e or \x1B also work instead of \033
# Reset # Reset
Color_Off='\033[0m' # Text Reset Color_Off='\033[0m' # Text Reset
@@ -524,14 +524,14 @@ Cyan='\033[0;36m' # Cyan
White='\033[0;97m' # White White='\033[0;97m' # White
# Additional colors # Additional colors
LGrey='\033[0;37m' # Light Gray LGrey='\033[0;37m' # Ligth Gray
DGrey='\033[0;90m' # Dark Gray DGrey='\033[0;90m' # Dark Gray
LRed='\033[0;91m' # Light Red LRed='\033[0;91m' # Ligth Red
LGreen='\033[0;92m' # Light Green LGreen='\033[0;92m' # Ligth Green
LYellow='\033[0;93m'# Light Yellow LYellow='\033[0;93m'# Ligth Yellow
LBlue='\033[0;94m' # Light Blue LBlue='\033[0;94m' # Ligth Blue
LPurple='\033[0;95m'# Light Purple LPurple='\033[0;95m'# Light Purple
LCyan='\033[0;96m' # Light Cyan LCyan='\033[0;96m' # Ligth Cyan
# Bold # Bold
@@ -566,6 +566,6 @@ On_White='\033[47m' # White
# Example of usage # Example of usage
echo -e "${Green}This is GREEN text${Color_Off} and normal text" 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}" echo -e "${Red}${On_White}This is Red test on White background${Color_Off}"
# option -e is mandatory, it enable interpretation of backslash escapes # option -e is mandatory, it enable interpretation of backslash escapes
printf "${Red} This is red \n" printf "${Red} This is red \n"
+7 -7
View File
@@ -397,8 +397,8 @@ d, t := doubleAndTriple(5)
_, t := doubleAndTriple(3) _, t := doubleAndTriple(3)
// t = 9 // t = 9
// Functions can defer commands. Deferred commands are // Functions can defer commands. Defered commands are
// ran in a stack order after the execution and // runned in a stack order after the execution and
// returning of a function // returning of a function
var aux = 0 var aux = 0
@@ -488,7 +488,7 @@ person3.Age // 0
## Maps ## Maps
Maps are data structures that holds values assigned to a key. Maps are data structures that holds values assigneds to a key.
```go ```go
// Declaring a map // Declaring a map
@@ -508,7 +508,7 @@ newYork // "EUA"
// Delete // Delete
delete(cities, "NY") delete(cities, "NY")
// Check if a key is set // Check if a key is setted
value, ok := cities["NY"] value, ok := cities["NY"]
ok // false ok // false
value // "" value // ""
@@ -600,7 +600,7 @@ Go doesn't support `throw`, `try`, `catch` and other common error handling struc
```go ```go
import "errors" import "errors"
// Function that contain a logic that can cause a possible exception flow // Function that contain a logic that can cause a possible exception flow
func firstLetter(text string) (string, error) { func firstLetter(text string) (string, error) {
if len(text) < 1 { if len(text) < 1 {
return nil, errors.New("Parameter text is empty") return nil, errors.New("Parameter text is empty")
@@ -632,7 +632,7 @@ func Sum(x, y int) int {
} }
// main_test.go // main_test.go
import ( import (
"testing" "testing"
"reflect" "reflect"
) )
@@ -676,7 +676,7 @@ func main() {
blocking2: 0 blocking2: 0
blocking2: 1 blocking2: 1
blocking2: 2 blocking2: 2
done done
*/ */
// Go routines are a function (either declared previously or anonymous) called with the keyword go // Go routines are a function (either declared previously or anonymous) called with the keyword go
+14 -14
View File
@@ -204,7 +204,7 @@ a \|= b; //a is the variable name; b is the variable name; this expression is an
} }
``` ```
**Example:** **Example:**
```java ```java
for (int i = 0; i <= n; i++) { for (int i = 0; i <= n; i++) {
System.out.println(i); System.out.println(i);
} }
@@ -254,10 +254,10 @@ for(dataType item : array) {
**Example:** **Example:**
```java ```java
int i=1; int i=1;
do{ do{
System.out.println(i); System.out.println(i);
i++; i++;
}while(i<=10); }while(i<=10);
``` ```
@@ -308,7 +308,7 @@ for(dataType item : array) {
//Declare a variable, object name //Declare a variable, object name
String s; String s;
//Invoke a constructor to create an object //Invoke a contructor to create an object
s = new String ("Hello World"); s = new String ("Hello World");
//Invoke an instance method that operates on the object's value //Invoke an instance method that operates on the object's value
@@ -361,13 +361,13 @@ class MyClass {
// four methods // four methods
public void setCadence(int newValue) { public void setCadence(int newValue) {
cadence = newValue; cadence = newValue;
} }
public void setGear(int newValue) { public void setGear(int newValue) {
gear = newValue; gear = newValue;
} }
public void applyBrake(int decrement) { public void applyBrake(int decrement) {
speed -= decrement; speed -= decrement;
} }
public void speedUp(int increment) { public void speedUp(int increment) {
speed += increment; speed += increment;
} }
@@ -531,13 +531,13 @@ class MyClass extends MySuperClass implements YourInterface {
```java ```java
interface print{ interface print{
void printPaper(); void printPaper();
} }
public class A4 implements print{ public class A4 implements print{
public void printPaper(){ public void printPaper(){
System.out.println("A4 Page Printed. "); System.out.println("A4 Page Printed. ");
} }
} }
``` ```
-6
View File
@@ -95,9 +95,3 @@ arr.reduce(callback[, initialValue]) // Apply a function against
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.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.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. 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.
+7 -7
View File
@@ -1,8 +1,8 @@
<?php <?php
// Exit the file, string inside get's echo'ed // Exit the file, string inside get's echo'ed
die("This file is not meant to be ran. ¯\_(ツ)_/¯"); die("This file is not ment to be ran. ¯\_(ツ)_/¯");
exit("This file is not meant to be ran. ¯\_(ツ)_/¯"); exit("This file is not ment to be ran. ¯\_(ツ)_/¯");
/** /**
* Printing * Printing
@@ -17,7 +17,7 @@ var_dump($arr); // Print anything, with type hints for any value and sizes
$string = 'Awesome cheatsheets'; $string = 'Awesome cheatsheets';
str_contains($string, 'cheat'); // Find if the string contains the specified string (PHP >= 8.0) str_contains($string, 'cheat'); // Find if the string contains the specified string (PHP >= 8.0)
str_replace('Awesome', 'Bonjour', $string); // Replace all occurrence str_replace('Awesome', 'Bonjour', $string); // Replace all occurence
strcmp($string, 'Awesome cheatsheets'); // Compare two strings strcmp($string, 'Awesome cheatsheets'); // Compare two strings
strpos($string, 'a', 0); // Get position in the string strpos($string, 'a', 0); // Get position in the string
str_split($string, 2); // Split the string str_split($string, 2); // Split the string
@@ -189,7 +189,7 @@ $argc; // Number of arguments passed into terminal
$myObject?->getName()?->startWith('A'); $myObject?->getName()?->startWith('A');
/** /**
* Class * Class
* http://php.net/manual/en/language.oop5.basic.php * http://php.net/manual/en/language.oop5.basic.php
*/ */
class NormalClass extends AbstractClassName implements InterfaceName class NormalClass extends AbstractClassName implements InterfaceName
@@ -200,7 +200,7 @@ class NormalClass extends AbstractClassName implements InterfaceName
// --> PROPERTY TYPES <-- // --> PROPERTY TYPES <--
/** /**
* Public property, everyone can access this property. * Public property, everyone can access this property.
* @var Type * @var Type
*/ */
public $property; public $property;
@@ -251,7 +251,7 @@ class NormalClass extends AbstractClassName implements InterfaceName
protected function protectedFunction(Type $var = null): Type protected function protectedFunction(Type $var = null): Type
{ {
} }
/** /**
* Static function, doesn't need an instance to be executed. * Static function, doesn't need an instance to be executed.
* @param Type * @param Type
@@ -541,7 +541,7 @@ u Pattern is treated as UTF-8
\w Any "word" character (a-z 0-9 _) \w Any "word" character (a-z 0-9 _)
\W Any non "word" character \W Any non "word" character
\s Whitespace (space, tab CRLF) \s Whitespace (space, tab CRLF)
\S Any non whitespace character \S Any non whitepsace character
\d Digits (0-9) \d Digits (0-9)
\D Any non digit character \D Any non digit character
. (Period) - Any character except newline . (Period) - Any character except newline
+14 -14
View File
@@ -44,7 +44,7 @@
- As of python3.8 there are 35 keywords - As of python3.8 there are 35 keywords
| Keyword | Description | Category | | Keyword | Description | Category |
|---------- | ---------- | --------- | |---------- | ---------- | --------- |
| True | Boolean value for not False or 1 | Value Keyword| | True | Boolean value for not False or 1 | Value Keyword|
| False | Boolean Value for not True or 0 | Value Keyword | | False | Boolean Value for not True or 0 | Value Keyword |
| None | No Value | Value keyword | | None | No Value | Value keyword |
@@ -58,7 +58,7 @@
| else | this block will be executed if condition is false | conditional | | else | this block will be executed if condition is false | conditional |
| for | used for looping | iteration | | for | used for looping | iteration |
| while | used for looping | iteration | | while | used for looping | iteration |
| break | get out of loop | iteration | | break | get out of loop | iteration |
| continue | skip for specific condition | iteration | | continue | skip for specific condition | iteration |
| def | make user defined function | structure | | def | make user defined function | structure |
| class | make user defined classes | structure | | class | make user defined classes | structure |
@@ -71,8 +71,8 @@
| import | import libraries/modules/packages | import | | import | import libraries/modules/packages | import |
| from | import specific function/classes from modules/packages | import | | from | import specific function/classes from modules/packages | import |
| try | this block will be tried to get executed | exception handling | | try | this block will be tried to get executed | exception handling |
| except | is any exception/error has occurred it'll be executed | exception handling | | except | is any exception/error has occured it'll be executed | exception handling |
| finally | It'll be executed no matter exception occurs or not | exception handling | | finally | It'll be executed no matter exception occurs or not | exception handling |
| raise | throws any specific error/exception | exception handling | | raise | throws any specific error/exception | exception handling |
| assert | throws an AssertionError if condition is false | exception handling | | assert | throws an AssertionError if condition is false | exception handling |
| async | used to define asynchronous functions/co-routines | asynchronous programming | | async | used to define asynchronous functions/co-routines | asynchronous programming |
@@ -135,7 +135,7 @@
- Lists are created using square brackets: - Lists are created using square brackets:
```python ```python
thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"]
``` ```
- List items are ordered, changeable, and allow duplicate values. - List items are ordered, changeable, and allow duplicate values.
@@ -157,14 +157,14 @@ thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
- pop() function removes the last value in the given list by default. - pop() function removes the last value in the given list by default.
```python ```python
thislist = ["apple", "banana", "cherry"] thislist = ["apple", "banana", "cherry"]
print(thislist.pop()) # cherry print(thislist.pop()) # cherry
print(thislist.pop(0)) #apple print(thislist.pop(0)) #apple
``` ```
### Tuple ### Tuple
@@ -291,14 +291,14 @@ thisdict = {
"model": "Mustang", "model": "Mustang",
"year": 1964 "year": 1964
} }
x = car.pop("model") x = car.pop("model")
print(x)# Mustang print(x)# Mustang
print(car)#{'brand': 'Ford', 'year': 1964} print(car)#{'brand': 'Ford', 'year': 1964}
``` ```
### Conditional branching ### Conditional branching
@@ -378,5 +378,5 @@ function_name()
``` ```
* We need not to specify the return type of the function. * We need not to specify the return type of the function.
* Functions by default return `None` * Functions by default return `None`
* We can return any datatype. * We can return any datatype.
-815
View File
@@ -1,815 +0,0 @@
# TypeScript
* TypeScript is a statically typed superset of JavaScript that compiles to plain JavaScript
* It adds optional static type definitions to JavaScript, enabling better tooling and error detection
* In TypeScript, types are checked at compile-time, not runtime
* A TypeScript file has an extension of .ts (or .tsx for React components)
* TypeScript follows JavaScript syntax but adds type annotations and advanced features
* We can compile and run a TypeScript file by the following commands:
`$ tsc filename.ts` (compile to JavaScript)
`$ node filename.js` (run the compiled JavaScript)
Or directly: `$ ts-node filename.ts`
#### TypeScript requires compilation to JavaScript before execution.
## Create and execute a program
1. Install TypeScript globally: `npm install -g typescript`
1. Create the program: `touch program.ts`
1. Write the TypeScript code and save it
1. Compile: `tsc program.ts`
1. Run: `node program.js`
<br>
### Basic Data Types
| Data Type | Description | Example |
| --------- | ----------- | ------- |
| number | Integer and floating point values | `42`, `3.14`, `-7` |
| string | Text values | `"hello"`, `'world'`, `` `template` `` |
| boolean | True/false values | `true`, `false` |
| undefined | Undefined value | `undefined` |
| null | Null value | `null` |
| any | Any type (disables type checking) | Can be anything |
| unknown | Type-safe counterpart of any | Requires type checking |
| void | Absence of any type | Function return type |
| never | Type that never occurs | Functions that throw errors |
| object | Non-primitive types | `{}`, `[]`, functions |
<br>
## Keywords and Reserved Words
<br>
- TypeScript includes all JavaScript keywords plus additional TypeScript-specific ones
| Keyword | Description | Category |
|---------- | ---------- | --------- |
| let | Declares a block-scoped variable | Variable Declaration |
| const | Declares a block-scoped constant | Variable Declaration |
| var | Declares a function-scoped variable | Variable Declaration |
| function | Declares a function | Function |
| class | Declares a class | Class |
| interface | Declares an interface | Type Definition |
| type | Declares a type alias | Type Definition |
| enum | Declares an enumeration | Type Definition |
| namespace | Declares a namespace | Module System |
| module | Declares a module | Module System |
| import | Imports from another module | Module System |
| export | Exports from current module | Module System |
| extends | Class/interface inheritance | Inheritance |
| implements | Class implements interface | Inheritance |
| public | Public access modifier | Access Modifier |
| private | Private access modifier | Access Modifier |
| protected | Protected access modifier | Access Modifier |
| readonly | Read-only property | Access Modifier |
| static | Static class member | Class Member |
| abstract | Abstract class/method | Class |
| async | Asynchronous function | Async Programming |
| await | Awaits a promise | Async Programming |
| new | Creates new instance | Object Creation |
| this | Current object reference | Object Reference |
| super | Parent class reference | Inheritance |
| typeof | Gets type of variable | Type Operation |
| keyof | Gets keys of type | Type Operation |
| in | Property existence check | Type Guard |
| instanceof | Instance type check | Type Guard |
| as | Type assertion | Type Assertion |
| is | Type predicate | Type Guard |
| infer | Infers type in conditional types | Advanced Types |
| declare | Ambient declarations | Declaration |
| get | Property getter | Accessor |
| set | Property setter | Accessor |
| yield | Generator yield | Generator |
<br>
## Operators
<br>
| Operator | Description |
|-|-|
| ( ) | Grouping, function call, type assertion |
| [ ] | Array indexing, array/tuple types |
| . | Property access |
| ?. | Optional chaining |
| ! | Non-null assertion, logical not |
| ~ | Bitwise not |
| \- | Unary minus, arithmetic subtraction |
| \+ | Unary plus, arithmetic addition |
| \* | Multiplication |
| / | Division |
| % | Modulo |
| \*\* | Exponentiation |
| << | Left shift |
| \>> | Right shift |
| \>>> | Unsigned right shift |
| < | Less than |
| <= | Less than or equal |
| \> | Greater than |
| \>= | Greater than or equal |
| == | Equality (with coercion) |
| === | Strict equality |
| != | Inequality (with coercion) |
| !== | Strict inequality |
| & | Bitwise AND |
| ^ | Bitwise XOR |
| \| | Bitwise OR, Union types |
| && | Logical AND |
| \|\| | Logical OR |
| ?? | Nullish coalescing |
| ? : | Ternary conditional |
| = | Assignment |
| += | Add and assign |
| -= | Subtract and assign |
| *= | Multiply and assign |
| /= | Divide and assign |
| %= | Modulo and assign |
| **= | Exponentiate and assign |
| <<= | Left shift and assign |
| \>>= | Right shift and assign |
| &= | Bitwise AND and assign |
| ^= | Bitwise XOR and assign |
| \|= | Bitwise OR and assign |
| , | Comma operator |
| => | Arrow function |
| ... | Spread/rest operator |
### Basic Data Structures
### Array
- Array is an ordered collection of elements of the same or different types.
- Arrays are created using square brackets or Array constructor:
```typescript
let numbers: number[] = [1, 2, 3, 4];
let fruits: Array<string> = ["apple", "banana", "cherry"];
let mixed: (string | number)[] = [1, "two", 3];
```
- Array elements are indexed starting from 0.
- Arrays are mutable - you can change, add, and remove elements.
- Common array methods:
```typescript
let arr = [1, 2, 3];
arr.push(4); // Add to end: [1, 2, 3, 4]
arr.pop(); // Remove from end: [1, 2, 3]
arr.unshift(0); // Add to start: [0, 1, 2, 3]
arr.shift(); // Remove from start: [1, 2, 3]
arr.length; // Get length: 3
```
### Tuple
- Tuple is an array with a fixed number of elements of specific types.
- Tuples are created using square brackets with type annotations:
```typescript
let person: [string, number] = ["John", 30];
let coordinate: [number, number] = [10, 20];
```
- Tuple elements are ordered and have specific types at each position.
- You can access elements by index, but type checking ensures correctness:
```typescript
let point: [number, number] = [10, 20];
console.log(point[0]); // 10 (number)
console.log(point[1]); // 20 (number)
```
- Named tuples provide better readability:
```typescript
let user: [name: string, age: number] = ["Alice", 25];
```
- Optional and rest elements in tuples:
```typescript
let optional: [string, number?] = ["hello"];
let rest: [string, ...number[]] = ["coords", 1, 2, 3];
```
### Set
- Set is a collection of unique values of any type.
- Sets are created using the Set constructor:
```typescript
let uniqueNumbers = new Set<number>([1, 2, 3, 2]); // {1, 2, 3}
let stringSet = new Set<string>();
```
- Set operations:
```typescript
let mySet = new Set<string>();
mySet.add("apple"); // Add element
mySet.has("apple"); // Check existence: true
mySet.delete("apple"); // Remove element
mySet.clear(); // Remove all elements
mySet.size; // Get size
```
- Iterating over Set:
```typescript
let fruits = new Set(["apple", "banana", "cherry"]);
for (let fruit of fruits) {
console.log(fruit);
}
```
### Map
- Map is a collection of key-value pairs where keys can be any type.
- Maps are created using the Map constructor:
```typescript
let userMap = new Map<string, number>();
let mixedMap = new Map<string | number, any>();
```
- Map operations:
```typescript
let map = new Map<string, number>();
map.set("age", 30); // Add key-value pair
map.get("age"); // Get value: 30
map.has("age"); // Check key exists: true
map.delete("age"); // Remove key-value pair
map.clear(); // Remove all entries
map.size; // Get size
```
- Object vs Map:
```typescript
// Object - string/symbol keys only
let obj: { [key: string]: number } = { "age": 30 };
// Map - any type keys
let map = new Map<any, number>();
map.set("age", 30);
map.set(42, 100);
map.set(true, 1);
```
### Object Types and Interfaces
- Objects store key-value pairs and are fundamental to TypeScript.
- Object type annotation:
```typescript
let person: { name: string; age: number } = {
name: "John",
age: 30
};
```
- Interface definition for better reusability:
```typescript
interface User {
readonly id: number; // Read-only property
name: string;
age?: number; // Optional property
[key: string]: any; // Index signature
}
let user: User = {
id: 1,
name: "Alice"
};
```
- Nested objects and complex types:
```typescript
interface Address {
street: string;
city: string;
country: string;
}
interface Person {
name: string;
address: Address;
hobbies: string[];
}
```
### Conditional branching
```typescript
// If-else statements
if (condition) {
// code block
} else if (anotherCondition) {
// code block
} else {
// code block
}
// Ternary operator
let result = condition ? valueIfTrue : valueIfFalse;
// Switch statement
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
break;
}
```
### Loops
TypeScript supports all JavaScript loop constructs:
#### For loop
```typescript
// Traditional for loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// For-of loop (iterates over values)
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
// For-in loop (iterates over keys/indices)
for (let index in fruits) {
console.log(index, fruits[index]);
}
```
#### While loop
```typescript
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Do-while loop
let j = 0;
do {
console.log(j);
j++;
} while (j < 5);
```
#### Loop control
```typescript
for (let i = 0; i < 10; i++) {
if (i === 3) continue; // Skip iteration
if (i === 7) break; // Exit loop
console.log(i);
}
```
### Function definition
```typescript
// Function declaration
function functionName(param1: type, param2: type): returnType {
return value;
}
// Function expression
const functionName = function(param: type): returnType {
return value;
};
// Arrow function
const functionName = (param: type): returnType => {
return value;
};
// Arrow function (concise)
const functionName = (param: type): returnType => value;
```
### Function variations
```typescript
// Optional parameters
function greet(name: string, age?: number): string {
return age ? `Hello ${name}, you are ${age}` : `Hello ${name}`;
}
// Default parameters
function multiply(a: number, b: number = 1): number {
return a * b;
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
// Function overloads
function process(input: string): string;
function process(input: number): number;
function process(input: string | number): string | number {
if (typeof input === 'string') {
return input.toUpperCase();
}
return input * 2;
}
// Generic functions
function identity<T>(arg: T): T {
return arg;
}
let result = identity<string>("hello"); // Type is string
let result2 = identity(42); // Type inferred as number
```
### Function call
```typescript
functionName(argument1, argument2);
// With optional parameters
greet("John"); // "Hello John"
greet("John", 25); // "Hello John, you are 25"
// With rest parameters
sum(1, 2, 3, 4); // 10
// Generic function call
identity<string>("hello");
identity(42); // Type inferred
```
### Classes
```typescript
class ClassName {
// Properties
public publicProperty: type;
private privateProperty: type;
protected protectedProperty: type;
readonly readonlyProperty: type;
static staticProperty: type;
// Constructor
constructor(param: type) {
this.publicProperty = param;
}
// Methods
public method(): returnType {
return value;
}
// Getters and setters
get property(): type {
return this.privateProperty;
}
set property(value: type) {
this.privateProperty = value;
}
// Static method
static staticMethod(): returnType {
return value;
}
}
// Inheritance
class ChildClass extends ParentClass {
constructor(param: type) {
super(param); // Call parent constructor
}
// Override method
method(): returnType {
return super.method(); // Call parent method
}
}
// Abstract class
abstract class AbstractClass {
abstract abstractMethod(): void;
concreteMethod(): void {
console.log("This is implemented");
}
}
```
### Key TypeScript Features
* **Static Typing**: Types are checked at compile-time
* **Type Inference**: TypeScript can often infer types automatically
* **Optional Typing**: You can gradually add types to existing JavaScript
* **Generics**: Create reusable components that work with multiple types
* **Interfaces**: Define contracts for objects and classes
* **Enums**: Create named constants
* **Union Types**: Variables can be one of several types
* **Intersection Types**: Combine multiple types
* **Type Guards**: Runtime type checking
* **Decorators**: Add metadata to classes and methods
### Compilation
* TypeScript code must be compiled to JavaScript before execution
* The TypeScript compiler (`tsc`) performs type checking and transpilation
* Configuration is managed through `tsconfig.json`
* TypeScript can target different JavaScript versions (ES5, ES6, etc.)
* Source maps can be generated for debugging compiled code
#### Sample TypeScript Code
**hello.ts**
```typescript
// TypeScript source code
interface User {
name: string;
age: number;
isActive?: boolean;
}
class UserManager {
private users: User[] = [];
addUser(user: User): void {
this.users.push(user);
console.log(`Added user: ${user.name}`);
}
getActiveUsers(): User[] {
return this.users.filter(user => user.isActive ?? true);
}
getUserCount(): number {
return this.users.length;
}
}
// Generic function
function processData<T>(data: T[], processor: (item: T) => T): T[] {
return data.map(processor);
}
// Usage
const userManager = new UserManager();
const newUser: User = {
name: "John Doe",
age: 30,
isActive: true
};
userManager.addUser(newUser);
// Arrow functions with types
const formatUser = (user: User): string =>
`${user.name} (${user.age} years old)`;
// Union types and type guards
function displayInfo(value: string | number | boolean): string {
if (typeof value === "string") {
return `Text: ${value.toUpperCase()}`;
} else if (typeof value === "number") {
return `Number: ${value.toFixed(2)}`;
} else {
return `Boolean: ${value ? "Yes" : "No"}`;
}
}
console.log(displayInfo("hello"));
console.log(displayInfo(42.567));
console.log(displayInfo(true));
```
#### Compilation Commands
```bash
# Compile single file
tsc hello.ts
# Compile with specific target
tsc hello.ts --target ES2020
# Compile with source maps
tsc hello.ts --sourceMap
# Watch mode (recompile on changes)
tsc hello.ts --watch
# Compile all files in project
tsc
# Check for errors without generating files
tsc --noEmit
# Compile with strict mode
tsc hello.ts --strict
```
#### Compiled JavaScript Output
**hello.js** (compiled from above TypeScript)
```javascript
"use strict";
// JavaScript output (target ES2017)
class UserManager {
constructor() {
this.users = [];
}
addUser(user) {
this.users.push(user);
console.log(`Added user: ${user.name}`);
}
getActiveUsers() {
return this.users.filter(user => user.isActive ?? true);
}
getUserCount() {
return this.users.length;
}
}
// Generic function (types removed)
function processData(data, processor) {
return data.map(processor);
}
// Usage
const userManager = new UserManager();
const newUser = {
name: "John Doe",
age: 30,
isActive: true
};
userManager.addUser(newUser);
// Arrow functions
const formatUser = (user) => `${user.name} (${user.age} years old)`;
// Type guards remain as runtime checks
function displayInfo(value) {
if (typeof value === "string") {
return `Text: ${value.toUpperCase()}`;
}
else if (typeof value === "number") {
return `Number: ${value.toFixed(2)}`;
}
else {
return `Boolean: ${value ? "Yes" : "No"}`;
}
}
console.log(displayInfo("hello"));
console.log(displayInfo(42.567));
console.log(displayInfo(true));
```
#### tsconfig.json Configuration
```json
{
"compilerOptions": {
// Basic Options
"target": "ES2020", // Target JavaScript version
"module": "commonjs", // Module system
"lib": ["ES2020", "DOM"], // Include library files
"outDir": "./dist", // Output directory
"rootDir": "./src", // Input directory
"strict": true, // Enable strict type checking
// Additional Checks
"noUnusedLocals": true, // Error on unused variables
"noUnusedParameters": true, // Error on unused parameters
"noImplicitReturns": true, // Error on missing return statements
"noFallthroughCasesInSwitch": true, // Error on fallthrough cases
// Module Resolution
"moduleResolution": "node", // Module resolution strategy
"baseUrl": "./", // Base directory
"paths": { // Path mapping
"@/*": ["src/*"],
"@utils/*": ["src/utils/*"]
},
// Source Maps & Debugging
"sourceMap": true, // Generate source maps
"inlineSourceMap": false, // Don't inline source maps
"declaration": true, // Generate .d.ts files
"declarationMap": true, // Generate .d.ts.map files
// Experimental
"experimentalDecorators": true, // Enable decorators
"emitDecoratorMetadata": true, // Emit decorator metadata
// JavaScript Support
"allowJs": true, // Allow JavaScript files
"checkJs": false, // Type check JavaScript files
// Other Options
"esModuleInterop": true, // CommonJS/ES6 interop
"skipLibCheck": true, // Skip lib.d.ts type checking
"forceConsistentCasingInFileNames": true, // Consistent file names
"removeComments": true, // Remove comments from output
"noEmitOnError": true // Don't emit if there are errors
},
"include": [
"src/**/*", // Include all files in src
"tests/**/*" // Include test files
],
"exclude": [
"node_modules", // Exclude node_modules
"dist", // Exclude output directory
"**/*.test.ts", // Exclude test files from compilation
"**/*.spec.ts"
],
"files": [
// Explicitly include specific files (optional)
"src/main.ts"
]
}
```
#### Package.json Scripts
```json
{
"name": "typescript-project",
"version": "1.0.0",
"scripts": {
"build": "tsc",
"start": "node dist/main.js",
"dev": "ts-node src/main.ts",
"watch": "tsc --watch",
"clean": "rm -rf dist",
"type-check": "tsc --noEmit"
},
"devDependencies": {
"typescript": "^4.9.0",
"ts-node": "^10.9.0",
"@types/node": "^18.0.0"
}
}
```
#### Compilation Examples with Different Targets
**Original TypeScript:**
```typescript
const greet = (name: string = "World"): string => `Hello, ${name}!`;
const user = { name: "Alice", age: 30 };
const { name, age } = user;
```
**Compiled to ES5:**
```javascript
var greet = function (name) {
if (name === void 0) { name = "World"; }
return "Hello, " + name + "!";
};
var user = { name: "Alice", age: 30 };
var name = user.name, age = user.age;
```
**Compiled to ES2020:**
```javascript
const greet = (name = "World") => `Hello, ${name}!`;
const user = { name: "Alice", age: 30 };
const { name, age } = user;
```
#### Error Examples
**TypeScript with errors:**
```typescript
// Type errors that prevent compilation
let message: string = 42; // Error: Type 'number' is not assignable to type 'string'
let numbers: number[] = ["a", "b"]; // Error: Type 'string' is not assignable to type 'number'
function add(a: number, b: number): number {
return a + b;
}
add("hello", "world"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'
```
**Compiler output:**
```bash
$ tsc error-example.ts
error-example.ts(2,5): error TS2322: Type 'number' is not assignable to type 'string'.
error-example.ts(3,5): error TS2322: Type 'string[]' is not assignable to type 'number[]'.
error-example.ts(8,5): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
```
-1
View File
@@ -21,7 +21,6 @@ cat /proc/<process_id>/maps # Show the current virtual memory usage of a Linux
ip r # Display ip of the server ip r # Display ip of the server
lsof -i :9000 # List process running on port 9000 lsof -i :9000 # List process running on port 9000
kill -9 $(lsof -t -i:PORT) # Kill the process running on whichever port specified
journalctl -u minio.service -n 100 --no-pager # List last 100 logs for specific service journalctl -u minio.service -n 100 --no-pager # List last 100 logs for specific service
+25 -80
View File
@@ -1,6 +1,6 @@
############################################################################## ##############################################################################
# VIM CHEATSHEET # VIM CHEATSHEET
# WEBSITE: http://www.vim.org/ # WEBSITE: http://www.vim.org/
# DOCUMENTATION: https://vim.sourceforge.io/docs.php # DOCUMENTATION: https://vim.sourceforge.io/docs.php
############################################################################## ##############################################################################
@@ -20,15 +20,13 @@ e jump to end of words (punctuation considered words)
E jump to end of words (no punctuation) E jump to end of words (no punctuation)
b jump backward by words (punctuation considered words) b jump backward by words (punctuation considered words)
B jump backward by words (no punctuation) B jump backward by words (no punctuation)
ge jump backward to end of a word ge jump backward to end of words
gE jump backwards to the end of a word (words can contain punctuation)
0 (zero) start of line 0 (zero) start of line
^ first non-blank character of line ^ first non-blank character of line
$ jump to the end of the line $ end of line
g_ jump to the last non-blank character of the line - move line upwards, on the first non blank character
- move line upwards, on the first non-blank character + move line downwards, on the first non blank character
+ move line downwards, on the first non-blank character <enter> move line downwards, on the first non blank character
<enter> move line downwards, on the first non-blank character
gg go to first line gg go to first line
G go to last line G go to last line
ngg go to line n ngg go to line n
@@ -40,6 +38,10 @@ nG go To line n
} move the cursor a paragraph forwards } move the cursor a paragraph forwards
]] move the cursor a section forwards or to the next { ]] move the cursor a section forwards or to the next {
[[ move the cursor a section backwards or the previous { [[ move the cursor a section backwards or the previous {
CTRL-f move the cursor forward by a screen of text
CTRL-b move the cursor backward by a screen of text
CTRL-u move the cursor up by half a screen
CTRL-d move the cursor down by half a screen
H move the cursor to the top of the screen. H move the cursor to the top of the screen.
M move the cursor to the middle of the screen. M move the cursor to the middle of the screen.
L move the cursor to the bottom of the screen. L move the cursor to the bottom of the screen.
@@ -47,16 +49,6 @@ fx search line forward for 'x'
Fx search line backward for 'x' Fx search line backward for 'x'
tx search line forward before 'x' tx search line forward before 'x'
Tx search line backward before 'x' Tx search line backward before 'x'
CTRL-y moves screen up one line
CTRL-e moves screen down one line
CTRL-u moves cursor & screen up ½ page
CTRL-d moves cursor & screen down ½ page
CTRL-b moves screen up one page, cursor to last line
CTRL-f moves screen down one page, cursor to first line
zz shift current line to middle of screen
z. same as zz but also jumps to the first non-black character
zt shift current line to top of screen
zb shift current line to bottom of screen
############################################################################## ##############################################################################
@@ -68,15 +60,8 @@ zb shift current line to bottom of screen
ma make a bookmark named a at the current cursor position ma make a bookmark named a at the current cursor position
`a go to position of bookmark a `a go to position of bookmark a
'a go to the line with bookmark a 'a go to the line with bookmark a
`0 go to the position where Vim was previously exited
`" go to the position when last editing this file
`. go to the line that you last edited `. go to the line that you last edited
`` go to the position before the last jump
g, go to newer position in change list
g; go to older position in change list
# Tip: To jump to a mark you can either use a backtick (`) or an apostrophe (').
# Using an apostrophe jumps to the beginning (first non-blank) of the line holding the mark.
############################################################################## ##############################################################################
# INSERT MODE # INSERT MODE
@@ -85,13 +70,10 @@ g; go to older position in change list
i start insert mode at cursor i start insert mode at cursor
I insert at the beginning of the line I insert at the beginning of the line
gi return to insert mode where you inserted text the last time
gI like "I", but always start in column 1
a append after the cursor a append after the cursor
A append at the end of the line A append at the end of the line
o open (append) blank line below current line o open (append) blank line below current line
O open blank line above current line O open blank line above current line
CTRL-o Temporarily enter normal mode to issue one normal-mode command(while in insert mode)
Esc exit insert mode Esc exit insert mode
@@ -102,25 +84,10 @@ Esc exit insert mode
r replace a single character (does not use insert mode) r replace a single character (does not use insert mode)
R enter Insert mode, replacing characters rather than inserting R enter Insert mode, replacing characters rather than inserting
J join line below to the current one with one space in between J join line below to the current one
gJ join line below to the current one without space in between
cc change (replace) an entire line cc change (replace) an entire line
cw change (replace) to the end of word (same as ce) cw change (replace) to the end of word
2cw change (replace) repeat cw twice C change (replace) to the end of line
ciw change (replace) word under the cursor
caw change (replace) word under the cursor and the space after or before it
ci" change (replace) word inside ""
cit change (replace) html tag content
cat change (replace) html tag
cis change (replace) sentence under the cursor
cas change (replace) sentence under the cursor and the space after or before it
cib change (replace) inside a block with ()
cab change (replace) a block with ()
ciB change (replace) inside a block with {}
caB change (replace) a block with {}
C change (replace) to the end of line(same as c$)
cG change (replace) to the end of the file
cgg change (replace) from first line to current line
ct' change (replace) until the ' character (can change ' for any character) ct' change (replace) until the ' character (can change ' for any character)
s delete character at cursor and substitute text s delete character at cursor and substitute text
S delete line at cursor and substitute text (same as cc) S delete line at cursor and substitute text (same as cc)
@@ -135,7 +102,6 @@ guiw make current word lowercase
gU$ make uppercase until end of line gU$ make uppercase until end of line
gu$ make lowercase until end of line gu$ make lowercase until end of line
>> indent line one column to right >> indent line one column to right
>i{ indent everything in the {}
<< indent line one column to left << indent line one column to left
== auto-indent current line == auto-indent current line
ddp swap current line with next ddp swap current line with next
@@ -144,7 +110,6 @@ ddkP swap current line with previous
:r [name] insert the file [name] below the cursor. :r [name] insert the file [name] below the cursor.
:r !{cmd} execute {cmd} and insert its standard output below the cursor. :r !{cmd} execute {cmd} and insert its standard output below the cursor.
# Tip: Instead of b or B one can also use ( or { respectively.
############################################################################## ##############################################################################
# DELETING TEXT # DELETING TEXT
@@ -153,15 +118,10 @@ ddkP swap current line with previous
x delete current character x delete current character
X delete previous character X delete previous character
dw delete (cut) to the end of word (same as de) dw delete the current word
diw delete (cut) word under the cursor
daw delete (cut) word under the cursor and the space after or before it
dap delete (cut) a paragraph
dd delete (cut) a line dd delete (cut) a line
dt' delete (cut) until the next ' character on the line (replace ' by any character) dt' delete until the next ' character on the line (replace ' by any character)
dG delete (cut) to the end of the file D delete from cursor to end of line
dgg delete (cut) from first line to current line
D delete (cut) from cursor to end of line (same as d$)
:[range]d delete [range] lines :[range]d delete [range] lines
@@ -176,10 +136,6 @@ yy yank (copy) a line
y$ yank to end of line y$ yank to end of line
p put (paste) the clipboard after cursor/current line p put (paste) the clipboard after cursor/current line
P put (paste) before cursor/current line P put (paste) before cursor/current line
gp put (paste) the clipboard after cursor and leave cursor after the new text
gP put (paste) before cursor and leave cursor after the new text
"+y yank into the system clipboard register
"+p paste from the system clipboard register
:set paste avoid unexpected effects in pasting :set paste avoid unexpected effects in pasting
:registers display the contents of all registers :registers display the contents of all registers
"xyw yank word into register x "xyw yank word into register x
@@ -191,12 +147,6 @@ gP put (paste) before cursor and leave cursor after the new tex
"xgP just like "P", but leave the cursor just after the new text "xgP just like "P", but leave the cursor just after the new text
:[line]put x put the text from register x after [line] :[line]put x put the text from register x after [line]
# Tip: if you are using vim extension on vs code, you can enable
"vim.useSystemClipboard": true
in setting.json, this will allow to Use system clipboard for unnamed register.
############################################################################## ##############################################################################
# MACROS # MACROS
@@ -207,7 +157,6 @@ qa start recording macro 'a'
q end recording macro q end recording macro
@a replay macro 'a' @a replay macro 'a'
@: replay last command @: replay last command
@@ repeat macro
############################################################################## ##############################################################################
@@ -223,11 +172,9 @@ CTRL-v start visual block mode
O move to other corner of block O move to other corner of block
aw mark a word aw mark a word
ab a () block (with braces) ab a () block (with braces)
aB a {} block (with brackets) ab a {} block (with brackets)
at a block with <> tags
ib inner () block ib inner () block
iB inner {} block ib inner {} block
it inner <> block
Esc exit visual mode Esc exit visual mode
VISUAL MODE COMMANDS VISUAL MODE COMMANDS
@@ -247,7 +194,6 @@ v% selects matching parenthesis
vi{ selects matching curly brace vi{ selects matching curly brace
vi" selects text between double quotes vi" selects text between double quotes
vi' selects text between single quotes vi' selects text between single quotes
gv reselect the last selected area
############################################################################## ##############################################################################
# SPELLING # SPELLING
@@ -294,7 +240,7 @@ set ic ignore case: turn on
set noic ignore case: turn off set noic ignore case: turn off
:%s/old/new/g replace all old with new throughout file :%s/old/new/g replace all old with new throughout file
:%s/old/new/gc replace all old with new throughout file with confirmation :%s/old/new/gc replace all old with new throughout file with confirmation
:argdo %s/old/new/gc | wq open multiple files and run this command to replace old :argdo %s/old/new/gc | wq open multiple files and run this command to replace old
with new in every file with confirmation, save and quit with new in every file with confirmation, save and quit
@@ -337,6 +283,7 @@ CTRL-w < increase window width
CTRL-w > decrease window width CTRL-w > decrease window width
CTRL-w = equal window CTRL-w = equal window
CTRL-w o close other windows CTRL-w o close other windows
zz Centers the window to the current line
############################################################################## ##############################################################################
@@ -359,14 +306,12 @@ clast display the last error
% show matching brace, bracket, or parenthese % show matching brace, bracket, or parenthese
gf edit the file whose name is under the cursor gf edit the file whose name is under or after the cursor
gF edit the file whose name is under the cursor and jump to the line number
gd when the cursor is on a local variable or function, jump to its declaration gd when the cursor is on a local variable or function, jump to its declaration
'' return to the line where the cursor was before the latest jump '' return to the line where the cursor was before the latest jump
gi return to insert mode where you inserted text the last time
CTRL-o move to previous position you were at CTRL-o move to previous position you were at
CTRL-i move to more recent position you were at CTRL-i move to more recent position you were at
:set nu display numbers (short for :set number)
:set nonu hide numbers (short for :set nonumber)
############################################################################## ##############################################################################
@@ -540,7 +485,7 @@ CTRL-n jump to the next empty tag / attribute
cs'" change surrounding quotes to double-quotes cs'" change surrounding quotes to double-quotes
cs(} change surrounding parens to braces cs(} change surrounding parens to braces
cs({ change surrounding parens to braces with space cs({ change surrounding parens to braces with space
ds' delete surrounding quotes ds' delete surrounding quotes
dst delete surrounding tags dst delete surrounding tags
@@ -648,7 +593,7 @@ jj exit insertion mode
<leader>/ clear the search register <leader>/ clear the search register
<leader>h toggle hidden characters <leader>h toggle hidden characters
<leader>W strip all trailing whitespace <leader>W strip all trailing whitespace
@@ -716,5 +661,5 @@ CTRL-y go to next tag of attribute in sparkup plugin
<leader>g toggle Gundo window <leader>g toggle Gundo window
IMG<CR> show image browser to insert image tag with src, width and height IMG<CR> show image browser to insert image tag with src, width and height
b insert image tag with dimensions from NERDTree b insert image tag with dimensions from NERDTree
(http://stackoverflow.com/questions/5707925/vim-image-placement) (http://stackoverflow.com/questions/5707925/vim-image-placement)