1
1
mirror of https://github.com/namibia/awesome-cheatsheets.git synced 2024-11-21 20:35:12 +00:00

Merge branch 'master' of github.com:LeCoupa/awesome-cheatsheets

This commit is contained in:
Julien Le Coupanec 2020-11-30 18:18:00 +01:00
commit 61813a4812
12 changed files with 1104 additions and 44 deletions

View File

@ -28,6 +28,7 @@ Feel free to take a look. You might learn new things. They have been designed to
- [C](languages/C.txt) - [C](languages/C.txt)
- [C#](languages/C%23.txt) - [C#](languages/C%23.txt)
- [PHP](languages/php.php) - [PHP](languages/php.php)
- [JAVA](languages/java.md)
#### Functional #### Functional
@ -98,6 +99,7 @@ Feel free to take a look. You might learn new things. They have been designed to
#### Development #### Development
- [cURL](tools/curl.sh) - [cURL](tools/curl.sh)
- [Drush](tools/drush.sh)
- [Elasticsearch](tools/elasticsearch.js) - [Elasticsearch](tools/elasticsearch.js)
- [Emmet](tools/emmet.md) - [Emmet](tools/emmet.md)
- [Git](tools/git.sh) - [Git](tools/git.sh)

View File

@ -7,4 +7,20 @@ mysql -u username -p database_name < file.sql # Import d
SHOW PROCESSLIST; # Show you any queries that are currently running or in the queue to run SHOW PROCESSLIST; # Show you any queries that are currently running or in the queue to run
GRANT ALL ON mydb.* TO 'myuser'@'locahost'; # Grant **all** privileges on database # *****************************************************************************
# Users and Privileges
# *****************************************************************************
# Replace 'host' with '%' to indicate any host
CREATE USER 'user'@'host'; # Create user
DROP USER 'user'@'host'; # Remove user.
GRANT ALL PRIVILEGES ON base.* TO 'user'@'host' IDENTIFIED BY 'password'; # Grant access to database using password
GRANT SELECT, INSERT, DELETE ON base.* TO 'user'@'host' IDENTIFIED BY 'password'; # Grant specific privileges to database using password
GRANT ALL PRIVILEGES ON base.* TO 'user'@'host' WITH GRANT OPTION; # Grant **all** privileges on database
REVOKE ALL PRIVILEGES ON base.* FROM 'user'@'host'; # Remove privileges on database
REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'user'@'host'; # Remove **all** privileges on database
FLUSH PRIVILEGES; # Use **only** if you modify grant tables directly using statements like INSERT, UPDATE or DELETE.

View File

@ -45,6 +45,11 @@
<abbr></abbr> <!-- Contains abbreviations while also making the full form avaialable --> <abbr></abbr> <!-- Contains abbreviations while also making the full form avaialable -->
<address></address> <!-- Used to display contact information --> <address></address> <!-- Used to display contact information -->
<code></code> <!-- Used to display inline code snippets --> <code></code> <!-- Used to display inline code snippets -->
<q></q> <!-- Defines a short inline quotation -->
<sub></sub> <!-- Defines subscripted text -->
<sup></sup> <!-- Defines superscripted text -->
<kbd></kbd> <!-- Specifies text as keyboard input -->
<small></small> <!-- Specifies small text -->
<!-- Links Formatting --> <!-- Links Formatting -->
@ -176,6 +181,11 @@ width="" <!-- Describes the width of th
<time></time> <!-- Identifies the time and date --> <time></time> <!-- Identifies the time and date -->
<wbr> <!-- A line break within the content --> <wbr> <!-- A line break within the content -->
<!-- Some other useful tags -->
<canvas></canvas> <!-- Allows to draw 2D shapes on the web page with the help of javascript -->
<keygen> <!-- Represents a control for generating a public-private key pair -->
<map></map> <!-- Specifies an image map -->
<!-- Collective Character Obejcts --> <!-- Collective Character Obejcts -->

View File

@ -95,6 +95,8 @@ genscript # converts plain text files into postscript for pr
dvips <filename> # prints .dvi files (i.e. files produced by LaTeX) dvips <filename> # prints .dvi files (i.e. files produced by LaTeX)
grep <pattern> <filenames> # looks for the string in the files grep <pattern> <filenames> # looks for the string in the files
grep -r <pattern> <dir> # search recursively for pattern in directory grep -r <pattern> <dir> # search recursively for pattern in directory
head -n file_name | tail +n # Print nth line from file.
head -y lines.txt | tail +x # want to display all the lines from x to y. This includes the xth and yth lines.
############################################################################## ##############################################################################
@ -111,7 +113,7 @@ cd .. # changes to the parent directory
cd <dirname> # changes directory cd <dirname> # changes directory
cp -r <dir1> <dir2> # copy <dir1> into <dir2> including sub-directories cp -r <dir1> <dir2> # copy <dir1> into <dir2> including sub-directories
pwd # tells you where you currently are pwd # tells you where you currently are
cd ~ # changes to home.
############################################################################## ##############################################################################
# SSH, SYSTEM INFO & NETWORK COMMANDS # SSH, SYSTEM INFO & NETWORK COMMANDS

619
languages/java.md Normal file
View File

@ -0,0 +1,619 @@
### HELLO WORLD :ghost:
```java
//Text file name HelloWorld.java
public class HelloWorld {
// main() is the method
public static void main (String[] arfs)
//Prints "Hello World" in the terminal window.
System.out.pritn("Hello World");
}
```
### COMPILATION & EXECUTING JAVA CODE
* Goto your program directory in terminal (Assumed JAVA Path is set)
* After for compile your code
> **javac HelloWorld.java (your program file name)**
* For run program
> **java HelloWorld (main class name)**
### DATA TYPES
| Type | Set of values | Values | Operators |
|:-------:|:-----------------------:|:----------------------------:|:---------:|
| int | integers | between -2^31 and + (2^31)-1 | + - * / % |
| double | floating-point numbers | real numbers | + - * / |
| boolean | boolean values | true or false | && \|\| ! |
| char | characters | | |
| String | sequences of characters | | |
### DECLARATION AND ASSIGNMENT STATEMENTS
```java
//Declaration statement
int a,b;
//Assignment statement
a = 13212; //a is the variable name; 13212 is the literal which is assign to the variable a
//Initialization statement
int c = a + b;
```
### COMPARISON OPERATORS
| Operation | Meaning |
|:---------:|:---------------------:|
| == | equal |
| != | not equal |
| < | less than |
| > | greater than |
| <= | less than or equal |
| >= | greater than or equal |
### PRINTING
```java
String s = "Happy Coding Folks!!"
void System.out.print(String s) //print s
void System.out.println(String s) //print s, followed by a newline
void System.out.println() //print a newline
```
### PARSING COMMAND-LINE ARGUMENTS
```java
String s = "Java is the best!!"
int Integer.parseInt(String s) //convert s to an int value
double Double.parseDouble(String) //convert s to a double value
long Long.parseLong(String s) // convert s to a long value
````
### MATH LIBRARY
```java
Public Class Math{
double abs(double a) // absolute value of a
double max(double a, double b) //maximum of a and b
double min(double a, dobule a) //minimum of a and b
double sin(double theta) //sine of theta
double cos(double theta) //cosine of theta
double tan(double theta) //tangent of theta
double toRadians(double degrees) // convert angle from degrees to radians
double toDegreestouble radians) // convert angle from radians to degrees
double exp(doube a) // exponential (e^a)
double pow(double a, double p) //raise a to the bth power (a^b)
double random() //random in [0,1)
double sqrt(double a) //square root of a
}
```
### EXAMPLES OF TYPE CONVERSION
| Expression | Expression type | Expression value |
|:---------------------:|:---------------:|:----------------:|
| (1 + 2 + 3 + 4) / 4.0 | double | 2.5 |
| Math.sqrt(4) | double | 2.0 |
| "123343" + 99 | String | "12334399" |
| 11 * 0.25 | double | 2.75 |
| (int) 11 * 0.25 | double | 2.75 |
| 11 * (int) 0.25 | int | 0 |
| (int) (11 * 0.25) | int | 2 |
### CONDITIONAL & LOOP STATEMENT
#### ANATOMY OF CONDITIONAL STATEMENT
> IF Statement
```java
if (x>y) { // x > y is the boolean expression
//Sequence of statements
x = y;
}
```
> IF-ELSE STATEMENT
```java
if (BOOLEAN EXPRESSION) {
//Sequence of statements
} else {
//Sequence of statements
}
```
> NESTED IF STATEMENT
```java
if (BOOLEAN EXPRESSION) {
//Sequence of statements
} else if {
//Sequence of statements
}
.
.
.
else {
//Sequence of statements
}
```
>SWITCH STATEMENT
```java
switch (VARIABLE TO EVALUATE ITS VALUE) {
case value: Statement; break;
...
...
...
default: Statement; break;
}
```
**Example:**
```java
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
```
#### ANATOMY OF A LOOP STATEMENT
>FOR LOOP STATEMENT
```java
for (declare and initialize a loop control variable; loop-continuation condition/s; increment or decrement of the variable of control)
{
//Statement
}
```
**Example:**
```java
for (int i = 0; i <= n; i++) {
System.out.println(i);
}
```
> WHILE LOOP STATEMENT
```java
while(condition){ //till condition will be true.
//code to be executed
}
```
**Example:**
```java
//Initialization is a separate statement
int power = 1;
while ( power <= 10/2 ) // power <= n/2 is an example of the loop-continuation condition
{
System.out.println(power);
}
```
> DO-WHILE LOOP STATEMENT
```java
do{ //always run one time even if condition would be false
//Statement
} while(loop-continuation condition);
```
**Example:**
```java
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
```
### ARRAY
> ARRAY DECLARATION
```java
int[] ai; // array of int
short[][] as; // array of array of short
short s, // scalar short
aas[][]; // array of array of short
Object[] ao; // array of Object
Collection<?>[] ca; // array of Collection of unknown type
```
> DECLARATION OF ARRAY VARIABLE
```java
Exception ae[] = new Exception[3];
Object aao[][] = new Exception[2][3];
int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
'S', 't', 'r', 'i', 'n', 'g' };
String[] aas = { "array", "of", "String", };
```
### ACCESS MODIFIERS
1. defualt(No keyword required)
2. private
3. public
4. protected
### NON ACCESS MODIFIERS
1. static
2. final
3. transient
4. abstract
5. synchronized
6. volatile
## Object Oriented Programming (OOPs) Concept :clipboard:
### OBJECT
```java
//Declare a variable, object name
String s;
//Invoke a contructor to create an object
s = new String ("Hello World");
//Invoke an instance method that operates on the object's value
char c = s.chartAt(4);
```
> INSTANCE VARIABLES
```java
public class Charge {
//Instance variable declarations
private final double rx, ry;
private final double q;
}
```
### METHODS
```java
public static double sum (int a, int b) { //double is the return type, sum is the method's name, a and b are two arguments of type int;
int result; //local variable
result = a + b;
return result;//return statement;
}
```
### CLASS DECLARATION
```java
class MyClass {
// field, constructor, and
// method declarations
}
```
**Example:**
```java
public class Bicycle {
// the Bicycle class has
// three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has
// one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has
// four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
}
}
```
>DECLARING CLASSESS IMPLEMENTATING AN INTERFACE AND EXTENDING PARENT CLASS
```java
class MyClass extends MySuperClass implements YourInterface {
// field, constructor, and
// method declarations
}
```
* MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
> CONSTRUCTORS
* A class contains constructors that are invoked to create objects from the class blueprint.
* Constructor declarations look like method declarations—except that they use the name of the class and have no return type
* Each and every class has defualt No-args constructor.
```java
public class Bicycle{
private int gear;
private int cadence;
private int speed;
public Bicycle(int startCadence, int startSpeed, int startGear) { //args-constructor
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public Bicycle(){//No-args constructor
super();
}
}
```
### POLYMORPHISM
* Polymorphism is the concept where an object behaves differently in different situations.
* There are two types of polymorphism
1. compile time polymorphism
2. runtime polymorphism.
#### 1. Compile Time Polymorphism
* Compile-time polymorphism is achieved by method overloading.
* method overloading is creating multiple method with methods name is same and arguments are different.
```java
public class Circle {
public void draw(){
System.out.println("Drwaing circle with default color Black and diameter 1 cm.");
}
public void draw(int diameter){ //method draw() overloaded.
System.out.println("Drwaing circle with default color Black and diameter"+diameter+" cm.");
}
public void draw(int diameter, String color){ //method draw() overloaded.
System.out.println("Drwaing circle with color"+color+" and diameter"+diameter+" cm.");
}
}
```
#### 2. Run Time Polymorphism
* Run-time polymorphism is achieved by method overriding.
* Runtime polymorphism is implemented when we have an **“IS-A”** relationship between objects.
* method overriding is the subclass has to override the superclass method.
```java
public interface Shape {
public void draw();
}
```
```java
public class Circle implements Shape{
@Override
public void draw(){
System.out.println("Drwaing circle");
}
}
```
```java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing Square");
}
}
```
* `Shape` is the superclass and there are two subclasses `Circle` and `Square`
* Below is an example of runtime polymorphism.
```java
Shape sh = new Circle();
sh.draw();
Shape sh1 = getShape(); //some third party logic to determine shape
sh1.draw();
```
### INHERITANCE
* Inheritance is the mechanism of code reuse.
* The object that is getting inherited is called the superclass and the object that inherits the superclass is called a subclass.
* We use `extends` keyword in java to implement inheritance from class.
* We use `implements` keyword in java to implement inheritance from interface.
```java
public class Superclass{
// methods and fields
}
```
```java
public interface Superinterface{
// methods and fields
}
```
```java
public class Subclass extends Superclass implements Superinterface{
// methods and fields
}
```
### Abstraction
* Abstraction is the concept of hiding the internal details and describing things in simple terms.
* Abstraction can be achieved by two ways.
1. Abstract Class
2. Interface
#### 1. Abstract Class
* An abstract class must be declared with an `abstract` keyword.
* It can have abstract and non-abstract methods.
* It cannot be instantiated.
* It can have constructors and static methods also.
* It can have final methods which will force the subclass not to change the body of the method.
```java
abstract class Flower{
abstract String Smell(); //abstract method.
String Oil(){ // non-abstract method.
System.out.println("Flower Oil is good.");
}
}
public class Lily extends Flower{
private String Smell(){ // implementation of abstarct method.
System.out.println("Lily smell's lovender.");
}
}
```
#### 2. Interface
* Interface is a blueprint of a **class**.
* It can have only abstract methods. [Except Java 8 and next versions.]
* Since Java 8, we can have **default and static** methods in an interface.
```java
interface print{
void printPaper();
}
public class A4 implements print{
public void printPaper(){
System.out.println("A4 Page Printed. ");
}
}
```
### Encapsulation
* Encapsulation is used for access restriction to class members and methods.
* Encapsulation is the technique used to implement abstraction in OOP.
* As in encapsulation, the data in a class is hidden from other classes, so it is also known as **data-hiding**.
* Encapsulation can be achieved by Declaring all the variables in the class as private and writing public methods in the class to set and get the values of variables.
* Best example of Encapsulation is POJO (Plain-Java-Object-Class).
```java
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
```
## ADVANCE DATA TYPE
* **STACK DATA TYPE**
```java
public class Stack<Item> implements Iterable <Item>
Stack() //create an empty stack
boolean isEmpty() //return if the stack empty
void push(Item item) // push an item onto the stack
Item pop() //return and remove the item that was inserted most recently
int size() //number of item on stack
```
* **QUEUE DATA TYPE**
```java
public class Queue<Item> implements Iterable<Item>
Queue() //create an emptyh queue
boolean isEmpthy() //return if the queue empthy
void enqueue(Item item) // insert an item onto queue
Item dequeue() //return and remove the item that was inserted least recently
int size() //number of item on queue
```
* **ITERABLE**
```java
//import Iterator
import java.util.Iterator;
public class Queue<Item> implements Iterable <Item> {
//FIFO queue
private Node first;
private Node last;
private class Node {
Item item;
Node next;
}
public void enqueue (Item item)
...
public Item dequeue()
...
}
```
* **SYMBOL TABLE DATA TYPE**
```java
public class ST<Key extends Comparable<Key>, Value>
ST() //create and empty symbol table
void put(Key key, Value val) //associate val with key
Value get(Key key) //value associated with key
void remove(Key key) //remove key (and its associated value)
boolean contains (Key key) //return if there is a value associated with key
int size() //number of key-value pairs
Iterable<Key> keys() // all keys in the symbol table
```
* **SET DATA TYPE**
```java
public class SET<Key extends Comparable<Key>> implements Iterable<Key>
SET() //create an empthy set
boolean isEmpthy() //return if the set is empthy
void add (Key key) //add key to the set
void remove(Key key) //remove key from set
boolean contains(Key key) //return if the key is in the set
int size() //number of elements in set
```

View File

@ -366,3 +366,106 @@ class ClassWithLogger
*/ */
use LoggerAwareTrait; use LoggerAwareTrait;
} }
/**
* PHP Regex.
*/
// Meta Characters.
^ Start of subject (or line in multiline mode)
$ End of subject (or line in multiline mode)
[ Start character class definition
] End character class definition
| Alternates, eg (a|b) matches a or b
( Start subpattern
) End subpattern
\ Escape character
// Pattern Modifiers.
i Caseless - ignore case
m Multiline mode - ^ and $ match start and end of lines
s Dotall - . class includes newline
x Extended- comments & whitespace
e preg_replace only - enables evaluation of replacement as PHP code
S Extra analysis of pattern
U Pattern is ungreedy
u Pattern is treated as UTF-8
// Subpattern Modifiers & Assertions.
(?:) Non capturing subpattern ((?:foo|fu)bar) matches foobar or fubar without foo or fu appearing as a captured subpattern
(?=) Positive look ahead assertion foo(?=bar) matches foo when followed by bar
(?!) Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
(?<=) Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
(?<!) Negative look behind assertion (?<!foo)bar matches bar when not preceded by foo
(?>) Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
(?(x)) Conditional subpatterns (?(3)foo|fu)bar Matches foo if 3rd subpattern has matched, fu if not
(?#) Comment (?# Pattern does x y or z)
// Base Character Classes
\w Any "word" character (a-z 0-9 _)
\W Any non "word" character
\s Whitespace (space, tab CRLF)
\S Any non whitepsace character
\d Digits (0-9)
\D Any non digit character
. (Period) - Any character except newline
// Multiplicity.
n* Zero or more of n
n+ One or more of n
n? Zero or one occurrences of n
{n} n occurrences exactly
{n,} At least n occurrences
{,m} At most m occurrences
{n,m} Between n and m occurrences (inclusive)
// PHP Regular Expression Functions.
Function Description
preg_match() The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all() The preg_match_all() function matches all occurrences of pattern in string. Useful for search and replace.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split() Preg Split (preg_split()) operates exactly like the split() function, except that regular expressions are accepted as input parameters.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements matching the regex pattern within a string.
preg_ quote() Quote regular expression characters
// Code Snippets.
//A better solution for validate email syntax is using filter_var.
if (filter_var('test+email@fexample.com', FILTER_VALIDATE_EMAIL)) {
echo "Your email is ok.";
} else {
echo "Wrong email address format.";
}
//Validate username, consist of alpha-numeric (a-z, A-Z, 0-9), underscores, and has minimum 5 character and maximum 20 character.
//You could change the minimum character and maximum character to any number you like.
$username = "user_name12";
if (preg_match('/^[a-z\d_]{5,20}$/i', $username)) {
echo "Your username is ok.";
} else {
echo "Wrong username format.";
}
//Validate domain
$url = "http://domain-name.com/";
if (preg_match('/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i', $url)) {
echo "Your url is ok.";
} else {
echo "Wrong url.";
}
//Extract domain name from certain URL
$url = "http://domain-name.com/index.html";
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
$host = $matches[1];
echo $host; // domain-name.com
//Highlight a word in the content
$text = "A regular expression (shortened as regex) is a sequence of characters that define a search pattern. Usually such patterns are used by string-searching algorithms for 'find' or 'find and replace' operations on strings, or for input validation.";
$text = preg_replace("/\b(regex)\b/i", 'replaced content', $text);
echo $text; /*A regular expression (shortened as replaced content) is a sequence of characters that define a search pattern. Usually such patterns are used by string-searching algorithms for 'find' or 'find and replace' operations on strings, or for input validation.*/

66
tools/drush.sh Normal file
View File

@ -0,0 +1,66 @@
##############################################################################
# DRUSH
# Install: https://www.drush.org/install/
# Usage: https://www.drush.org/usage/
##############################################################################
cache clear (cc) # Clear all caches.
cron # Run all cron hooks.
disable (dis) # Disable one or more modules.
download (dl) # Download core Drupal and projects like CCK, Zen, etc.
enable (en) # Enable one or more modules.
eval # Evaluate arbitrary php code after bootstrapping Drupal.
help # Print this help message. Use --filter to limit command list to one command file (e.g. --filter=pm)
info # Release information for a project
installcore (ic) # Install Drupal core via the specified install profile. Note that updating core with Drush is not yet available. See http://drupal.org/node/434944.
refresh (rf) # Refresh update status information script Runs the given php script(s) after a full Drupal bootstrap. NOTE: you can't supply absolute paths to the script e.g. ~/Desktop/script.php won't work Desktop/script.php will
sql cli (sqlc) # Open a SQL command-line interface using Drupal?s credentials.
sql conf # Print database connection details.
sql connect # A string for connecting to the DB.
sql dump # Exports the Drupal DB as SQL using mysqldump.
sql load # Copy source database to target database.
sql query (sqlq) # Execute a query against the site database.
status (st) # Provides a birds-eye view of the current Drupal installation, if any.
statusmodules (sm) # Show module enabled/disabled status
sync # Rsync the Drupal tree to/from another server using ssh.
test clean # Delete leftover tables and files from prior test runs.
test mail # Run all tests and mail the results to your team.
uninstall # Uninstall one or more modules.
update (up) # Update your project code and apply any database updates required (update.php)
updatecode (upc) # Update your project code. Moves existing project files to the backup directory specified in the config.
updatedb (updb) # Execute the update.php process from the command line.
variable delete (vdel) # Delete a variable.
variable get (vget) # Get a list of some or all site variables and values.
variable set (vset) # Set a variable.
watchdog delete (wd) # Delete all messages or only those of a specified type.
watchdog show (ws) # Shows recent watchdog log messages. Optionally filter for a specific type.

View File

@ -1,28 +1,55 @@
git init # initiates git in the current directory git init # initiates git in the current directory
git clone <address> # creates a git repo from given address (get the address from your git-server) git clone <address> # creates a git repo from given address (get the address from your git-server)
git clone <address> -b <branch_name> <path/to/directory> # clones a git repo from the address into the given directory and checkout's the given branch
git clone <address> -b <branch_name> --single-branch # Clones a single branch
git add file.txt # adds(stages) file.txt to the git git add file.txt # adds(stages) file.txt to the git
git add * # adds(stages) all new modifications, deletions, creations to the git git add * # adds(stages) all new modifications, deletions, creations to the git
git reset file.txt # Removes file.txt from the stage git reset file.txt # Removes file.txt from the stage
git reset --hard # Throws away all your uncommitted changes, hard reset files to HEAD
git rm file.txt # removes file.txt both from git and file system git rm file.txt # removes file.txt both from git and file system
git rm --cached file.txt # only removes file.txt both from git index
git status # shows the modifications and stuff that are not staged yet git status # shows the modifications and stuff that are not staged yet
git branch # shows all the branches (current branch is shown with a star) git branch # shows all the branches (current branch is shown with a star)
git branch my-branch # creates my-branch git branch my-branch # creates my-branch
git branch -d my-branch # deletes my-branch git branch -d my-branch # deletes my-branch
git checkout my-bracnch # switches to my-branch git checkout my-branch # switches to my-branch
git merge my-branch # merges my-branch to current branch git merge my-branch # merges my-branch to current branch
git push origin --delete my-branch # delete remote branch git push origin --delete my-branch # delete remote branch
git branch -m <new-branch-name> # rename the branch
git checkout --orphan <branch_name> # checkout a branch with no commit history
git branch -vv # list all branches and their upstreams, as well as last commit on branch
git branch -a # List all local and remote branches
git cherry-pick <commit_id> # merge the specified commit git cherry-pick <commit_id> # merge the specified commit
git cherry-pick <commit_id_A>^..<commit_id_B> # pick the entire range of commits where A is older than B ( the ^ is for including A as well )
git remote # shows the remotes git remote # shows the remotes
git remote -v # shows the remote for pull and push git remote -v # shows the remote for pull and push
git remote add my-remote <address> # creates a remote (get the address from your git-server) git remote add my-remote <address> # creates a remote (get the address from your git-server)
git remote rm my-remote # Remove a remote
git log # shows the log of commits git log # shows the log of commits
git log --oneline # shows the log of commits, each commit in a single line
git log -p <file_name> # change over time for a specific file
git log <Branch1> ^<Branch2> # lists commit(s) in branch1 that are not in branch2
git log -n <x> # lists the last x commits
git log -n <x> --oneline # lists the last x commits, each commit in single line
git grep --heading --line-number '<string/regex>' # Find lines matching the pattern in tracked files
git log --grep='<string/regex>' # Search Commit log
git commit -m "msg" # commit changes with a msg git commit -m "msg" # commit changes with a msg
git commit --amend # combine staged changes with the previous commit, or edit the previous commit message without changing its snapshot
git commit --amend --no-edit # amends a commit without changing its commit message
git commit --amend --author='Author Name <email@address.com>' # Amend the author of a commit
git push my-remote my-branch # pushes the commits to the my-remote in my-branch (does not push the tags) git push my-remote my-branch # pushes the commits to the my-remote in my-branch (does not push the tags)
git revert <commit-id> # Undo a commit by creating a new commit
git show # shows one or more objects (blobs, trees, tags and commits).
git diff # show changes between commits, commit and working tree
git diff --color # show colored diff
git diff --staged # Shows changes staged for commit
git tag # shows all the tags git tag # shows all the tags
git tag -a v1.0 -m "msg" # creates an annotated tag git tag -a v1.0 -m "msg" # creates an annotated tag
@ -39,7 +66,7 @@ git stash -u # stash everything including new untracked
git stash save "msg" # stash with a msg git stash save "msg" # stash with a msg
git stash list # list all stashes git stash list # list all stashes
git stash pop # delete the recent stash and applies it git stash pop # delete the recent stash and applies it
git stash stach@{2} # delete the {2} stash and applies it git stash pop stash@{2} # delete the {2} stash and applies it
git stash show # shows the description of stash git stash show # shows the description of stash
git stash apply # keep the stash and applies it to the git git stash apply # keep the stash and applies it to the git
git stash branch my-branch stash@{1} # creates a branch from your stash git stash branch my-branch stash@{1} # creates a branch from your stash
@ -55,6 +82,11 @@ git clean -f -d/git clean -fd # To remove directories permanently
git clean -f -X/git clean -fX # To remove ignored files permanently git clean -f -X/git clean -fX # To remove ignored files permanently
git clean -f -x/git clean -fx # To remove ignored and non-ignored files permanently git clean -f -x/git clean -fx # To remove ignored and non-ignored files permanently
git config --global --list # lists the git configuration for all repos
git config --global --edit # opens an editor to edit the git config file
git config --global alias.<handle> <command> # add git aliases to speed up workflow , eg. if handle is st and command is status then running git st would execute git status
.gitignore .gitignore
# is a file including names of stuff that you don"t want to be staged or tracked. # is a file including names of stuff that you don"t want to be staged or tracked.
# You usually keep your local files like database, media, and etc here. # You usually keep your local files like database, media, and etc here.
@ -64,4 +96,3 @@ git clean -f -x/git clean -fx # To remove ignored and non-ignored files perm
# is a hidden directory in repo directory including git files. It is created after "git init". # is a hidden directory in repo directory including git files. It is created after "git init".

View File

@ -100,6 +100,8 @@ git config --global --remove-section url.ssh://git@heroku.com/ # To remove
### Managing and deploying applications on Heroku (Using Docker) ################################### ### Managing and deploying applications on Heroku (Using Docker) ###################################
##################################################################################################### #####################################################################################################
# Setting stack of your app to a Container
heroku stack:set container
heroku container:login # Login to the container resistry heroku container:login # Login to the container resistry
git clone https://github.com/heroku/alpinehelloworld.git # Get sample code by cloning into the following repository git clone https://github.com/heroku/alpinehelloworld.git # Get sample code by cloning into the following repository

View File

@ -4,6 +4,212 @@
############################################################################## ##############################################################################
sudo nginx -t # Check syntax sudo nginx -t # Check syntax
sudo systemctl status nginx # nginx current status
sudo systemctl reload nginx # Reload nginx sudo systemctl reload nginx # Reload nginx
sudo service nginx restart # Restart nginx sudo systemctl restart nginx # Restart nginx
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ # Link website sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ # Link website
# *****************************************************************************
# General Settings
# *****************************************************************************
# Ports
server {
# Use HTTP protocol
listen 80;
# Use HTTPS protocol
listen 443 ssl;
# Listen on port 80 using IPv6
listen [::]:80;
# Listen on port 80 using **only** IPv6
listen [::]:80 ipv6only=on;
}
# Domain name (server_name)
server {
# Listen to example.com
server_name example.com;
# Listen to multiple domains
server_name example.com www.example.com;
# Listen to all sub-domains
server_name *.example.com;
# Listen to all top-level domains
server_name example.*;
# Listen to unspecified hostnames (listens to IP address itself)
server_name "";
}
# *****************************************************************************
# Serving Files
# *****************************************************************************
# Static assets (traditional web server)
server {
listen 80;
server_name example.com;
root /path/to/website;
# root /www/data/ for example
# If there's no 'root' inside, it will look for /www/data/index.html
location / {
}
# If there's no 'root' inside, it will look for /www/data/images/index.html
location /images/ {
}
# Since there's 'root' inside, it will look for /www/media/videos/index.html
location /videos/ {
root /www/media;
}
}
# *****************************************************************************
# Redirects
# *****************************************************************************
# 301 Permanent
server {
# Redirect www.example.com to example.com
listen 80;
server_name www.example.com;
return 301 http://example.com$request_uri;
}
server {
# Redirect http to https
listen 80;
server_name example.com;
return 301 https://example.com$request_uri;
}
# 302 Temporary
server {
listen 80;
server_name yourdomain.com;
return 302 http://otherdomain.com;
}
# *****************************************************************************
# Reverse proxy
# *****************************************************************************
# Useful for Node.js, Streamlit, Jupyter, etc
# Basic
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://0.0.0.0:3000;
# where 0.0.0.0:3000 is your Node.js Server bound on 0.0.0.0 listing on port 3000
}
}
# Basic + (upstream)
upstream node_js {
server 0.0.0.0:3000;
# where 0.0.0.0:3000 is your Node.js Server bound on 0.0.0.0 listing on port 3000
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://node_js;
}
}
# Upgraded Connection (useful for applications with support for WebSockets)
upstream node_js {
server 0.0.0.0:3000;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://node_js;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
}
# *****************************************************************************
# HTTPS Protocol
# *****************************************************************************
# The majority of SSL options depend on what your application does or needs
server {
listen 443 ssl;
server_name example.com;
ssl on;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/privkey.pem;
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /path/to/fullchain.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
add_header Strict-Transport-Security max-age=15768000;
}
# Permanent redirect to HTTPS secured domain
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
# You can easily secure you website/app using Let's Encrypt.
# Go https://certbot.eff.org/lets-encrypt/ubuntuxenial-nginx.html for more information
# *****************************************************************************
# Load Balancing
# *****************************************************************************
# Useful for large applications running in multiple instances. Below example is for reverse proxy
upstream node_js {
server 0.0.0.0:3000;
server 0.0.0.0:4000;
server 127.155.142.421;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://node_js;
}
}

View File

@ -87,6 +87,7 @@ J join line below to the current one
cc change (replace) an entire line cc change (replace) an entire line
cw change (replace) to the end of word cw change (replace) to the end of word
C change (replace) to the end of line C change (replace) to the end of line
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)
xp transpose two letters (delete and paste, technically) xp transpose two letters (delete and paste, technically)
@ -118,6 +119,7 @@ x delete current character
X delete previous character X delete previous character
dw delete the current word dw delete the current word
dd delete (cut) a line dd delete (cut) a line
dt' delete until the next ' character on the line (replace ' by any character)
D delete from cursor to end of line D delete from cursor to end of line
:[range]d delete [range] lines :[range]d delete [range] lines
@ -279,6 +281,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
############################################################################## ##############################################################################

View File

@ -4,89 +4,89 @@
### HTML & CSS ### HTML & CSS
- `CSScomb`: Coding style formatter for CSS, Less, SCSS and Saas. - [`CSScomb`](https://marketplace.visualstudio.com/items?itemName=mrmlnc.vscode-csscomb): Coding style formatter for CSS, Less, SCSS and Saas.
- `Puglint`: Linter and style checker for pug. - [`Puglint`](https://marketplace.visualstudio.com/items?itemName=mrmlnc.vscode-puglint): Linter and style checker for pug.
- `Sass`: Indented Sass syntax highlighting, autocomplete & snippets. - [`Sass`](https://marketplace.visualstudio.com/items?itemName=Syler.sass-indented): Indented Sass syntax highlighting, autocomplete & snippets.
- `SCSS IntelliSense`: Advanced autocompletion and refactoring support for SCSS. - [`SCSS IntelliSense`](https://marketplace.visualstudio.com/items?itemName=mrmlnc.vscode-scss): Advanced autocompletion and refactoring support for SCSS.
- `XML Format`: Format XML documents. - [`XML Format`](https://marketplace.visualstudio.com/items?itemName=mikeburgh.xml-format): Format XML documents.
### JavaScript, Node & NPM ### JavaScript, Node & NPM
- `Import Cost`: This extension will display inline in the editor the size of the imported package. - [`Import Cost`](https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost): This extension will display inline in the editor the size of the imported package.
- `ESLint`: Integrates ESLint into VS Code - [`ESLint`](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint): Integrates ESLint into VS Code
- `NPM`: NPM support for VS Code. - [`NPM`](https://marketplace.visualstudio.com/items?itemName=eg2.vscode-npm-script): NPM support for VS Code.
- `NPM Intellisense`: Visual Studio Code plugin that autocompletes NPM modules in import statements. - [`NPM Intellisense`](https://marketplace.visualstudio.com/items?itemName=christian-kohler.npm-intellisense): Visual Studio Code plugin that autocompletes NPM modules in import statements.
- `Version Lens`: Shows the latest version for each package using code lens. - [`Version Lens`](https://marketplace.visualstudio.com/items?itemName=pflannery.vscode-versionlens): Shows the latest version for each package using code lens.
- `Vetur`: Vue tooling for VS Code. - [`Vetur`](https://marketplace.visualstudio.com/items?itemName=octref.vetur): Vue tooling for VS Code.
### PHP ### PHP
- `Better PHPUnit`: A better PHPUnit test runner. - [`Better PHPUnit`](https://marketplace.visualstudio.com/items?itemName=calebporzio.better-phpunit): A better PHPUnit test runner.
- `Laravel Artisan`: Laravel Artisan commands within Visual Studio Code. - [`Laravel Artisan`](https://marketplace.visualstudio.com/items?itemName=ryannaddy.laravel-artisan): Laravel Artisan commands within Visual Studio Code.
- `PHP CS Fixer`: PHP CS Fixer extension for VS Code, php formatter, php code beautify tool. - [`PHP CS Fixer`](https://marketplace.visualstudio.com/items?itemName=junstyle.php-cs-fixer): PHP CS Fixer extension for VS Code, php formatter, php code beautify tool.
- `PHP Doc Comment VSCode Plugin`: Add phpdoc @param and @return tag for selected function signatures. - [`PHP Doc Comment VSCode Plugin`](https://marketplace.visualstudio.com/items?itemName=rexshi.phpdoc-comment-vscode-plugin): Add phpdoc @param and @return tag for selected function signatures.
- `PHP IntelliSense`: Advanced Autocompletion and Refactoring support for PHP. - [`PHP IntelliSense`](https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-intellisense): Advanced Autocompletion and Refactoring support for PHP.
### Git ### Git
- `Git History`: View git log, file history, compare branches or commits. - [`Git History`](https://marketplace.visualstudio.com/items?itemName=donjayamanne.githistory): View git log, file history, compare branches or commits.
- `Gitignore`: A extension for Visual Studio Code that assists you in working with .gitignore files. - [`Gitignore`](https://marketplace.visualstudio.com/items?itemName=codezombiech.gitignore): A extension for Visual Studio Code that assists you in working with .gitignore files.
### Themes ### Themes
- `Material Icon Theme`: Material Design Icons for Visual Studio Code. - [`Material Icon Theme`](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme): Material Design Icons for Visual Studio Code.
- `Palenight Theme`: An elegant and juicy material-like theme for Visual Studio Code. - [`Palenight Theme`](https://marketplace.visualstudio.com/items?itemName=whizkydee.material-palenight-theme): An elegant and juicy material-like theme for Visual Studio Code.
### Handy ### Handy
- `Better comments`: Improve your code commenting by annotating with alert, informational, TODOs, and more! - [`Better comments`](https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments): Improve your code commenting by annotating with alert, informational, TODOs, and more!
- `Debugger for Chrome`: Debug your JavaScript code in the Chrome browser. - [`Debugger for Chrome`](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome): Debug your JavaScript code in the Chrome browser.
- `EditorConfig for VS Code`: EditorConfig Support for Visual Studio Code. - [`EditorConfig for VS Code`](https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig): EditorConfig Support for Visual Studio Code.
- `File Utils`: A convenient way of creating, duplicating, moving, renaming and deleting files and directories. - [`File Utils`](https://marketplace.visualstudio.com/items?itemName=sleistner.vscode-fileutils): A convenient way of creating, duplicating, moving, renaming and deleting files and directories.
- `Final-Newline`: Inserts a final newline when saving the document. - [`Final-Newline`](https://marketplace.visualstudio.com/items?itemName=samverschueren.final-newline): Inserts a final newline when saving the document.
- `Formatting Toggle`: A VS Code extension that allows you to toggle the formatter (Prettier, Beautify, …) ON and OFF with a simple click. - [`Formatting Toggle`](https://marketplace.visualstudio.com/items?itemName=tombonnike.vscode-status-bar-format-toggle): A VS Code extension that allows you to toggle the formatter (Prettier, Beautify, …) ON and OFF with a simple click.
- `Open in Github/Bitbucket...`: Jump to a source code line in Github / Bitbucket, Gitlab, VisualStudio.com - [`Open in Github/Bitbucket...`](https://marketplace.visualstudio.com/items?itemName=ziyasal.vscode-open-in-github): Jump to a source code line in Github / Bitbucket, Gitlab, VisualStudio.com
- `OpenChrome`: Open file with Chrome. - [`OpenChrome`](https://marketplace.visualstudio.com/items?itemName=huazaierli.openchrome&ssr=false#overview): Open file with Chrome.
- `Output Colorizer`: Syntax Highlighting for log files. - [`Output Colorizer`](https://marketplace.visualstudio.com/items?itemName=IBM.output-colorizer): Syntax Highlighting for log files.
- `Prettier - Code formatter`: VS Code plugin for prettier/prettier. - [`Prettier - Code formatter`](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode): VS Code plugin for prettier/prettier.
- `Project Manager`: Easily switch between projects. - [`Project Manager`](https://marketplace.visualstudio.com/items?itemName=alefragnani.project-manager): Easily switch between projects.
- `REST Client`: REST Client for Visual Studio Code. - [`REST Client`](https://marketplace.visualstudio.com/items?itemName=humao.rest-client): REST Client for Visual Studio Code.
- `SVG Viewer`: SVG Viewer for Visual Studio Code. - [`SVG Viewer`](https://marketplace.visualstudio.com/items?itemName=cssho.vscode-svgviewer): SVG Viewer for Visual Studio Code.
- `Terminal`: Terminal for Visual Studio Code. - [`Terminal`](https://marketplace.visualstudio.com/items?itemName=formulahendry.terminal): Terminal for Visual Studio Code.
- `Vue Peek`: Allows peek and goto definition for Vue single-file components. - [`Vue Peek`](https://marketplace.visualstudio.com/items?itemName=dariofuzinato.vue-peek): Allows peek and goto definition for Vue single-file components.
- `VS Live Share`: Real-time collaborative development from the comfort of your favorite tools. - [`VS Live Share`](https://marketplace.visualstudio.com/items?itemName=MS-vsliveshare.vsliveshare): Real-time collaborative development from the comfort of your favorite tools.
- `Wrap Console Log`: Wrap to console.log by word or selection. - [`Wrap Console Log`](https://marketplace.visualstudio.com/items?itemName=midnightsyntax.vscode-wrap-console-log): Wrap to console.log by word or selection.
## My Settings ## My Settings