Full Code of black-shadows/Cheat-Sheets for AI

master 811c97f72101 cached
47 files
1.6 MB
460.8k tokens
1 requests
Download .txt
Showing preview only (1,820K chars total). Download the full file or copy to clipboard to get everything.
Repository: black-shadows/Cheat-Sheets
Branch: master
Commit: 811c97f72101
Files: 47
Total size: 1.6 MB

Directory structure:
gitextract_5wy5wbdt/

├── Angular/
│   └── README.md
├── C++/
│   ├── C++ Syntax.md
│   ├── Data Structures and Algorithms.md
│   └── README.md
├── Command Line/
│   └── README.md
├── Django/
│   └── README.md
├── Elixir/
│   └── README.md
├── Git/
│   └── README.md
├── Golang/
│   ├── README.md
│   └── golang_refcard.odt
├── Java/
│   ├── README.md
│   └── todo.md
├── JavaScript/
│   ├── README.md
│   ├── _config.yml
│   └── translations/
│       ├── fr-FR.md
│       ├── ja-JP.md
│       ├── pl_PL.md
│       ├── pt-BR.md
│       ├── ru-RU.md
│       ├── th-TH.md
│       ├── zh-CN.md
│       └── zh-TW.md
├── Kotlin/
│   └── README.md
├── MATLAB/
│   └── README.md
├── Markdown/
│   └── README.md
├── MongoDB/
│   ├── README.md
│   └── sql_mongo_comparison.md
├── Oracle SQL/
│   ├── README.md
│   └── SQL_commands.md
├── PHP/
│   └── README.md
├── Perl/
│   └── README.md
├── Python/
│   ├── CODE_OF_CONDUCT.md
│   ├── CONTRIBUTING.md
│   ├── README.md
│   ├── _config.yml
│   ├── blog_files/
│   │   ├── about.md
│   │   └── pysheet.md
│   ├── pyproject.toml
│   └── python_cheat_sheet.ipynb
├── README.md
├── React/
│   ├── README.md
│   └── react-placar.md
├── Ruby/
│   └── README.md
├── Ruby on Rails/
│   └── README.md
├── Scala/
│   └── README.md
├── Swift/
│   └── README.md
└── TypeScript/
    └── README.md

================================================
FILE CONTENTS
================================================

================================================
FILE: Angular/README.md
================================================
# Angular Cheatsheet

##### Table of Contents  
[Basics](#basics)  
[Loop](#loop)  
[Html](#html)  
[Directives](#directives)  
[Services](#services)  
[Routing](#routing)  
[Filters](#filters)  

## Basics
**Setup**  
0. You can use the official [Angular Seed Project](https://github.com/angular/angular-seed) for quick startup.  
1. Create a new module named myApp
```javascript
// ja > App.js
var app = angular.module("myApp", []);
```
2. add a directive: it tells AngularJS that the myApp module will live within the `<body>` scope (or the whole page, `<head>`) 
```html
<!-- index.html -->
<head ng-app="myApp"> <!-- or -->
<body ng-app="myApp">
```
See: [more info on ng-app](https://docs.angularjs.org/api/ng/directive/ngApp)  
This is called “Bootstrapping”. Sometimes you want to [do it manually](https://docs.angularjs.org/guide/bootstrap#manual-initialization) (if you have multiple Angular apps for instance).
3. Create a new controller: manages the app's data.
```javascript
// js > controllers > MainController.js
app.controller('MainController', ['$scope', function($scope) { 
  $scope.title = 'Top Sellers in Books'; 
}]);
```
4. ng-controller is a directive that defines the controller scope
```html
<div class="main" ng-controller="MainController">
  <h1>{{ title }}</h1>
</div>
```
We access $scope.title using {{ title }}. That’s an expression: used to display values on the page.

### Namings
**Binding** –– {{ ... }}  
**Expressions** –– something + '!'  
**Directives** ––  
**Template** –– (the part of the view containing the bindings and presentation logic) acts as a blueprint for how our data should be organized and presented to the user.  
**Controller** –– provides the context in which the bindings are evaluated and applies behavior and logic to our template.  
**Model** –– What the user sees after the page is fully rendered  
**Module** –– Child on Angular (usually it is the App in an Angular point of view)  
**Components** –– A combination of template + controller with an isolated scope (= no prototypal inheritance and no risk of our component affecting other parts of the application or vice versa) ([Docs](https://docs.angularjs.org/guide/component))
**DI / dependency injection** –– https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection  


### misc  
**Price**
```html
<p class="price">{{ product.price | currency }}</p>
```
AngularJS gets the value of product.price. It sends this number into the currency filter. The pipe symbol (|) takes the output on the left and "pipes" it to the right. The filter outputs a formatted currency with the dollar sign and the correct decimal places.  

**Date**
```javascript
pubdate: new Date('2014', '03', '08')
```
```html
<p class="date">{{ product.pubdate | date | uppercase }}</p>
```

## Loop
```javascript
$scope.products = [ 
  { 
    name: 'The Book of Trees', 
    price: 19, 
    pubdate: new Date('2014', '03', '08'), 
    cover: 'img/the-book-of-trees.jpg' 
  }, 
  { 
    name: 'Program or be Programmed', 
    price: 8, 
    pubdate: new Date('2013', '08', '01'), 
    cover: 'img/program-or-be-programmed.jpg' 
  }
]
```
```html
<div ng-repeat="product in products"> 
  <img ng-src="{{ product.cover }}">
  <p class="title">{{ product.name }}</p> 
  <p class="price">{{ product.price | currency }}</p> 
  <p class="date">{{ product.pubdate | date }}</p> 
  <p class="likes" ng-click="plusOne($index)">{{ product.likes }}</p>
</div>
```

## Html
```html
<!-- loops trough every product in products -->
<div ng-repeat="product in products"> 
  
<!-- include the source -->
<img ng-src="{{ product.cover }}"> 

<!-- ng-click is a directive that adds an onclick event. plusOne is the name of the function. $index passes the product number (in a loop). {{ product.likes }} displays the value -->
<p ng-click="plusOne($index)">{{ product.likes }}</p>
```

## Directives
in js/directives/appInfo.js
```javascript
app.directive('appInfo', function() { 
  return { 
    restrict: 'E', // specifies how directive will be used in view. 'E' means it will be used as a new HTML element.
    scope: { 
      info: '=' // specifies that we will pass information into this directive through an attribute named info. The = tells the directive to look for an attribute named info in the <app-info> element, like this: <app-info info="shutterbugg"></app-info>
    },          // The data in info becomes available to use in the template given by templateURL
    templateUrl: 'js/directives/appInfo.html', // specifies the HTML to use in order to display the data in scope.info. Here we use the HTML in js/directives/appInfo.html.
    link: function(scope, element, attrs) { // scope refers to the directive's scope. Any new properties attached to $scope will become available to use in the directive's template. element refers to the directive's HTML element. attrs contains the element's attributes. 
            scope.buttonText = "Install", // property buttonText
            scope.installed = false, // property installed

            scope.download = function() { // function download() 
              element.toggleClass('btn-active'); 
              if(scope.installed) { 
                scope.buttonText = "Install"; 
                scope.installed = false; 
              } else { 
                scope.buttonText = "Uninstall"; 
                scope.installed = true; 
              } 
            } 
          }

  }; 
});
```
in js/directives/appInfo.html
```html
<!-- define HTML to display details about app. Use expressions and filters to display data. -->
<img ng-src="{{ info.icon }}"> 
<h2>{{ info.title }}</h2> 
<p>{{ info.developer }}</p> 
<p>{{ info.price | currency }}</p>
<!-- part of link: function -->
<button ng-click="download()"> 
  {{ buttonText }} 
</button>
```
in index.html
```html
<!-- pass in objects from the controller's scope ($scope.shutterbugg) into the <app-info> element's info attribute so that it displays. -->
<app-info info="shutterbugg"></app-info>
```

## Services
**js > services > forecast.js**
```javascript
app.factory('forecast', ['$http', function($http) { // app.factory to create a new service named forecast + AngularJS's built-in $http to fetch JSON from the server
  return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/forecast-api/forecast.json') // $http construct an HTTP GET request for the weather data (a json list from codecademy).
            .success(function(data) { // If the request succeeds, the weather data is returned; 
              return data; 
            }) 
            .error(function(err) { // otherwise the error info is returned.
              return err; 
            }); 
}]);
```
**js > controllers > MainController.js**
```javascript
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) { // add forecast into MainController as dependency so that it's available to use.
  forecast.success(function(data) { // to asynchronously fetch the weather data from server
    $scope.fiveDay = data; // store it into $scope.fiveDay 
  }); 
}]);
// any properties attached to $scope become available to use in the view
```
**index.html**
```html
<div class="main" ng-controller="MainController">
  <h1>{{ fiveDay.city_name }}</h1>
</div>
```

## Routing
**app.config.js**
```javascript
// new
angular.
  module('phonecatApp').
  config(['$locationProvider', '$routeProvider', // the services we use
    function config($locationProvider, $routeProvider) {
      $locationProvider.hashPrefix('!');

      $routeProvider. // to define the application routes
        when('/phones', { // to map the URL /phones to
          template: '<phone-list></phone-list>'
        }).
        when('/phones/:phoneId', { // mapp URL to phones + variable part named id to the URL
          template: '<phone-detail></phone-detail>'
        }).
        otherwise('/phones');
    }
  ]);
```
**phone-detail/phone-detail.module.js**
```javascript
// new
angular.module('phoneDetail', [
  'ngRoute'
]);
```
**phone-detail/phone-detail.component.js**
```javascript
// new
angular.
  module('phoneDetail').
  component('phoneDetail', {
    template: 'TBD: Detail view for <span>{{$ctrl.phoneId}}</span>',
    controller: ['$routeParams',
      function PhoneDetailController($routeParams) {
        this.phoneId = $routeParams.phoneId;
      }
    ]
  });
```
**js > app.js**
```javascript
// old
app.config(function ($routeProvider) { 
  $routeProvider 
    .when('/', { 
      controller: 'HomeController', // to the controller HomeController 
      templateUrl: 'views/home.html' // and the template home.html
    })
    .when('/photos/:id', { 
  		controller: 'PhotoController',
    	templateUrl: 'views/photo.html'
  	})
    .otherwise({ // Otherwise if a user accidentally visits a URL other than /
      redirectTo: '/' // we just redirect to /
    }); 
});
```
**js > controllers > HomeController**
```javascript
// old
app.controller('HomeController', ['$scope', 'photos', function($scope, photos) { // use photos service
  photos.success(function(data) {
    $scope.photos = data;
  });
}]);
```
**js > controllers > PhotoController**
```javascript
// old
// $routeParams to retrieve id from the URL by using $routeParams.id
// Notice injected both $routeParams and the photos service into the dependency array to make them available to use inside the controller.
app.controller('PhotoController', ['$scope', 'photos', '$routeParams', function($scope, photos, $routeParams) {
  photos.success(function(data) { // photos service to fetch the array of photos from the server
    $scope.detail = data[$routeParams.id]; // $routeParams.id to access the specific photo by its index
  });
}]);
```
**js > services > photos**
```javascript
// old
// fetch the array of all photos and stores it into $scope.photos
app.factory('photos', ['$http', function($http) {
  return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/photos-api/photos.json')
         .success(function(data) {
           return data;
         })
         .error(function(data) {
           return data;
         });
}]);
```
**views > home.html**
```html
<div class="item col-md-4" ng-repeat="photo in photos">
  <a href="#/photos/{{$index}}">
    <img class="img-responsive" ng-src="{{ photo.url }}">
    <p class="author">by {{ photo.author }}</p>
  </a>
</div>
```
**views > photo.html**
```html
<img ng-src="{{ detail.url }}">
```
**index.html**
```html
<!-- ow when a user visits /, a view will be constructed by injecting home.html into the <div ng-view></div> -->
<div ng-view></div>
```

## Filters
```javascript
detail.upvotes | number // 1,266
detail.pubdate | date // Oct 18, 2014 

```
**Filter an Array**  
```html
Search: <input type="text" data-ng-model="$ctrl.query">
Search by Name: <input type="text" data-ng-model="$ctrl.query.name"> <!-- save input in $ctrl.query -->
<p>Total number of phones: {{$ctrl.phones.length}}</p>
<ul class="phones">
  <li data-ng-repeat="phone in $ctrl.phones | filter:$ctrl.query"> <!-- use $ctrl.query as filter to only show matching elements -->
    <span>{{phone.name}}</span>
    <p>{{phone.snippet}}</p>
  </li>
</ul>
```
```html
<p>
  Sort by:
  <select ng-model="$ctrl.orderProp"> <!-- save selection in $ctrl.orderProp -->
    <option value="name">Alphabetical</option> <!-- save selection in $ctrl.orderProp.name -->
    <option value="age">Newest</option> <!-- save selection in $ctrl.orderProp.age -->
    <option value="-age">Oldest</option> <!-- place - in front to reverse -->
  </select>
</p>
<ul class="phones">
  <li data-ng-repeat="phone in $ctrl.phones | orderBy:$ctrl.orderProp"> <!-- use $ctrl.orderProp as filter to order the list -->
    <!-- if a value is not available it will return to the default -->
    <span>{{phone.name}}</span>
    <p>{{phone.snippet}}</p>
  </li>
</ul>
```

<h1 class="no-toc">More Points</h1>

<div id="cheatsheet">
<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Bootstrapping</th>
<th><p><code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';</code>
</p>
</th>
</tr>
<tr>
<td><code><b>platformBrowserDynamic().bootstrapModule</b>(AppModule);</code></td>
<td><p>Bootstraps the app, using the root component from the specified <code>NgModule</code>. </p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>NgModules</th>
<th><p><code>import { NgModule } from '@angular/core';</code>
</p>
</th>
</tr>
<tr>
<td><code>@<b>NgModule</b>({ declarations: ..., imports: ...,<br>     exports: ..., providers: ..., bootstrap: ...})<br>class MyModule {}</code></td>
<td><p>Defines a module that contains components, directives, pipes, and providers.</p>
</td>
</tr><tr>
<td><code><b>declarations:</b> [MyRedComponent, MyBlueComponent, MyDatePipe]</code></td>
<td><p>List of components, directives, and pipes that belong to this module.</p>
</td>
</tr><tr>
<td><code><b>imports:</b> [BrowserModule, SomeOtherModule]</code></td>
<td><p>List of modules to import into this module. Everything from the imported modules
is available to <code>declarations</code> of this module.</p>
</td>
</tr><tr>
<td><code><b>exports:</b> [MyRedComponent, MyDatePipe]</code></td>
<td><p>List of components, directives, and pipes visible to modules that import this module.</p>
</td>
</tr><tr>
<td><code><b>providers:</b> [MyService, { provide: ... }]</code></td>
<td><p>List of dependency injection providers visible both to the contents of this module and to importers of this module.</p>
</td>
</tr><tr>
<td><code><b>entryComponents:</b> [SomeComponent, OtherComponent]</code></td>
<td><p>List of components not referenced in any reachable template, for example dynamically created from code.</p></td>
</tr><tr>
<td><code><b>bootstrap:</b> [MyAppComponent]</code></td>
<td><p>List of components to bootstrap when this module is bootstrapped.</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Template syntax</th>
<th></th>
</tr>
<tr>
<td><code>&lt;input <b>[value]</b>="firstName"&gt;</code></td>
<td><p>Binds property <code>value</code> to the result of expression <code>firstName</code>.</p>
</td>
</tr><tr>
<td><code>&lt;div <b>[attr.role]</b>="myAriaRole"&gt;</code></td>
<td><p>Binds attribute <code>role</code> to the result of expression <code>myAriaRole</code>.</p>
</td>
</tr><tr>
<td><code>&lt;div <b>[class.extra-sparkle]</b>="isDelightful"&gt;</code></td>
<td><p>Binds the presence of the CSS class <code>extra-sparkle</code> on the element to the truthiness of the expression <code>isDelightful</code>.</p>
</td>
</tr><tr>
<td><code>&lt;div <b>[style.width.px]</b>="mySize"&gt;</code></td>
<td><p>Binds style property <code>width</code> to the result of expression <code>mySize</code> in pixels. Units are optional.</p>
</td>
</tr><tr>
<td><code>&lt;button <b>(click)</b>="readRainbow($event)"&gt;</code></td>
<td><p>Calls method <code>readRainbow</code> when a click event is triggered on this button element (or its children) and passes in the event object.</p>
</td>
</tr><tr>
<td><code>&lt;div title="Hello <b>{{ponyName}}</b>"&gt;</code></td>
<td><p>Binds a property to an interpolated string, for example, "Hello Seabiscuit". Equivalent to:
<code>&lt;div [title]="'Hello ' + ponyName"&gt;</code></p>
</td>
</tr><tr>
<td><code>&lt;p&gt;Hello <b>{{ponyName}}</b>&lt;/p&gt;</code></td>
<td><p>Binds text content to an interpolated string, for example, "Hello Seabiscuit".</p>
</td>
</tr><tr>
<td><code>&lt;my-cmp <b>[(title)]</b>="name"&gt;</code></td>
<td><p>Sets up two-way data binding. Equivalent to: <code>&lt;my-cmp [title]="name" (titleChange)="name=$event"&gt;</code></p>
</td>
</tr><tr>
<td><code>&lt;video <b>#movieplayer</b> ...&gt;<br>  &lt;button <b>(click)</b>="movieplayer.play()"&gt;<br>&lt;/video&gt;</code></td>
<td><p>Creates a local variable <code>movieplayer</code> that provides access to the <code>video</code> element instance in data-binding and event-binding expressions in the current template.</p>
</td>
</tr><tr>
<td><code>&lt;p <b>*myUnless</b>="myExpression"&gt;...&lt;/p&gt;</code></td>
<td><p>The <code>*</code> symbol turns the current element into an embedded template. Equivalent to:
<code>&lt;ng-template [myUnless]="myExpression"&gt;&lt;p&gt;...&lt;/p&gt;&lt;/ng-template&gt;</code></p>
</td>
</tr><tr>
<td><code>&lt;p&gt;Card No.: <b>{{cardNumber | myCardNumberFormatter}}</b>&lt;/p&gt;</code></td>
<td><p>Transforms the current value of expression <code>cardNumber</code> via the pipe called <code>myCardNumberFormatter</code>.</p>
</td>
</tr><tr>
<td><code>&lt;p&gt;Employer: <b>{{employer?.companyName}}</b>&lt;/p&gt;</code></td>
<td><p>The safe navigation operator (<code>?</code>) means that the <code>employer</code> field is optional and if <code>undefined</code>, the rest of the expression should be ignored.</p>
</td>
</tr><tr>
<td><code>&lt;<b>svg:</b>rect x="0" y="0" width="100" height="100"/&gt;</code></td>
<td><p>An SVG snippet template needs an <code>svg:</code> prefix on its root element to disambiguate the SVG element from an HTML component.</p>
</td>
</tr><tr>
<td><code>&lt;<b>svg</b>&gt;<br>  &lt;rect x="0" y="0" width="100" height="100"/&gt;<br>&lt;/<b>svg</b>&gt;</code></td>
<td><p>An <code>&lt;svg&gt;</code> root element is detected as an SVG element automatically, without the prefix.</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Built-in directives</th>
<th><p><code>import { CommonModule } from '@angular/common';</code>
</p>
</th>
</tr>
<tr>
<td><code>&lt;section <b>*ngIf</b>="showSection"&gt;</code></td>
<td><p>Removes or recreates a portion of the DOM tree based on the <code>showSection</code> expression.</p>
</td>
</tr><tr>
<td><code>&lt;li <b>*ngFor</b>="let item of list"&gt;</code></td>
<td><p>Turns the li element and its contents into a template, and uses that to instantiate a view for each item in list.</p>
</td>
</tr><tr>
<td><code>&lt;div <b>[ngSwitch]</b>="conditionExpression"&gt;<br>  &lt;ng-template <b>[<b>ngSwitchCase</b>]</b>="case1Exp"&gt;...&lt;/ng-template&gt;<br>  &lt;ng-template <b>ngSwitchCase</b>="case2LiteralString"&gt;...&lt;/ng-template&gt;<br>  &lt;ng-template <b>ngSwitchDefault</b>&gt;...&lt;/ng-template&gt;<br>&lt;/div&gt;</code></td>
<td><p>Conditionally swaps the contents of the div by selecting one of the embedded templates based on the current value of <code>conditionExpression</code>.</p>
</td>
</tr><tr>
<td><code>&lt;div <b>[ngClass]</b>="{'active': isActive, 'disabled': isDisabled}"&gt;</code></td>
<td><p>Binds the presence of CSS classes on the element to the truthiness of the associated map values. The right-hand expression should return {class-name: true/false} map.</p>
</td>
</tr>
<tr>
<td><code>&lt;div <b>[ngStyle]</b>="{'property': 'value'}"&gt;</code><br><code>&lt;div <b>[ngStyle]</b>="dynamicStyles()"&gt;</code></td>
<td><p>Allows you to assign styles to an HTML element using CSS. You can use CSS directly, as in the first example, or you can call a method from the component.</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Forms</th>
<th><p><code>import { FormsModule } from '@angular/forms';</code>
</p>
</th>
</tr>
<tr>
<td><code>&lt;input <b>[(ngModel)]</b>="userName"&gt;</code></td>
<td><p>Provides two-way data-binding, parsing, and validation for form controls.</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Class decorators</th>
<th><p><code>import { Directive, ... } from '@angular/core';</code>
</p>
</th>
</tr>
<tr>
<td><code><b>@Component({...})</b><br>class MyComponent() {}</code></td>
<td><p>Declares that a class is a component and provides metadata about the component.</p>
</td>
</tr><tr>
<td><code><b>@Directive({...})</b><br>class MyDirective() {}</code></td>
<td><p>Declares that a class is a directive and provides metadata about the directive.</p>
</td>
</tr><tr>
<td><code><b>@Pipe({...})</b><br>class MyPipe() {}</code></td>
<td><p>Declares that a class is a pipe and provides metadata about the pipe.</p>
</td>
</tr><tr>
<td><code><b>@Injectable()</b><br>class MyService() {}</code></td>
<td><p>Declares that a class has dependencies that should be injected into the constructor when the dependency injector is creating an instance of this class.
</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Directive configuration</th>
<th><p><code>@Directive({ property1: value1, ... })</code>
</p>
</th>
</tr>
<tr>
<td><code><b>selector:</b> '.cool-button:not(a)'</code></td>
<td><p>Specifies a CSS selector that identifies this directive within a template. Supported selectors include <code>element</code>,
<code>[attribute]</code>, <code>.class</code>, and <code>:not()</code>.</p>
<p>Does not support parent-child relationship selectors.</p>
</td>
</tr><tr>
<td><code><b>providers:</b> [MyService, { provide: ... }]</code></td>
<td><p>List of dependency injection providers for this directive and its children.</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Component configuration</th>
<th><p>
<code>@Component</code> extends <code>@Directive</code>,
so the <code>@Directive</code> configuration applies to components as well</p>
</th>
</tr>
<tr>
<td><code><b>moduleId:</b> module.id</code></td>
<td><p>If set, the <code>templateUrl</code> and <code>styleUrl</code> are resolved relative to the component.</p>
</td>
</tr><tr>
<td><code><b>viewProviders:</b> [MyService, { provide: ... }]</code></td>
<td><p>List of dependency injection providers scoped to this component's view.</p>
</td>
</tr><tr>
<td><code><b>template:</b> 'Hello {{name}}'<br><b>templateUrl:</b> 'my-component.html'</code></td>
<td><p>Inline template or external template URL of the component's view.</p>
</td>
</tr><tr>
<td><code><b>styles:</b> ['.primary {color: red}']<br><b>styleUrls:</b> ['my-component.css']</code></td>
<td><p>List of inline CSS styles or external stylesheet URLs for styling the component’s view.</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Class field decorators for directives and components</th>
<th><p><code>import { Input, ... } from '@angular/core';</code>
</p>
</th>
</tr>
<tr>
<td><code><b>@Input()</b> myProperty;</code></td>
<td><p>Declares an input property that you can update via property binding (example:
<code>&lt;my-cmp [myProperty]="someExpression"&gt;</code>).</p>
</td>
</tr><tr>
<td><code><b>@Output()</b> myEvent = new EventEmitter();</code></td>
<td><p>Declares an output property that fires events that you can subscribe to with an event binding (example: <code>&lt;my-cmp (myEvent)="doSomething()"&gt;</code>).</p>
</td>
</tr><tr>
<td><code><b>@HostBinding('class.valid')</b> isValid;</code></td>
<td><p>Binds a host element property (here, the CSS class <code>valid</code>) to a directive/component property (<code>isValid</code>).</p>
</td>
</tr><tr>
<td><code><b>@HostListener('click', ['$event'])</b> onClick(e) {...}</code></td>
<td><p>Subscribes to a host element event (<code>click</code>) with a directive/component method (<code>onClick</code>), optionally passing an argument (<code>$event</code>).</p>
</td>
</tr><tr>
<td><code><b>@ContentChild(myPredicate)</b> myChildComponent;</code></td>
<td><p>Binds the first result of the component content query (<code>myPredicate</code>) to a property (<code>myChildComponent</code>) of the class.</p>
</td>
</tr><tr>
<td><code><b>@ContentChildren(myPredicate)</b> myChildComponents;</code></td>
<td><p>Binds the results of the component content query (<code>myPredicate</code>) to a property (<code>myChildComponents</code>) of the class.</p>
</td>
</tr><tr>
<td><code><b>@ViewChild(myPredicate)</b> myChildComponent;</code></td>
<td><p>Binds the first result of the component view query (<code>myPredicate</code>) to a property (<code>myChildComponent</code>) of the class. Not available for directives.</p>
</td>
</tr><tr>
<td><code><b>@ViewChildren(myPredicate)</b> myChildComponents;</code></td>
<td><p>Binds the results of the component view query (<code>myPredicate</code>) to a property (<code>myChildComponents</code>) of the class. Not available for directives.</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Directive and component change detection and lifecycle hooks</th>
<th><p>(implemented as class methods)
</p>
</th>
</tr>
<tr>
<td><code><b>constructor(myService: MyService, ...)</b> { ... }</code></td>
<td><p>Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.</p>
</td>
</tr><tr>
<td><code><b>ngOnChanges(changeRecord)</b> { ... }</code></td>
<td><p>Called after every change to input properties and before processing content or child views.</p>
</td>
</tr><tr>
<td><code><b>ngOnInit()</b> { ... }</code></td>
<td><p>Called after the constructor, initializing input properties, and the first call to <code>ngOnChanges</code>.</p>
</td>
</tr><tr>
<td><code><b>ngDoCheck()</b> { ... }</code></td>
<td><p>Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.</p>
</td>
</tr><tr>
<td><code><b>ngAfterContentInit()</b> { ... }</code></td>
<td><p>Called after <code>ngOnInit</code> when the component's or directive's content has been initialized.</p>
</td>
</tr><tr>
<td><code><b>ngAfterContentChecked()</b> { ... }</code></td>
<td><p>Called after every check of the component's or directive's content.</p>
</td>
</tr><tr>
<td><code><b>ngAfterViewInit()</b> { ... }</code></td>
<td><p>Called after <code>ngAfterContentInit</code> when the component's views and child views / the view that a directive is in has been initialized.</p>
</td>
</tr><tr>
<td><code><b>ngAfterViewChecked()</b> { ... }</code></td>
<td><p>Called after every check of the component's views and child views / the view that a directive is in.</p>
</td>
</tr><tr>
<td><code><b>ngOnDestroy()</b> { ... }</code></td>
<td><p>Called once, before the instance is destroyed.</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Dependency injection configuration</th>
<th></th>
</tr>
<tr>
<td><code>{ <b>provide</b>: MyService, <b>useClass</b>: MyMockService }</code></td>
<td><p>Sets or overrides the provider for <code>MyService</code> to the <code>MyMockService</code> class.</p>
</td>
</tr><tr>
<td><code>{ <b>provide</b>: MyService, <b>useFactory</b>: myFactory }</code></td>
<td><p>Sets or overrides the provider for <code>MyService</code> to the <code>myFactory</code> factory function.</p>
</td>
</tr><tr>
<td><code>{ <b>provide</b>: MyValue, <b>useValue</b>: 41 }</code></td>
<td><p>Sets or overrides the provider for <code>MyValue</code> to the value <code>41</code>.</p>
</td>
</tr>
</tbody></table>

<table class="is-full-width is-fixed-layout">
<tbody><tr>
<th>Routing and navigation</th>
<th><p><code>import { Routes, RouterModule, ... } from '@angular/router';</code>
</p>
</th>
</tr>
<tr>
<td><code>const routes: <b>Routes</b> = [<br>  { path: '', component: HomeComponent },<br>  { path: 'path/:routeParam', component: MyComponent },<br>  { path: 'staticPath', component: ... },<br>  { path: '**', component: ... },<br>  { path: 'oldPath', redirectTo: '/staticPath' },<br>  { path: ..., component: ..., data: { message: 'Custom' } }<br>]);<br><br>const routing = RouterModule.forRoot(routes);</code></td>
<td><p>Configures routes for the application. Supports static, parameterized, redirect, and wildcard routes. Also supports custom route data and resolve.</p>
</td>
</tr><tr>
<td><code><br>&lt;<b>router-outlet</b>&gt;&lt;/<b>router-outlet</b>&gt;<br>&lt;<b>router-outlet</b> name="aux"&gt;&lt;/<b>router-outlet</b>&gt;<br></code></td>
<td><p>Marks the location to load the component of the active route.</p>
</td>
</tr><tr>
<td><code><br>&lt;a routerLink="/path"&gt;<br>&lt;a <b>[routerLink]</b>="[ '/path', routeParam ]"&gt;<br>&lt;a <b>[routerLink]</b>="[ '/path', { matrixParam: 'value' } ]"&gt;<br>&lt;a <b>[routerLink]</b>="[ '/path' ]" [queryParams]="{ page: 1 }"&gt;<br>&lt;a <b>[routerLink]</b>="[ '/path' ]" fragment="anchor"&gt;<br></code></td>
<td><p>Creates a link to a different view based on a route instruction consisting of a route path, required and optional parameters, query parameters, and a fragment. To navigate to a root route, use the <code>/</code> prefix; for a child route, use the <code>./</code>prefix; for a sibling or parent, use the <code>../</code> prefix.</p>
</td>
</tr><tr>
<td><code>&lt;a [routerLink]="[ '/path' ]" routerLinkActive="active"&gt;</code></td>
<td><p>The provided classes are added to the element when the <code>routerLink</code> becomes the current active route.</p>
</td>
</tr><tr>
<td><code>class <b>CanActivate</b>Guard implements <b>CanActivate</b> {<br>    canActivate(<br>      route: ActivatedRouteSnapshot,<br>      state: RouterStateSnapshot<br>    ): Observable&lt;boolean&gt;|Promise&lt;boolean&gt;|boolean { ... }<br>}<br><br>{ path: ..., canActivate: [<b>CanActivate</b>Guard] }</code></td>
<td><p>An interface for defining a class that the router should call first to determine if it should activate this component. Should return a boolean or an Observable/Promise that resolves to a boolean.</p>
</td>
</tr><tr>
<td><code>class <b>CanDeactivate</b>Guard implements <b>CanDeactivate</b>&lt;T&gt; {<br>    canDeactivate(<br>      component: T,<br>      route: ActivatedRouteSnapshot,<br>      state: RouterStateSnapshot<br>    ): Observable&lt;boolean&gt;|Promise&lt;boolean&gt;|boolean { ... }<br>}<br><br>{ path: ..., canDeactivate: [<b>CanDeactivate</b>Guard] }</code></td>
<td><p>An interface for defining a class that the router should call first to determine if it should deactivate this component after a navigation. Should return a boolean or an Observable/Promise that resolves to a boolean.</p>
</td>
</tr><tr>
<td><code>class <b>CanActivateChild</b>Guard implements <b>CanActivateChild</b> {<br>    canActivateChild(<br>      route: ActivatedRouteSnapshot,<br>      state: RouterStateSnapshot<br>    ): Observable&lt;boolean&gt;|Promise&lt;boolean&gt;|boolean { ... }<br>}<br><br>{ path: ..., canActivateChild: [CanActivateGuard],<br>    children: ... }</code></td>
<td><p>An interface for defining a class that the router should call first to determine if it should activate the child route. Should return a boolean or an Observable/Promise that resolves to a boolean.</p>
</td>
</tr><tr>
<td><code>class <b>Resolve</b>Guard implements <b>Resolve</b>&lt;T&gt; {<br>    resolve(<br>      route: ActivatedRouteSnapshot,<br>      state: RouterStateSnapshot<br>    ): Observable&lt;any&gt;|Promise&lt;any&gt;|any { ... }<br>}<br><br>{ path: ..., resolve: [<b>Resolve</b>Guard] }</code></td>
<td><p>An interface for defining a class that the router should call first to resolve route data before rendering the route. Should return a value or an Observable/Promise that resolves to a value.</p>
</td>
</tr><tr>
<td><code>class <b>CanLoad</b>Guard implements <b>CanLoad</b> {<br>    canLoad(<br>      route: Route<br>    ): Observable&lt;boolean&gt;|Promise&lt;boolean&gt;|boolean { ... }<br>}<br><br>{ path: ..., canLoad: [<b>CanLoad</b>Guard], loadChildren: ... }</code></td>
<td><p>An interface for defining a class that the router should call first to check if the lazy loaded module should be loaded. Should return a boolean or an Observable/Promise that resolves to a boolean.</p>
</td>
</tr>
</tbody></table>
</div>


================================================
FILE: C++/C++ Syntax.md
================================================
# C++ Syntax Cheat Sheet

## Table of Contents

<!-- TOC depthFrom:1 depthTo:6 withLinks:1 updateOnSave:0 orderedList:0 -->

- [C++ Syntax Cheat Sheet](#c-syntax-cheat-sheet)
	- [Table of Contents](#table-of-contents)
	- [1.0 C++ Classes](#10-c-classes)
		- [1.1 Class Syntax](#11-class-syntax)
			- [1.1.1 Class Declaration (`.h` file)](#111-class-declaration-h-file)
			- [1.1.2 Class Definition (`.cpp` file)](#112-class-definition-cpp-file)
			- [1.1.3 Class Utilization (Another `.cpp` file)](#113-class-utilization-another-cpp-file)
			- [1.1.4 Getters and Setters](#114-getters-and-setters)
		- [1.2 Inheritance](#12-inheritance)
			- [1.2.1 `Rectangle` Declaration (`.h` file)](#121-rectangle-declaration-h-file)
			- [1.2.2 `Rectangle` Definition (`.cpp` file)](#122-rectangle-definition-cpp-file)
			- [1.2.3 `Rectangle` Utilization (Another `.cpp` file)](#123-rectangle-utilization-another-cpp-file)
		- [1.3 Polymorphism](#13-polymorphism)
		- [1.4 Templates](#14-templates)
		- [1.5 Constructor/Destructor/Copy Constructor](#15-constructordestructorcopy-constructor)
			- [1.5.1 Use of `explicit` in Constructors](#151-use-of-explicit-in-constructors)
		- [1.6 Initialization Lists](#16-initialization-lists)
		- [1.7 Operator Overloading](#17-operator-overloading)
	- [2.0 General C++ Syntax](#20-general-c-syntax)
		- [2.1 Namespaces](#21-namespaces)
		- [2.2 References/Pointers](#22-referencespointers)
		- [2.3 Keywords](#23-keywords)
			- [2.3.1 `const`](#231-const)
			- [2.3.2 `volatile`](#232-volatile)
			- [2.3.3 `inline`](#233-inline)
		- [2.4 Strings (find, erase, etc)](#24-strings-find-erase-etc)
		- [2.5 Iterators](#25-iterators)
		- [2.6 Exceptions](#26-exceptions)

<!-- /TOC -->


## 1.0 C++ Classes
### 1.1 Class Syntax
#### 1.1.1 Class Declaration (`.h` file)
Here's a simple class representing a polygon, a shape with any number of sides.

The class *declaration* typically goes in the `.h` file. The *declaration* gives the class name, any classes it may extend, declares the members and methods, and declares which members/methods are public, private, or protected.
```c++
class Polygon {

// Private members and methods are only accessible via methods in the class definition
// Another option is 'protected', which are members and methods only accessible in the class definition or by classes who extend this class
private:
    int num_sides;    	// Number of sides
    std::string name    // Name of the polygon

// Public members and methods are accessible to anyone who creates an instance of the class
public:
    // Constructors
    Polygon(const int num_sides, const std::string &name);  // <--- This constructor takes the number of sides and name as arguments

    // Getters and Setters
    const int GetNumSides(void) const;
    void SetNumSides(const int num_sides);

    const std::string & GetName(void) const;
    void SetName(const std::string &name);
    
}; // <--- Don't forget the semicolon!
```

#### 1.1.2 Class Definition (`.cpp` file)
```c++
#include "Polygon.h"    // <--- Obtains the class declaration

// Constructor
// You must scope the method definitions with the class name (Polygon::)
Polygon::Polygon(const int num_sides, const std::string &name) {
    this->num_sides = num_sides;	// 'this' refers to the instance of the class. Members are accessed via pointers
    this->name = name;
}

// Get the number of sides
const int Polygon::GetNumSides(void) const {
    return this->num_sides;
}

// Set the number of sides
void Polygon::SetNumSides(const int num_sides) {
    this->num_sides = num_sides;
}

// Get the polygon name
const std::string & Polygon::GetName(void) const {
    return this->name;
}

// Set the polygon name
void Polygon::SetName(const std::string &name) {
    this->name = name;
}
```

#### 1.1.3 Class Utilization (Another `.cpp` file)
```c++
#include <string>
#include "Polygon.h"    // <--- Obtains the class declaration

int main(int argc, char *argv[]) {
    // Create a polygon with 4 sides and the name "Rectangle"
    Polygon polygon = Polygon(4, "Rectangle");

    // Check number of sides -- Prints "Rectangle has 4 sides"
    std::cout << polygon.GetName() << " has " << polygon.GetNumSides() << " sides"<< std::endl;

    // Change number of sides to 3 and name to "Triangle"
    polygon.SetNumSides(3);
    polygon.SetName("Triangle");
}
```

#### 1.1.4 Getters and Setters
A shortcut often used for Getters/Setters is to define them in the class declaration (`.h`) file as follows:
```c++
class Car {
private:
	int year;
	std::string make;

public:
	const int GetYear(void) const { return this->year; }
	void SetYear(const int year) { this->year = year; }
	const std::string & GetMake(void) const { return this->make; }
	void SetMake(const std::string &make) { this->make = make; }
};
```

Another important consideration: If you have getters and setters for all of your members, you may want to reconsider the design of your class. It is more often than not that having getters and setters for every member is indicative of poor planning of the class design and interface. Getters are very common, but setters should be used more carefully. Should you have set the variable in the constructor? Is it set somewhere else in another method, perhaps even indirectly?

### 1.2 Inheritance
A class can extend another class, meaning that the new class inherits all of the data from the other class, and can also override its methods, add new members, etc. Inheritance is the key feature required for polymorphism.

**Example:** the class `Rectangle` can inherit the class `Polygon`. You would then say that `Rectangle` extends `Polygon`, or that class `Rectangle` is a sub-class of `Polygon`. In plain English, this means that a `Rectangle` is a more specialized version of a `Polygon`.

#### 1.2.1 `Rectangle` Declaration (`.h` file)
```c++
#include "Polygon.h"	// <--- You must include the declaration in order to extend the class

class Rectangle: public Polygon {
private:			// <--- The members 'num_sides' and 'name' are already inherited from Polygon
	int length;
	int width;

public:
	// Constructors
	Rectangle(const std::string &name);
	Rectangle(const std::string &name, const int length, const int width);

	// Getters and Setters	<--- The methods 'GetNumSides()', 'SetNumSides()', 'GetName()' and 'SetName()' are already inherited from Polygon
	const int GetLength(void) const { return this->length; }
	void SetLength(const int) { this->length = length; }

	const int GetWidth(void) const { return this->width; }
	void SetWidth(const int) { this->width = width; }

	// Other Methods
	const int Area(void) const;
};
```

#### 1.2.2 `Rectangle` Definition (`.cpp` file)
```c++
#include "Rectangle.h"	// <--- Only need to include 'Rectangle', since 'Polygon' is included in 'Rectangle.h'

// This constructor calls the superclass (Polygon) constructor and sets the name and number of sides to '4', and then sets the length and width
Rectangle::Rectangle(const std::string &name, const int length, const int width) : Polygon(4, name) {
	this->length = length;
	this->width = width;
}

// This constructor calls the superclass (Polygon) constructor, but sets the length and width to a constant value
Rectangle::Rectangle(const std::string &name) : Polygon(4, name) {
	this->length = 1;
	this->width = 1;
}

// Compute the area of the rectangle
Rectangle::Area(void) const {
	return this->length * this->width;
}
```

#### 1.2.3 `Rectangle` Utilization (Another `.cpp` file)
```c++
#include "Rectangle.h"

int main(int argc, char *argv[]) {
	Rectangle rectangle = Rectangle("Square", 6, 6);

	// Prints "Square has 4 sides, and an area of 36"
	std::cout << rectangle.GetName() << " has " << rectangle.GetNumSides() << " sides, and an area of " << rectangle.Area() << std::endl;
}
```

### 1.3 Polymorphism

### 1.4 Constructor/Destructor/Copy Constructor
#### 1.4.1 Use of `explicit` in Constructors
The keyword `explicit` should be used in single-argument constructors to avoid the following situation. Consider the class `Array`:
```c++
class Array {
public:
	Array(int size) {
		this->size = size;
	}

private:
	int size;
};
```

The following is now legal but ambiguous:
```c++
Array array = 12345;
```

It ends up being the equivalent of this:
```c++
Array array = Array(12345);
```

That's fine, one would suppose, but what about the following:
```c++
// Method PrintArray is defined as: Array::Print(const Array &array)
array.Print(12345);
```

Uh-oh. That's now legal, compilable code, but what does it mean? It is extremely unclear to the user.

To fix this, declare the single-argument `Array` constructor as `explicit`:
```c++
class Array {
public:
	explicit Array(int size) {
		this->size = size;
	}
};
```

Now you can only use the print method as follows:
```c++
array.Print(Array(12345));
```

### 1.4 Initialization Lists

### 1.5 Operator Overloading
[Reference](http://en.cppreference.com/w/cpp/language/operators)

### 1.6 Templates
[Reference](http://en.cppreference.com/w/cpp/language/templates)

## 2.0 General C++ Syntax
### 2.1 Namespaces

### 2.2 References and Pointers

### 2.3 Keywords
[Reference](http://en.cppreference.com/w/cpp/keyword)

#### 2.3.1 General Keywords
[`asm`](http://en.cppreference.com/w/cpp/language/asm)
[`auto`](http://en.cppreference.com/w/cpp/language/auto)
[`cont`](http://en.cppreference.com/w/cpp/language/cv)
[`constexpr` (*since C++11*)](http://en.cppreference.com/w/cpp/language/constexpr)
[`explicit`](http://en.cppreference.com/w/cpp/language/explicit)
[`export` (*until C++11*)](http://en.cppreference.com/w/cpp/keyword/export)
[`extern` (*language linkage*)](http://en.cppreference.com/w/cpp/language/language_linkage)
[`friend`](http://en.cppreference.com/w/cpp/language/friend)
[`inline`](http://en.cppreference.com/w/cpp/language/inline)
[`mutable`](http://en.cppreference.com/w/cpp/language/cv)
[`noexcept` (*operator*)](http://en.cppreference.com/w/cpp/language/noexcept)
[`noexcept` (*function specifier*)](http://en.cppreference.com/w/cpp/language/noexcept_spec)
[`nullptr`](http://en.cppreference.com/w/cpp/language/nullptr)
[`override`](http://en.cppreference.com/w/cpp/language/override)
[`static` (*class member specifier*)](http://en.cppreference.com/w/cpp/language/static)
[`template`](http://en.cppreference.com/w/cpp/language/templates)
[`this`](http://en.cppreference.com/w/cpp/language/this)
[`virtual` (*function specifier*)](http://en.cppreference.com/w/cpp/language/virtual)
[`virtual` (*base class specifier*)](http://en.cppreference.com/w/cpp/language/derived_class)
[`volatile`](http://en.cppreference.com/w/cpp/language/cv)

#### 2.3.2 Storage Class Specifiers
[Reference](http://en.cppreference.com/w/cpp/language/storage_duration)
* `auto` (*until C++11*)
* `register` (*until C++17*)
* `static`
* `extern`
* `thread_local` (*since C++11*)

#### 2.3.3 `const` and `dynamic` Cast Conversion
* [`const_cast`](http://en.cppreference.com/w/cpp/language/const_cast)
* [`dynamic_cast`](http://en.cppreference.com/w/cpp/language/dynamic_cast)

### 2.4 Preprocessor Tokens
* `#if`: Preprocessor version of `if(...)`
* `#elif`: Preprocessor version of `else if(...)`
* `#else`: Preprocessor version of `else`
* `#endif`: Used to end an `#if`, `#ifdef`, or `#ifndef`
* `defined()`: Returns true if the macro is defined
* `#ifdef`: Same as `#if defined(...)`
* `#ifndef`: Same as `#if !defined(...)`
* `#define`: Defines a text macro. See [here](http://en.cppreference.com/w/cpp/preprocessor/replace) for full explanation, including macro functions and predefined macros.
* `#undef`: Un-defines a text macro
* `#include`: Includes a source file
* `#line`: Changes the current file name and line number in the preprocessor
* `#error`: Prints an error message and stops compilation
* `#pragma`: Non-standard, used instead of header guards (`#ifndef HEADER_H` ...)

### 2.4 Strings (`std::string`)
[Reference](http://en.cppreference.com/w/cpp/string/basic_string)

### 2.5 Iterators (`std::iterator<...>`)
[Reference](http://en.cppreference.com/w/cpp/concept/Iterator)

### 2.6 Exceptions (`std::exception`)
[Reference](http://en.cppreference.com/w/cpp/error/exception)


================================================
FILE: C++/Data Structures and Algorithms.md
================================================
# C++ Data Structures and Algorithms Cheat Sheet

## Table of Contents

<!-- TOC depthFrom:1 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 -->

- [C++ Data Structures and Algorithms Cheat Sheet](#c-data-structures-and-algorithms-cheat-sheet)
	- [Table of Contents](#table-of-contents)
	- [1.0 Data Structures](#10-data-structures)
		- [1.1 Overview](#11-overview)
		- [1.2 Vector `std::vector`](#12-vector-stdvector)
		- [1.3 Deque `std::deque`](#13-deque-stddeque)
		- [1.4 List `std::list` and `std::forward_list`](#14-list-stdlist-and-stdforward_list)
		- [1.5 Map `std::map` and `std::unordered_map`](#15-map-stdmap-and-stdunordered_map)
		- [1.6 Set `std::set`](#16-set-stdset)
		- [1.7 Stack `std::stack`](#17-stack-stdstack)
		- [1.8 Queue `std::queue`](#18-queue-stdqueue)
		- [1.9 Priority Queue `std::priority_queue`](#19-priority-queue-stdpriority_queue)
		- [1.10 Heap `std::priority_queue`](#110-heap-stdpriority_queue)
	- [2.0 Trees](#20-trees)
		- [2.1 Binary Tree](#21-binary-tree)
		- [2.2 Balanced Trees](#22-balanced-trees)
		- [2.3 Binary Search](#23-binary-search)
		- [2.4 Depth-First Search](#24-depth-first-search)
		- [2.5 Breadth-First Search](#25-breadth-first-search)
	- [3.0 NP Complete Problems](#30-np-complete-problems)
		- [3.1 NP Complete](#31-np-complete)
		- [3.2 Traveling Salesman Problem](#32-traveling-salesman-problem)
		- [3.3 Knapsack Problem](#33-knapsack-problem)
	- [4.0 Algorithms](#40-algorithms)
		- [4.1 Insertion Sort](#41-insertion-sort)
		- [4.2 Selection Sort](#42-selection-sort)
		- [4.3 Bubble Sort](#43-bubble-sort)
		- [4.4 Merge Sort](#44-merge-sort)
		- [4.5 Quicksort](#45-quicksort)

<!-- /TOC -->


## 1.0 Data Structures
### 1.1 Overview

![Legend](General/Legend.png)

![DataStructures](General/Data%20Structures.png "Data Structures")

![ComplexityChart](General/Complexity%20Chart.png "Complexity Chart")

![DataStructureSelection](General/Data%20Structures%20Selection.png "Data Structures Selection")
-------------------------------------------------------
### 1.2 Vector `std::vector`
**Use for**
* Simple storage
* Adding but not deleting
* Serialization
* Quick lookups by index
* Easy conversion to C-style arrays
* Efficient traversal (contiguous CPU caching)

**Do not use for**
* Insertion/deletion in the middle of the list
* Dynamically changing storage
* Non-integer indexing

**Time Complexity**

| Operation    | Time Complexity |
|--------------|-----------------|
| Insert Head  |          `O(n)` |
| Insert Index |          `O(n)` |
| Insert Tail  |          `O(1)` |
| Remove Head  |          `O(n)` |
| Remove Index |          `O(n)` |
| Remove Tail  |          `O(1)` |
| Find Index   |          `O(1)` |
| Find Object  |          `O(n)` |

**Example Code**
```c++
std::vector<int> v;

//---------------------------------
// General Operations
//---------------------------------

// Insert head, index, tail
v.insert(v.begin(), value);             // head
v.insert(v.begin() + index, value);     // index
v.push_back(value);                     // tail

// Access head, index, tail
int head = v.front();       // head
int value = v.at(index);    // index
int tail = v.back();        // tail

// Size
unsigned int size = v.size();

// Iterate
for(std::vector<int>::iterator it = v.begin(); it != v.end(); it++) {
    std::cout << *it << std::endl;
}

// Remove head, index, tail
v.erase(v.begin());             // head
v.erase(v.begin() + index);     // index
v.pop_back();                   // tail

// Clear
v.clear();
```
-------------------------------------------------------
### 1.3 Deque `std::deque`
**Use for**
* Similar purpose of `std::vector`
* Basically `std::vector` with efficient `push_front` and `pop_front`

**Do not use for**
* C-style contiguous storage (not guaranteed)

**Notes**
* Pronounced 'deck'
* Stands for **D**ouble **E**nded **Que**ue

**Example Code**
```c++
std::deque<int> d;

//---------------------------------
// General Operations
//---------------------------------

// Insert head, index, tail
d.push_front(value);                    // head
d.insert(d.begin() + index, value);     // index
d.push_back(value);                     // tail

// Access head, index, tail
int head = d.front();       // head
int value = d.at(index);    // index
int tail = d.back();        // tail

// Size
unsigned int size = d.size();

// Iterate
for(std::vector<int>::iterator it = d.begin(); it != d.end(); it++) {
    std::cout << *it << std::endl;
}

// Remove head, index, tail
d.pop_front();                  // head
d.erase(d.begin() + index);     // index
d.pop_back();                   // tail

// Clear
d.clear();
```
-------------------------------------------------------
### 1.4 List `std::list` and `std::forward_list`
**Use for**
* Insertion into the middle/beginning of the list
* Efficient sorting (pointer swap vs. copying)

**Do not use for**
* Direct access

**Time Complexity**

| Operation    | Time Complexity |
|--------------|-----------------|
| Insert Head  |          `O(1)` |
| Insert Index |          `O(n)` |
| Insert Tail  |          `O(1)` |
| Remove Head  |          `O(1)` |
| Remove Index |          `O(n)` |
| Remove Tail  |          `O(1)` |
| Find Index   |          `O(n)` |
| Find Object  |          `O(n)` |

**Example Code**
```c++
std::list<int> l;

//---------------------------------
// General Operations
//---------------------------------

// Insert head, index, tail
l.push_front(value);                    // head
l.insert(l.begin() + index, value);     // index
l.push_back(value);                     // tail

// Access head, index, tail
int head = l.front();                                           // head
int value = std::list<int>::iterator it = l.begin() + index;    // index
int tail = l.back();                                            // tail

// Size
unsigned int size = l.size();

// Iterate
for(std::list<int>::iterator it = l.begin(); it != l.end(); it++) {
    std::cout << *it << std::endl;
}

// Remove head, index, tail
l.pop_front();                  // head
l.erase(l.begin() + index);     // index
l.pop_back();                   // tail

// Clear
l.clear();

//---------------------------------
// Container-Specific Operations
//---------------------------------

// Splice: Transfer elements from list to list
//	splice(iterator pos, list &x)
//  	splice(iterator pos, list &x, iterator i)
//  	splice(iterator pos, list &x, iterator first, iterator last)
l.splice(l.begin() + index, list2);

// Remove: Remove an element by value
l.remove(value);

// Unique: Remove duplicates
l.unique();

// Merge: Merge two sorted lists
l.merge(list2);

// Sort: Sort the list
l.sort();

// Reverse: Reverse the list order
l.reverse();
```
-------------------------------------------------------
### 1.5 Map `std::map` and `std::unordered_map`
**Use for**
* Key-value pairs
* Constant lookups by key
* Searching if key/value exists
* Removing duplicates
* `std::map`
    * Ordered map
* `std::unordered_map`
    * Hash table

**Do not use for**
* Sorting

**Notes**
* Typically ordered maps (`std::map`) are slower than unordered maps (`std::unordered_map`)
* Maps are typically implemented as *binary search trees*

**Time Complexity**

**`std::map`**

| Operation           | Time Complexity |
|---------------------|-----------------|
| Insert              |     `O(log(n))` |
| Access by Key       |     `O(log(n))` |
| Remove by Key       |     `O(log(n))` |
| Find/Remove Value   |     `O(log(n))` |

**`std::unordered_map`**

| Operation           | Time Complexity |
|---------------------|-----------------|
| Insert              |          `O(1)` |
| Access by Key       |          `O(1)` |
| Remove by Key       |          `O(1)` |
| Find/Remove Value   |              -- |

**Example Code**
```c++
std::map<std::string, std::string> m;

//---------------------------------
// General Operations
//---------------------------------

// Insert
m.insert(std::pair<std::string, std::string>("key", "value"));

// Access by key
std::string value = m.at("key");

// Size
unsigned int size = m.size();

// Iterate
for(std::map<int>::iterator it = m.begin(); it != m.end(); it++) {
    std::cout << *it << std::endl;
}

// Remove by key
m.erase("key");

// Clear
m.clear();

//---------------------------------
// Container-Specific Operations
//---------------------------------

// Find if an element exists by key
bool exists = (m.find("key") != m.end());

// Count the number of elements with a certain key
unsigned int count = m.count("key");
```
-------------------------------------------------------
### 1.6 Set `std::set`
**Use for**
* Removing duplicates
* Ordered dynamic storage

**Do not use for**
* Simple storage
* Direct access by index

**Notes**
* Sets are often implemented with binary search trees

**Time Complexity**

| Operation    | Time Complexity |
|--------------|-----------------|
| Insert       |     `O(log(n))` |
| Remove       |     `O(log(n))` |
| Find         |     `O(log(n))` |

**Example Code**
```c++
std::set<int> s;

//---------------------------------
// General Operations
//---------------------------------

// Insert
s.insert(20);

// Size
unsigned int size = s.size();

// Iterate
for(std::set<int>::iterator it = s.begin(); it != s.end(); it++) {
    std::cout << *it << std::endl;
}

// Remove
s.erase(20);

// Clear
s.clear();

//---------------------------------
// Container-Specific Operations
//---------------------------------

// Find if an element exists
bool exists = (s.find(20) != s.end());

// Count the number of elements with a certain value
unsigned int count = s.count(20);
```
-------------------------------------------------------
### 1.7 Stack `std::stack`
**Use for**
* First-In Last-Out operations
* Reversal of elements

**Time Complexity**

| Operation    | Time Complexity |
|--------------|-----------------|
| Push         |          `O(1)` |
| Pop          |          `O(1)` |
| Top          |          `O(1)` |

**Example Code**
```c++
std::stack<int> s;

//---------------------------------
// Container-Specific Operations
//---------------------------------

// Push
s.push(20);

// Size
unsigned int size = s.size();

// Pop
s.pop();

// Top
int top = s.top();
```
-------------------------------------------------------
### 1.8 Queue `std::queue`
**Use for**
* First-In First-Out operations
* Ex: Simple online ordering system (first come first served)
* Ex: Semaphore queue handling
* Ex: CPU scheduling (FCFS)

**Notes**
* Often implemented as a `std::deque`

**Example Code**
```c++
std::queue<int> q;

//---------------------------------
// General Operations
//---------------------------------

// Insert
q.push(value);

// Access head, tail
int head = q.front();       // head
int tail = q.back();        // tail

// Size
unsigned int size = q.size();

// Remove
q.pop();
```
-------------------------------------------------------
### 1.9 Priority Queue `std::priority_queue`
**Use for**
* First-In First-Out operations where **priority** overrides arrival time
* Ex: CPU scheduling (smallest job first, system/user priority)
* Ex: Medical emergencies (gunshot wound vs. broken arm)

**Notes**
* Often implemented as a `std::vector`

**Example Code**
```c++
std::priority_queue<int> p;

//---------------------------------
// General Operations
//---------------------------------

// Insert
p.push(value);

// Access
int top = p.top();  // 'Top' element

// Size
unsigned int size = p.size();

// Remove
p.pop();
```
-------------------------------------------------------
### 1.10 Heap `std::priority_queue`
**Notes**
* A heap is essentially an instance of a priority queue
* A **min** heap is structured with the root node as the smallest and each child subsequently smaller than its parent
* A **max** heap is structured with the root node as the largest and each child subsequently larger than its parent
* A min heap could be used for *Smallest Job First* CPU Scheduling
* A max heap could be used for *Priority* CPU Scheduling

**Max Heap Example (using a binary tree)**

![MaxHeap](General/MaxHeap.png)
-------------------------------------------------------
## 2.0 Trees
### 2.1 Binary Tree
* A binary tree is a tree with at most two (2) child nodes per parent
* Binary trees are commonly used for implementing `O(log(n))` operations for ordered maps, sets, heaps, and binary search trees
* Binary trees are **sorted** in that nodes with values greater than their parents are inserted to the **right**, while nodes with values less than their parents are inserted to the **left**

**Binary Search Tree**

![BinarySearchTree](General/BinarySearchTree.png)
-------------------------------------------------------
### 2.2 Balanced Trees
* Balanced trees are a special type of tree which maintains its balance to ensure `O(log(n))` operations
* When trees are not balanced the benefit of `log(n)` operations is lost due to the highly vertical structure
* Examples of balanced trees:
    * AVL Trees
    * Red-Black Trees

-------------------------------------------------------
### 2.3 Binary Search
**Idea:**
1. If current element, return
2. If less than current element, look left
3. If more than current element, look right
4. Repeat

**Data Structures:**
* Tree
* Sorted array

**Space:**
* `O(1)`

**Best Case:**
* `O(1)`

**Worst Case:**
* `O(log n)`

**Average:**
* `O(log n)`

**Visualization:**

![BinarySearch](Searching/Animations/Binary%20Search.gif "Binary Search")
-------------------------------------------------------
### 2.4 Depth-First Search
**Idea:**
1. Start at root node
2. Recursively search all adjacent nodes and mark them as searched
3. Repeat

**Data Structures:**
* Tree
* Graph

**Space:**
* `O(V)`, `V = number of verticies`

**Performance:**
* `O(E)`, `E = number of edges`

**Visualization:**

![DepthFirstSearch](Searching/Animations/Depth-First%20Search.gif "Depth-First Search")
-------------------------------------------------------
### 2.5 Breadth-First Search
**Idea:**
1. Start at root node
2. Search neighboring nodes first before moving on to next level

**Data Structures:**
* Tree
* Graph

**Space:**
* `O(V)`, `V = number of verticies`

**Performance:**
* `O(E)`, `E = number of edges`

**Visualization:**

![DepthFirstSearch](Searching/Animations/Breadth-First%20Search.gif "Breadth-First Search")
-------------------------------------------------------
## 3.0 NP Complete Problems
### 3.1 NP Complete
* **NP Complete** means that a problem is unable to be solved in **polynomial time**
* NP Complete problems can be *verified* in polynomial time, but not *solved*

-------------------------------------------------------
### 3.2 Traveling Salesman Problem

-------------------------------------------------------
### 3.3 Knapsack Problem

-------------------------------------------------------

## 4.0 Algorithms
###  4.1 Insertion Sort
#### Idea
1. Iterate over all elements
2. For each element:
    * Check if element is larger than largest value in sorted array
3. If larger: Move on
4. If smaller: Move item to correct position in sorted array

#### Details
* **Data structure:** Array
* **Space:** `O(1)`
* **Best Case:** Already sorted, `O(n)`
* **Worst Case:** Reverse sorted, `O(n^2)`
* **Average:** `O(n^2)`

#### Advantages
* Easy to code
* Intuitive
* Better than selection sort and bubble sort for small data sets
* Can sort in-place

#### Disadvantages
* Very inefficient for large datasets

#### Visualization

![InsertionSort](Sorting/Animations/Insertion%20Sort.gif "Insertion Sort")
-------------------------------------------------------
### 4.2 Selection Sort
#### Idea
1. Iterate over all elements
2. For each element:
    * If smallest element of unsorted sublist, swap with left-most unsorted element

#### Details
* **Data structure:** Array
* **Space:** `O(1)`
* **Best Case:** Already sorted, `O(n^2)`
* **Worst Case:** Reverse sorted, `O(n^2)`
* **Average:** `O(n^2)`

#### Advantages
* Simple
* Can sort in-place
* Low memory usage for small datasets

#### Disadvantages
* Very inefficient for large datasets

#### Visualization

![SelectionSort](Sorting/Animations/Selection%20Sort.gif "Selection Sort")

![SelectionSort](Sorting/Animations/Selection%20Sort%202.gif "Selection Sort 2")
-------------------------------------------------------
### 4.3 Bubble Sort
#### Idea
1. Iterate over all elements
2. For each element:
    * Swap with next element if out of order
3. Repeat until no swaps needed

#### Details
* **Data structure:** Array
* **Space:** `O(1)`
* **Best Case:** Already sorted `O(n)`
* **Worst Case:** Reverse sorted, `O(n^2)`
* **Average:** `O(n^2)`

#### Advantages
* Easy to detect if list is sorted

#### Disadvantages
* Very inefficient for large datasets
* Much worse than even insertion sort

#### Visualization

![BubbleSort](Sorting/Animations/Bubble%20Sort.gif "Bubble Sort")
-------------------------------------------------------
### 4.4 Merge Sort
#### Idea
1. Divide list into smallest unit (1 element)
2. Compare each element with the adjacent list
3. Merge the two adjacent lists
4. Repeat

#### Details
* **Data structure:** Array
* **Space:** `O(n) auxiliary`
* **Best Case:** `O(nlog(n))`
* **Worst Case:** Reverse sorted, `O(nlog(n))`
* **Average:** `O(nlog(n))`

#### Advantages
* High efficiency on large datasets
* Nearly always O(nlog(n))
* Can be parallelized
* Better space complexity than standard Quicksort

#### Disadvantages
* Still requires O(n) extra space
* Slightly worse than Quicksort in some instances

#### Visualization

![MergeSort](Sorting/Animations/Merge%20Sort.gif "Merge Sort")

![MergeSort](Sorting/Animations/Merge%20Sort%202.gif "Merge Sort 2")
-------------------------------------------------------
### 4.5 Quicksort
#### Idea
1. Choose a **pivot** from the array
2. Partition: Reorder the array so that all elements with values *less* than the pivot come before the pivot, and all values *greater* than the pivot come after
3. Recursively apply the above steps to the sub-arrays

#### Details
* **Data structure:** Array
* **Space:** `O(n)`
* **Best Case:** `O(nlog(n))`
* **Worst Case:** All elements equal, `O(n^2)`
* **Average:** `O(nlog(n))`

#### Advantages
* Can be modified to use O(log(n)) space
* Very quick and efficient with large datasets
* Can be parallelized
* Divide and conquer algorithm

#### Disadvantages
* Not stable (could swap equal elements)
* Worst case is worse than Merge Sort

#### Optimizations
* Choice of pivot:
    * Choose median of the first, middle, and last elements as pivot
    * Counters worst-case complexity for already-sorted and reverse-sorted

#### Visualization

![QuickSort](Sorting/Animations/Quicksort.gif)


================================================
FILE: C++/README.md
================================================
# C++ and Data Structures & Algorithms Cheat Sheet

These are two cheat sheets I put together describing both basic [C++ syntax](C++%20Syntax.md) and many common [data structures and algorithms](Data%20Structures%20and%20Algorithms.md) in C++ for my past interviews at Google, NASA, etc.

Hopefully you find them useful, and please open an issue or submit a PR if you find incorrect or missing information!


================================================
FILE: Command Line/README.md
================================================
[back to overwiev](/../..)

# Command Line Cheatsheet

##### Table of Contents  
[Basics](#basics)  
[Showing & Navigating](#showing--navigating)  
[Copying/Moving/Removing](#copyingmovingremoving)  
[Input & Output Redirects](#input--output-redirects)  
[Sorting & Filtering](#sorting--filtering)  
[Environment](#environmen)  

## Basics
**clear** –– clears the terminal
**nano** filename –– opens the nano text editor for specific file (optional)
^ –– in nano stands for ctrl
~ –– usually represents the users home directory

## Showing & Navigating
**ls** –– lists all files (folders are called directories. files and directories are structured in a file system)  
**ls -a** –– lists all files + hidden files (-a is called an option)  
ls -t –– orders by time last added  
ls -l –– with long description (access-rights, n# of hard links, owner, group-name, size in bytes, date-last-modified, name)  
ls -alt –– -a, -t & -l together  
**pwd** –– print working directory path (the directory you’re currently in)  
**cd directory-name** –– change directory  
cd folder/childfolder –– two down  
cd .. –– one up – cd folder/folder –– two down  
**mkdir name** –– make directory  
**touch name** –– creates a new file inside the working directory  
**cat** filename –– outputs the content of a file to the console  
**wc** filename –– outputs the number of lines, words, and characters in file  

## Copying/Moving/Removing
**cp** file-to-copy place-to-paste –– copies files and paste them somewhere else  
cp file1 file2 file3 place-to-paste –– you can copy multiple files at once  
cp * place-to-paste –– copy all files from working directory  (special characters like * are called wildcard, when you combine it with .txt for example would mean any file that ends with .txt)    
**mv** file-to-move-1 place-to-move –– moves a file  
mv file-to-rename new-filename –– renames a file  
**rm** file-to-remove –– removes a file or directory !permanently!  
rm -r dir-to-remove –– removes a dir and all its children !permanently!  

##Input & Output Redirects
echo "Hello" > world.txt –– **>** redirects the standard output (Hello) into something else (world.txt)  
cat file1.txt > file2.txt –– content of file1 is redirected into file2 which overrides the content of file2 by the content of file1  
cat file1.txt >> file2.txt –– **>>** appends the output of file1 to file2  
cat < file.txt –– takes the output from the right and inputs it into the left  
cat file.txt | wc –– **|** is a "pipe". The | takes the standard output of the command on the left, and pipes it as standard input to the command on the right. You can think of this as "command to command" redirection.  
cat text1.txt | wc | cat > text2.txt –– multiple pipes can be combined here the output of text1.txt is given to wc whose output is given to cat which places it into text.txt

## Sorting & Filtering
**sort** filename –– outputs the sortet content of the file  
cat filename | sort > nameofsortedfile –– outputs the content of filename binds it to the sort function that then redirect that sorted output into a file  
**uniq** filename –– filters out adjacent, duplicate lines in a file  
sort file | uniq > anotherfile –– sorts a file "pipes" (|) the sorted content to uniq which filters out all adjacent duplicates and gives the result back to another file
sort file | uniq -c > anotherfile -– counting the duplicated lines in file  
sort file | uniq -c | sort -nr > anotherfile -– counting the duplicated lines in file and sort it (by frequency)
**grep** keyword filename –– searches a file for lines that have the keyword and output the result (it is case sensitive)  
grep -i keyword filename –– here grep is case insensitive  
grep -R keyword folder –– searches all files in a directory and outputs filenames and lines containing matched results  
grep -Rl keyword folder –– searches all files in a directory and outputs only filenames with matched results  
**sed** 's/keyword/replacement' filename –– find in file and replace s = substitution. So sed 's/find/replace' in_this_file (only replace the first finding)  
sed 's/keyword/replacement/**g**' filename –– same as above but replaces all instances not only the first finding  

## Environment
**nano** ~/.bash_profile –– creates a file to store environment settings. Whenever a session starts it will load it's content.
(within bash_profile) **alias** pd="pwd" –– create keyboard shortcuts, for commonly used commands.
(within bash_profile) **export** USER="username" –– create a variable that can be accessed by $USER
(within bash_profile) export PS1=">> " –– to change the command prompt from $ to >>
**source** ~/.bash_profile –– makes changes available without the fuzz to open a new console.
**env** –– return a list of environment variables


================================================
FILE: Django/README.md
================================================
# Cheatsheet for Django QuerySets
Current Django Version: [2.0](https://docs.djangoproject.com/en/2.0/ref/models/querysets/)

## Methods that return new [QuerySets](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#methods-that-return-new-querysets)

**Can be chained:**

```python
Entry.objects.filter(**kwargs).exclude(**kwargs).order_by(**kwargs)
```

 * [filter](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#filter)
 * [exclude](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#exclude)
 * [annotate](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#annotate)
 * [order_by](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#order-by)
 * [reverse](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#reverse)
 * [distinct](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#distinct)
 * [values](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#values)
 * [values_list](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#values-list)
 * [dates](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#dates)
 * [datetimes](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#datetimes)
 * [none](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#none)
 * [all](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#all)
 * [union](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#union)
 * [intersection](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#intersection)
 * [difference](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#difference)
 * [select_related](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#select-related)
 * [prefetch_related](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#prefetch-related)
 * [extra](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#extra)
 * [defer](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#defer)
 * [only](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#only)
 * [using](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#using)
 * [select_for_update](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#select-for-update)
 * [raw](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#raw)

## Methods that do not return QuerySets

 * [get](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#get)
 * [create](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#create)
 * [get_or_create](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#get-or-create)
 * [update_or_create](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#update-or-create)
 * [bulk_create](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#bulk-create)
 * [count](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#count)
 * [in_bulk](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#in-bulk)
 * [iterator](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#iterator)
 * [latest](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#latest)
 * [earliest](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#earliest)
 * [first](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#first)
 * [last](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#last)
 * [aggregate](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#aggregate)
 * [exists](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#exists)
 * [update](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#update)
 * [delete](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#delete)
 * [as_manager](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#as-manager)

## Field lookups

**Field lookups are how you specify the meat of an SQL WHERE clause. They’re specified as keyword arguments to the QuerySet methods *filter()*, *exclude()* and *get()*.**

```python
Example: Entry.objects.get(id__exact=14)  # note double underscore.
```

 * [exact](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#exact)
 * [iexact](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#iexact)
 * [contains](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#contains)
 * [icontains](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#icontains)
 * [in](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#in)
 * [gt](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#gt)
 * [gte](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#gte)
 * [lt](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#lt)
 * [lte](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#lte)
 * [startswith](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#startswith)
 * [istartswith](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#istartswith)
 * [endswith](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#endswith)
 * [iendswith](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#iendswith)
 * [range](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#range)
 * [date](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#date)
 * [year](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#year)
 * [month](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#month)
 * [day](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#day)
 * [week](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#week)
 * [week_day](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#week-day)
 * [quarter (new in 2.0)](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#quarter)
 * [time](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#time)
 * [hour](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#hour)
 * [minute](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#minute)
 * [second](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#second)
 * [isnull](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#isnull)
 * [regex](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#regex)
 * [iregex](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#iregex)

**Protip: Use [in](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#in) to avoid chaining [filter()](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#filter) and [exclude()](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#exclude)**

```python
Entry.objects.filter(status__in=['Hung over', 'Sober', 'Drunk'])
```

## Aggregation functions

 * [expression](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#expression)
 * [output_field](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#output-field)
 * [filter (new in 2.0)](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#id6)
 * [Avg](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#avg)
 * [Count](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#id8)
 * [Max](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#max)
 * [Min](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#min)
 * [StdDev](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#stddev)
 * [Sum](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#sum)
 * [Variance](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#variance)

## Query-related classes

 * [Q() objects](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#q-objects)
 * [Prefetch() objects](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#prefetch-objects)
 * [prefetch_related_objects()](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#prefetch-related-objects)
 * [FilteredRelation() objects (new in 2.0)](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#filteredrelation-objects)

- - -

<a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-sa/3.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text" property="dct:title" rel="dct:type">Django-QuerySet-Cheatsheet</span> by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">@chrisdl and @briandant</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/deed.en_US">Creative Commons Attribution-ShareAlike 3.0 Unported License</a>.<br />

The [contributors](https://github.com/chrisdl/Django-QuerySet-Cheatsheet/graphs/contributors) are as gods among ants and shall forever be remembered as such.

The Django web framework referenced in the Django-QuerySet-Cheatsheet is ​© 2005-2018 Django Software Foundation.
Django is a registered trademark of the Django Software Foundation.


================================================
FILE: Elixir/README.md
================================================
# Elixir Cheat Sheet

```elixir
elixir -v
1.3.1
```

Elixir is a dynamic functional compiled language that runs over an Erlang Virtual Machine called BEAM.

Erlang and its BEAM is well known for running low-lattency, distributed and fault-tolerant applications.

Elixir was designed to take all that advantages in a modern coding language.

Elixir data types are immutable.

In Elixir a function is usually described with its arity (number of arguments), such as: `is_boolean/1`.

## File Types

- `.exs` => Elixir script file
- `.ex` => Elixir regular file
- `.beam` => Compiled Elixir file

## Compile and Run Elixir code

- `elixir <script_file>.exs` => run a script file
- `elixirc <file>.ex` => compile a file to `Elixir.<File>.beam`

## Elixir Conventions

- `foo function return tuple` => the result of a `foo` function is usually `{:ok, result}` or `{:error, reason}`
- `foo! function may raise an error` => the result of a `foo!` is not wrapped in a tuple and it may raises an exception
- Exceptions/Errors are **not used** for controlling flow
- Elixir uses **fail fast** idea and the supervision trees to control process health and possible restart processes.

## Comments

- `#` => single line comment

There are no multi-line comment

## Code Documentation

- `@moduledoc` => module documentation
- `@doc` => function documentation
- `@spec` => function arguments/return specification
- `@typedoc` => type documentation
- `@type` => type definition
- `@typep` => private type definition

```elixir
defmodule Math do
  @moduledoc """
  Provides math-related functions.

  ## Examples

      iex> Math.sum(1, 2)
      3
  """

  @spec sum(number, number) :: number
  @doc """
  Calculates the sum of two numbers.
  """
  def sum(a, b), do: a + b
end

h Math
h Math.sum
```

## Elixir Special Unbound Variable

- `_` => unbound variable

## Elixir/Erlang Virtual Machine inspection

- `:observer.start` => start a gui tool for inspection
- `:erlang.memory` => inspect memory
- `:c.memory` => inspect memory

```elixir
:c.memory
# [
#   total: 19262624,
#   processes: 4932168,
#   processes_used: 4931184,
#   system: 14330456,
#   atom: 256337,
#   atom_used: 235038,
#   binary: 43592,
#   code: 5691514,
#   ets: 358016
# ]
```

## Interactive Elixir

- `iex` => open Interactive Elixir
- `iex <file>` => open Interactive Elixir loading a file
- `<Ctrl>c + a` => close iex
- `i <object>` => information about an object
- `h <function/arity>` => help for a function
- `h <operator/arity>` => help for a operator
- `s <function/arity>` => specification for a function
- `s <operator/arity>` => specification for a operator
- `t <function/arity>` => type for a function
- `c <file>` => load and compile a `.ex` file

## Basic Types

### Integer

- `1` => integer
- `1_000` => integers can use `_` to make it easy to read
- `0x1F` => integer
- `0b1010` => binary integer notation 10
- `0o777` => octadecimal integer notation 511
- `0x1F` => hexadecimal integer notation 31

### Float

- `-1.0` => float
- `5.7e-2` => float exponent notation 0.057

### Atom

- `:atom` => atom / symbol

- `true` => boolean (atom)

### BitString

- `<<97::size(2)>>` => bit string
- `<<97,98>>` => binary
- `"elixir"` => string

### Tuple

- `{1, 2, 3}` => tuple

### List

- `[1, 2, 3]` => list
- `'elixir'` => char list

- `[a: 5, b: 3]` => keyword list short notation
- `[{:a, 5}, {:b, 3}]` => keyword list long notation

### Map

- `%{name: "Mary", age: 29}` => map short notation (keys must be atoms)
- `%{:name => "Mary", :age => 29}` => map long notation

### PID

- `self() #=> #PID<0.80.0>` => current Process id

### Function

- `fn -> :hello end` => anonymous function

### Reference

- `make_ref() #=> #Reference<0.0.8.133>` => create a new reference

### Port

- `hd Port.list() #=> #Port<0.0>` => get first port

## Type Testing

- `is_nil/1`
- `is_integer 1`
- `is_float 4.6`
- `is_number 7.8`
- `is_atom :foo`
- `is_boolean false`
- `is_bitstring <<97:2>>`
- `is_binary <<97, 98>>`
- `is_list/1`
- `is_tuple/1`
- `is_map/1`
- `is_pid self()`
- `is_function(fn a, b -> a + b end)` => function
- `is_function(fn a, b -> a + b end, 2)` => function with arity
- `is_port hd Port.list()`
- `is_reference make_ref()`
- `Range.range?(1..3)`

## Converting Types

- `to_char_list("hełło")` => convert a string to char list
- `to_string('hełło')` => convert a char list to string
- `Map.to_list(%{:a => 1, 2 => :b})` => convert a map to list of tuples or keyword list

## Number Operators

- `10 / 2 => 5.0` => division always return a float
- `div(10, 2) => 5` => integer division
- `rem 10, 3 => 1` => integer remain of a division
- `round(3.58) => 4` => float round
- `trunc(3.58) => 3` => float trunc

## Boolean Operators

Falsy in Elixir is `false` and `nil`, otherwise will be truthy.

- `==` => equals
- `!=` => different
- `===` => strict equal (integer with float)
- `!==` => strict different (integer with float)
- `<` => less
- `<=` => less or equal
- `>` => greater
- `>=` => greater or equal
- `&&` => truthy and
- `||` => truthy or
- `!` => truthy not
- `and` => boolean and
- `or` => boolean or
- `not` => boolean not

It's possible to compare different data types and that's the sorting order: `number < atom < reference < functions < port < pid < tuple < list < bit string`.

## Pipe Operator

- `|>` => pipe operator

The return of a function will be passed as the first argument to the following.

```elixir
1..100 |>
  Stream.map(&(&1 * 3)) |>
  Stream.filter(&(rem(&1, 2) != 0)) |>
  Enum.sum
#=> 7500
```

## Pattern Matching

In Elixir `=` sign is not just an assign operator, but a **Match Operator**.

This means that you assign variables from right side to the left based on patterns defined by the left one. If a pattern does not match a `MatchError` is raised.

This powerful tool is also used to decompose complex objects like tuples, lists, etc into smaller ones:

```elixir
x = 1 #=> assign 1 to x
2 = x #=> ** (MatchError)
1 = x #=> match and does not assign anything

<<0, 1, x>> = <<0, 1, 2, 3>> #=> ** (MatchError)
<<0, 1, x::binary>> = <<0, 1, 2, 3>>
<<0, 1>> <> <<x::binary>> = <<0, 1, 2, 3>>
<<0, 1>> <> <<x, y>> = <<0, 1, 2, 3>>
<<0, 1>> <> <<x>> <> <<y>> = <<0, 1, 2, 3>>

"world" <> x = "hello" #=> ** (MatchError)
"he" <> x = "hello"

{x, y, z} = {1, 2} #=> ** (MatchError)
{} = {1, 2} #=> ** (MatchError)
{:a, :b} = {:b, :a} #=> ** (MatchError)
{x, y} = {1, 2}

first..last = 1..5

[x, 4] = [:a, 5] #=> ** (MatchError)
[] = [:a, 5] #=> ** (MatchError)
[:a, :b] = [:b, :a] #=> ** (MatchError)
[x, 4] = [:a, 4]

[x | y] = [] #=> ** (MatchError)
[x | y] = [1]
[x | y] = [1, 2, 3]

[a: x] = [b: 9] #=> ** (MatchError)
[a: x] = [a: 5]
[{:a, x}] = [a: 5]

%{a: x} = %{b: 5} #=> ** (MatchError)
%{} = %{a: 5} # empty map matches any map
%{a: x, b: 5} = %{b: 5, a: 7, c: 9}

defmodule User do
  defstruct name: "John", age: 27
end
john = %User{age: 29}
%User{name: name} = john
name #=> "John"
```

So in other words:

- non variables on the left side will be used to **restrict a pattern to match**
- variables using the pin operator on the left side will have its value to be used to **restrict a pattern to match**
- variables on the left side will be **assigned** with right side values

So **variables** and **non variables** behave differently with the match operator.

In order to assert an **empty map** you have to use a guard instead of pattern match, just like:

```elixir
(
  fn m when map_size(m) == 0 ->
    "empty map"
  end
).(%{}) #=> "empty map"
```

### Pin Operator

The Pin Operator `^` is used to treat variables the same way non variables with the match operator. In other words, the Pin Operator will evaluate the variable and use its value to **restrict a pattern**, preserving its original value.

```elixir
x = 1 #=> assign 1 to x
^x = 1 #=> match x value with right side 1
^x = 2 #=> ** (MatchError)
```

### Match Operator Limitation

You cannot make function calls on the left side of a match.

- `length([1, [2], 3]) = 3 #=> ** (CompileError) illegal pattern`

## Custom Operators

You can customize an Elixir Operator like the following example:

```elixir
1 + 2 #=> 3
defmodule WrongMath do
  def a + b do
    {a, b}
  end
end
import WrongMath
import Kernel, except: [+: 2]
1 + 2 #=> {1, 2}
```

## Sigils

Available delimiters for `Sigil`: `/`, `|`, `"`, `'`, `(`, `[`, `{`, `<`.

- `~r` => regular expression (modifiers: `i`)
- `~r/hello/i` => `i` modifies to case insensitive
- `~w` => list of string words (modifiers: )
- `~w[foo bar]c` => `c` modifies to list of char lists
- `~w[foo bar]a` => `c` modifies to list of atoms

```elixir
~w(one two three) #=> ["one", "two", "three"]
~w(one two three)c #=> ['one', 'two', 'three']
~w(one two three)a #=> [:one, :two, :three]
```

## Bit Strings

- `<<97::4>>` => short notation with 4 bits
- `<<97::size(4)>>` => long notation with 4 bits
- `byte_size(<<5::4>>)` => bit string byte size

### Performance for Bit Strings:

#### cheap functions:

- `byte_size(<<97::4>>)`

#### expensive functions:

## Binaries

Binaries are 8 bits multiple Bit Strings. Binaries are 8 bits by default.

- `<<97>>` => short notation with 8 bits
- `<<97::size(8)>>` => long notation with 8 bits
- `<>` => concatenate binaries/strings

### Performance for Binaries:

#### cheap functions:

- `byte_size(<<97>>)`

#### expensive functions:

## Strings

String is a Binary of code points where all elements are valid characters. Strings are surrounded by double-quotes and are encoded in `UTF-8` by default.

- `"hello"` => string
- `<<97, 98>>` => string "ab"
- `<<?a, ?b>>` => string "ab"
 `?x` => code points (ASCII code) for letter `x`
- `"hello #{:world}"` => string interpolation
- `"\n"` => new line
- `String.length("hello") #=> 5` => get the length of a string
- `String.upcase("hello") #=> "HELLO"` => upcase a string
- `"""` => multi-line string begin/end

### Performance for Strings:

#### cheap functions:

- `byte_size("hello")`

#### expensive functions:

- `String.length("Hello")`

## Tuples

Tuple is a list that is stored contiguously in memory.

- `{:ok, "hello"}`
- `tuple_size({:ok, "hello"})` => tuple size
- `elem({:ok, "hello"}, 0)` => get tuple element by index
- `put_elem({:ok, "hello"}, 1, "world")`

### Performance for Tuples:

#### cheap functions:

- `tuple_size({:ok, "hello"})`
- `elem({:ok, "hello"}, 1)`

#### expensive functions:

- `put_elem({:ok, "hello"}, 1, "world")`

## Lists

**Lists** implements Enumerables protocol.

List is a linked list structure where each element points to the next one in memory. When subtraction just the first ocurrence will be removed.

- `[:ok, "hello"]`
- `[97 | [1, 6, 9]]` => prepend
- `[1, 5] ++ [3, 9] # [1, 5, 3, 9]` => concatenation
- `[1, 5] -- [9, 5] # [1]` => subtraction first occurrences
- `hd([1, 5, 7])` => head
- `tl([1, 5, 7])` => tail
- `:foo in [:foo, :bar] #=> true` => in operator

### Performance for Lists:

#### cheap functions:

- `[97 | [1, 6, 9]]` => prepend
- `hd([1, 5, 7])` => head
- `tl([1, 5, 7])` => tail

#### expensive functions:

- `[1, 5] ++ [3, 9] # [1, 5, 3, 9]` => concatenation
- `[1, 5] -- [9, 5] # [1]` => subtraction first occurrences
- `length([1, 4])`
- `:foo in [:foo, :bar] #=> true` => in operator

## Char List

A Char List is a List of code points where all elements are valid characters. Char Lists are surrounded by single-quote and are usually used as arguments to some old Erlang code.

- `'ab'` => char list
- `[97, 98]` => `'ab'`
- `[?a, ?b]` => `'ab'`
- `?x` => code points (ASCII code) for letter `x`
- `'hello' ++ 'world' # 'helloworld'` => concatenation
- `'hello' -- 'world' # 'hel'` => subtraction first occurrences
- `?l in 'hello' #=> true` => in operator

### Performance for Char Lists:

#### cheap functions:

- `[?H | 'ello']` => prepend

#### expensive functions:

- `'hello' ++ 'world' # 'helloworld'` => concatenation
- `'hello' -- 'world' # 'hel'` => subtraction first occurrences
- `length('Hello')`
- `?l in 'hello' #=> true` => in operator

## Keyword Lists

Keyword list is a list of tuples where first elements are atoms. When fetching by key the first match will return. If a keyword list is the last argument of a function the square brackets `[` are optional.

- `[a: 5, b: 3]` => keyword list short notation
- `[{:a, 5}, {:b, 3}]` => keyword list long notation
- `[{:a, 6} | [b: 7]] # [a: 6, b: 7]` => prepend
- `[a: 5] ++ [a: 7] # [a: 5, a: 7]` => concatenation
- `[a: 5, b: 7] -- [a: 5] # [b: 7]` => subtraction first ocurrences
- `([a: 5, a: 7])[:a] # 5` => fetch by key
- `length(a: 5, b: 7)` => optional squared brackets `[`

### Performance for Keyword Lists:

#### cheap functions:

- `[{:a, 6} | [b: 7]] # [a: 6, b: 7]` => prepend

#### expensive functions:

- `[a: 5] ++ [a: 7] # [a: 5, a: 7]` => concatenation
- `[a: 5, b: 7] -- [a: 5] # [b: 7]` => subtraction first ocurrences
- `([a: 5, a: 7])[:a] # 5` => fetch by key
- `length(a: 5, b: 7)` => optional squared brackets `[`

## Maps

**Maps** implements Enumerables protocol.

Map holds a key value structure.

- `%{name: "Mary", age: 29}` => map short notation (keys must be atoms)
- `%{:name => "Mary", :age => 29}` => map long notation
- `%{name: "Mary", age: 29}[:name]` => fetch `:name` hash notation
- `%{name: "Mary", age: 29}[:born]` => returns nil when do not find in the hash notation
- `%{name: "Mary", age: 29}.name` => fetch `:name` short notation
- `%{name: "Mary", age: 29}.born # ** (KeyError)` => blows an error when key does not exists
- `%{%{name: "Mary", age: 29} | age: 31}` => update value for existing key
- `%{%{name: "Mary", age: 29} | born: 1990} # ** (KeyError)` => blows an error when updating non existing key
- `map_size(%{name: "Mary"}) #=> 1` => map size

### Performance for Maps:

#### cheap functions:

- `%{name: "Mary", age: 29}[:name]` => fetch `:name`
- `%{name: "Mary", age: 29}.name` => fetch `:name` short notation
- `%{%{name: "Mary", age: 29} | age: 31}` => update value for existing key
- `map_size(%{name: "Mary"}) #=> 1` => map size

#### expensive functions:

## Structs

Structs are built in top of Map.

- `defstruct` => define a struct

```elixir
defmodule User do
  defstruct name: "John", age: 27
end
john = %User{} #=> %User{age: 27, name: "John"}
mary = %User{name: "Mary", age: 25} #=> %User{age: 25, name: "Mary"}
meg = %{john | name: "Meg"} #=> %User{age: 27, name: "Meg"}
bill = Map.merge(john, %User{name: "Bill", age: 23})

john.name #=> John
john[:name] #=> ** (UndefinedFunctionError) undefined function: User.fetch/2
is_map john #=> true
john.__struct__ #=> User
Map.keys(john) #=> [:__struct__, :age, :name]
```

## Ranges

Ranges are `Struct`.

- `range = 1..10` => range definition
- `Enum.reduce(1..3, 0, fn i, acc -> i + acc end) #=> 6` => range used in a reduce function to sum them up
- `Enum.count(range) #=> 10`
- `Enum.member?(range, 11) #=> false`

## Protocols

- `defprotocol Foo` => define protocol `Foo`
- `defimpl Foo, for Integer` => implement that protocol for `Integer`

Here are all native data types that you can use: `Atom`, `BitString`, `Float`, `Function`, `Integer`, `List`, `Map`, `PID`, `Port`, `Reference`, `Tuple`.

```elixir
defprotocol Blank do
  @doc "Returns true if data is considered blank/empty"
  def blank?(data)
end

defimpl Blank, for: Integer do
  def blank?(_), do: false
end

defimpl Blank, for: List do
  def blank?([]), do: true
  def blank?(_),  do: false
end

defimpl Blank, for: Map do
  def blank?(map), do: map_size(map) == 0
end

defimpl Blank, for: Atom do
  def blank?(false), do: true
  def blank?(nil),   do: true
  def blank?(_),     do: false
end

Blank.blank?(0) #=> false
Blank.blank?([]) #=> true
Blank.blank?([1, 2, 3]) #=> false
Blank.blank?("hello") #=> ** (Protocol.UndefinedError)
```

`Structs` do not share `Protocol` implementations with `Map`.

```elixir
defimpl Blank, for: User do
  def blank?(_), do: false
end
```

You can also implement a `Protocol` for `Any`. And in this case you can derive any `Struct`.

```elixir
defimpl Blank, for: Any do
  def blank?(_), do: false
end

defmodule DeriveUser do
  @derive Blank
  defstruct name: "john", age: 27
end
```

Elixir built-in most common used protocols: `Enumerable`, `String.Chars`, `Inspect`.

## Nested data Structures

- `put_in/2`
- `update_in/2`
- `get_and_update_in/2`

```elixir
users = [
  john: %{name: "John", age: 27, languages: ["Erlang", "Ruby", "Elixir"]},
  mary: %{name: "Mary", age: 29, languages: ["Elixir", "F#", "Clojure"]}
]
users[:john].age #=> 27

users = put_in users[:john].age, 31
users = update_in users[:mary].languages, &List.delete(&1, "Clojure")
```

## Enums and Streams

**Lists** and **Maps** are Enumerables.

`Enum` module perform **eager** operations, meanwhile `Stream` module perform **lazy** operations.

```elixir
# eager Enum
1..100 |> Enum.map(&(&1 * 3)) |> Enum.sum #=> 15150

# lazy Stream
1..100 |> Stream.map(&(&1 * 3)) |> Enum.sum #=> 15150
```

## do/end Keyword List and Block Syntax

In Elixir you can use either **Keyword List** syntax or  **do/end Block** syntax:

```elixir
sky = :gray

if sky == :blue do
  :sunny
else
  :cloudy
end

if sky == :blue, do: :sunny, else: :cloudy

if sky == :blue, do: (
  :sunny
), else: (
  :cloudy
)
```

## Conditional Flows (if/else/case/cond)

### if / else

```elixir
sky = :gray
if sky == :blue, do: :sunny, else: :cloudy
```

### unless / else

```elixir
sky = :gray
unless sky != :blue, do: :sunny, else: :cloudy
```

### case / when

```elixir
sky = {:gray, 75}
case sky, do: (
  {:blue, _}         -> :sunny
  {_, t} when t > 80 -> :hot
  _                  -> :check_wheather_channel
)
```

On **when guards** short-circuiting operators `&&`, `||` and `!` are **not** allowed.

### cond

`cond` is equivalent as `if/else-if/else` statements.

```elixir
sky = :gray
cond do: (
  sky == :blue -> :sunny
  true         -> :cloudy
)
```

## The `with` macro

- `with` => macro to combine multiple match clauses
- `<-` => a matching clause, on the left
- `=` => bare expression is allowed
- `else` => if some matching clause fails

```elixir
opts = %{width: 10, height: 20}
with {:ok, width} <- Map.fetch(opts, :width),
     {:ok, height} <- Map.fetch(opts, :height) do
  {:ok, width * height}
else
  :error ->
    {:error, :wrong_data}
end
#=> {:ok, 200}
```

## Recursion

There is traditional **no for loop** in Elixir, due to Elixir immutability There is a macro `for` that it's also called as `Comprehension` but it works differently from a traditional for loop. If you want a simple loop iteration you'll need to use **recursion**:

```elixir
defmodule Logger do
  def log(msg, n) when n <= 0, do: ()
  def log(msg, n) do
    IO.puts msg
    log(msg, n - 1)
  end
end
Logger.log("Hello World!", 3)
# Hello World!
# Hello World!
# Hello World!
```

In functional programming languages **map** and **reduce** are two major algorithm concepts. They can be implemented with **recursion** or using the `Enum` module.

**reduce** will reduces the array into a single element:

```elixir
defmodule Math do
  def sum_list(list, sum \\ 0)
  def sum_list([], sum), do: sum
  def sum_list([head | tail], sum) do
    sum_list(tail, head + sum)
  end
end
Math.sum_list([1, 2, 3]) #=> 6

Enum.reduce([1, 2, 3], 0, &+/2) #=> 6
```

**map** modifies an existing array (new array with new modified values):

```elixir
defmodule Math do
  def double([]), do: []
  def double([head | tail]) do
    [head * 2 | double(tail)]
  end
end
Math.double([1, 2, 3]) #=> [2, 4, 6]

Enum.map([1, 2, 3], &(&1 * 2)) #=> [2, 4, 6]
```

## Comprehension -> the for loop

`Comprehension` is a syntax sugar for the very powerful `for special form`. You can have **generators** and **filters** in that.

- `for` => `Comprehension`
- `->` => **generators**
- `:into` => change return to another `Collectable` type

You can iterate over `Enumerable` what makes so close to a regular `for` loop on other languages:

```elixir
for n <- [1, 2, 3, 4], do: n * n
#=> [1, 4, 9, 16]
```

You can also iterate over multiple `Enumerable` and then create a combination between them:

```elixir
for i <- [:a, :b, :c], j <- [1, 2], do:  {i, j}
#=> [a: 1, a: 2, b: 1, b: 2, c: 1, c: 2]
```

You can pattern match each element:

```elixir
values = [good: 1, good: 2, bad: 3, good: 4]
for {:good, n} <- values, do: n * n
#=> [1, 4, 16]
```

Generators use `->` and they have on the right an `Enumerable` and on the left a **pattern matchable** element variable.

You can have **filters** to filter **truthy** elements:

```elixir
for dir  <- [".", "/"],
    file <- File.ls!(dir),
    path = Path.join(dir, file),
    File.regular?(path) do
  "dir=#{dir}, file=#{file}, path=#{path}"
end
#=> ["dir=., file=README.md, path=./README.md", "dir=/, file=.DS_Store, path=/.DS_Store"]
```

You can use `:into` to change the return type:

```elixir
for k <- [:foo, :bar], v <- 1..5, into: %{}, do: {k, v}
#=> %{bar: 5, foo: 5}
for k <- [:foo, :bar], v <- 1..5, into: [], do: {k, v}
#=> [foo: 1, foo: 2, foo: 3, foo: 4, foo: 5, bar: 1, bar: 2, bar: 3, bar: 4, bar: 5]
```

## Anonymous Functions

- `fn` => define functions
- `->` => one line function definition
- `.` => call a function
- `when` => guards

```elixir
add = fn a, b -> a + b end
add.(4, 5) #=> 9
```

We can have multiple clauses and guards inside functions.

```elixir
calc = fn
  x, y when x > 0 -> x + y
  x, y -> x * y
end
calc.(-1, 6) #=> 5
calc.(4, 5) #=> 45
```

## Modules And Named Functions

- `defmodule` => define Modules
- `def`  => define functions inside Modules
- `defp`  => define private functions inside Modules
- `when` => guards
- `@` => module attributes
- `__info__(:functions)` => list functions inside a module
- `defdelegate` => delegate functions

```eilxir
defmodule Math do
  def sum(a, b) when is_integer(a) and is_integer(b), do: a + b
end

Math.sum(1, 2) #=> 3

Math.__info__(:functions) #=> [sum: 2]
```

Module attribute works as constants, evaluated at compilation time:

```eilxir
defmodule Math do
  @foo :bar
  def print, do: @foo
end

Math.print #=> :bar
```

Special Module attributes:

- `@vsn`
- `@moduledoc`
- `@doc`
- `@behaviour`
- `@before_compile`

## Default Argument

- `\\` => default argument

```elixir
defmodule Concat do
  def join(a, b, sep \\ " ") do
    a <> sep <> b
  end
end

IO.puts Concat.join("Hello", "world")      #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world
```

Default values are **evaluated runtime**.

```elixir
defmodule DefaultTest do
  def dowork(x \\ IO.puts "hello") do
    x
  end
end
DefaultTest.dowork #=> :ok
# hello
DefaultTest.dowork 123 #=> 123
DefaultTest.dowork #=> :ok
# hello
```

Function with multiple clauses and a default value requires a **function head** where default values are set:

```elixir
defmodule Concat do
  def join(a, b \\ nil, sep \\ " ") # head function

  def join(a, b, _sep) when is_nil(b) do
    a
  end

  def join(a, b, sep) do
    a <> sep <> b
  end
end

IO.puts Concat.join("Hello")               #=> Hello
IO.puts Concat.join("Hello", "world")      #=> Hello world
IO.puts Concat.join("Hello", "world", "_") #=> Hello_world
```

## Function Capturing

- `&` => function capturing
- `&1` => 1st argument

`&` could be used with a module function.

When capturing you can use the function/operator with its arity.

```elixir
&(&1 * &2).(3, 4) #=> 12
(&*/2).(3, 4) #=> 12

(&Kernel.is_atom(&1)).(:foo) #=> true
(&Kernel.is_atom/1).(:foo) #=> true
(&{:ok, [&1]}).(:foo) #=> {:ok, [:foo, :bar]}
(&[&1, &2]).(:foo, :bar) #=> [:foo, :bar]
(&[&1 | [&2]]).(:foo, :bar) #=> [:foo, :bar]
```

## Behaviours

Behaviour modules defines functions

- `@callback` => defines a function to be implemented by other modules
- `::` => separates the function definition to its return type

```elixir
defmodule Parser do
  @callback parse(String.t) :: any
  @callback extensions() :: [String.t]
end

defmodule JSONParser do
  @behaviour Parser

  def parse(str), do: # ... parse JSON
  def extensions, do: ["json"]
end
```

## Exceptions/Errors => raise/try/rescue

**Exceptions/Errors** in Elixir are `Structs`.

- `raise "oops" #=> ** (RuntimeError) oops` => raises error with message
- `raise ArgumentError #=> ** (ArgumentError) argument error` => raises an error by module
- `raise ArgumentError, message: "oops" #=> ** (ArgumentError) oops` => raises an error by module with message
- `defexception` => define an exception
- `try/rescue` => catches an error
- `throw/try/catch` => can be used as circuit breaking, but should be avoided
- `exit("my reason")` => exiting current process
- `after` => ensures some resource is cleaned up even if an exception was raised

```elixir
defmodule MyError do
  defexception message: "default message"
end

is_map %MyError{} #=> true
Map.keys %MyError{} #=> [:__exception__, :__struct__, :message]

raise MyError #=> ** (MyError) default message
raise MyError, message: "custom message" #=> ** (MyError) custom message
```

You can rescue an error with:

```elixir
try do
  raise "oops"
rescue
  e in RuntimeError -> e
after
  IO.puts "I can do some clean up here"
end
#=> %RuntimeError{message: "oops"}

try do
  raise "oops"
rescue
  RuntimeError -> "Error!"
end
#=> "Error!"
```

`throw/catch` sometime is used for circuit breaking, but you can usually use another better way:

```elixir
try do
  Enum.each -50..50, fn(x) ->
    if rem(x, 13) == 0, do: throw(x)
  end
  "Got nothing"
catch
  x -> "Got #{x}"
end
#=> "Got -39"

Enum.find -50..50, &(rem(&1, 13) == 0)
#=> -39
```

`exit` can be caught but this is rare in Elixir:

```elixir
try do
  exit "I am exiting"
catch
  :exit, _ -> "not really"
end
#=> "not really"
```

You can ommit `try` inside functions and use `rescue`, `catch`, `after` directly:

```elixir
def without_even_trying do
  raise "oops"
after
  IO.puts "cleaning up!"
end
```

## IO

- `IO.puts/1 "Hello"` => prints to stdout
- `IO.puts :stderr, "Hello"` => prints to stderr
- `IO.gets "yes/no: "` => reads an user input

## StringIO

- `{:ok, pid} = StringIO.open("my-file.md")` => open a file
- `IO.read(pid, 2) #=> "he"` => read first 2 lines

## File

- `{:ok, file} = File.open "hello", [:write]` => open file for reading
- `IO.binwrite file, "world"` => write into file
- `File.close file` => close file
- `File.read "my-file.md"` => reads a file
- `File.stream!("my-file.md") |> Enum.take(10)` => read the first 10 lines

```elixir
{:ok, file} = File.open "my-file.md", [:write]
IO.binwrite file, "hello world"
File.close file
File.read "my-file.md" #=> {:ok, "hello world"}
```

## Path

- `Path.join` => joins
- `Path.expand("~/hello")` => expands to full path

## Processes, Tasks and Agents

Process in Elixir has the same concept as threads in a lot of other languages, but extremely lightweight in terms of memory and CPU. They are isolated from each other and communicate via message passing.

- `spawn/1` => fork a process
- `self()` => current process
- `Process.alive?(pid)` => check if process is still running
- `send/2` => send message to another process
- `receive/1` => receive message from another process
- `after` => receive option to work with timeout
- `flush()` => prints out all messages received
- `spawn_link/1` => forks a process and link them, so failures are propagated
- `Task.start/1` => starts a task
- `Task.start_link/1` => starts a task and link it to the current process
- `Process.register(pid, :foo)` => register a name for a process

The idea is to have a supervisor that `spawn_link` new processes and when they fail the supervisor will restart them. This is the basics for **Fail Fast** and **Fault Tolerant** in Elixir.

Tasks are used in supervision trees.

```elixir
parent = self()

spawn_link(fn -> send(parent, {:hello, self()}) end)
receive do: ({msg, pid} -> "#{inspect pid} => #{msg}"), after: (1_000 -> "nothing after 1s")

Task.start_link(fn -> send(parent, {:hello, self()}) end)
receive do: ({msg, pid} -> "#{inspect pid} => #{msg}"), after: (1_000 -> "nothing after 1s")

flush()
```

**State** can be stored in processes or using its abstraction: `Agent`.

Manual implementation of a storage using Elixir processes:

```elixir
defmodule KV do
  def start_link do
    Task.start_link(fn -> loop(%{}) end)
  end

  defp loop(map) do
    receive do
      {:get, key, caller} ->
        send caller, Map.get(map, key)
        loop(map)
      {:put, key, value} ->
        loop(Map.put(map, key, value))
    end
  end
end
{:ok, pid} = KV.start_link

send pid, {:put, :hello, :world}
send pid, {:get, :hello, self()}
flush() #=> :world
```

Implementation of a storage using `Agent`:

```elixir
{:ok, pid} = Agent.start_link(fn -> %{} end)
Agent.update(pid, fn map -> Map.put(map, :hello, :world) end)
Agent.get(pid, fn map -> Map.get(map, :hello) end)
```

## alias, require, import and use

In order to facilitate code reuse Elixir has: `alias`, `require`, `import` (directives) and `use` (macro).

- `alias Foo.Bar, as: Bar` => alias module, so Bar can be called instead of Foo.Bar
- `alias Foo.Bar` => `as` is optional on alias
- `require Foo` => ensure the module is compiled and available (usually for macros)
- `import Foo` => requires and import functions from Foo so they can be called without the `Foo.` prefix
- `import List, only: [duplicate: 2]` => only option
- `import List, expect: [duplicate: 2]` => except option
- `import List, only: :macros` => import only macros
- `import List, only: :functions` => import only functions
- `use Foo` => invokes the custom code defined in Foo as an extension point
- `alias MyApp.{Foo, Bar, Baz}` => multiple alias
- `require MyApp.{Foo, Bar, Baz}` => multiple require
- `import MyApp.{Foo, Bar, Baz}` => multiple import

All modules are defines inside `Elixir` namespace but it can be omitted for convenience.

`alias`, `require` and `import` are lexically scoped, which means that it will be valid just inside the scope it was defined. This is **not a global scope**.

`require` is usually used to require Elixir macro code:

```elixir
Integer.is_odd(3) #=> ** (CompileError): you must require Integer before invoking the macro Integer.is_odd/1
require Integer
Integer.is_odd(3) #=> true
```

`use` call `__using__` when the module is being used:

```elixir
defmodule Fruit do
  defmacro __using__(option: option) do
    IO.puts "options=#{inspect option}"
    quote do: IO.puts "Using Fruit module"
  end
end

defmodule Meal do
  use Fruit, option: :hello
end
#=> "Good to see you've added Fruit to your meal"
```

## Meta Programming

- `quote` => shows AST (Abstract Syntax Tree)

```elixir
quote do: 2 * 2 == 4
#=> {
#=>   :==,
#=>   [context: Elixir, import: Kernel],
#=>   [
#=>     {
#=>       :*,
#=>       [context: Elixir, import: Kernel],
#=>       [2, 2]
#=>     },
#=>     4
#=>   ]
#=> }
```

## Erlang libraries

Elixir provider some Erlang modules as atoms.

- `:crypto` => crypto functions like `:crypto.hash/2`
- `:io` => io functions like `:io.format/2`
- `:digraph` => deal with digraphs
- `:ets` => large data structure in memory
- `:dets` => large data structure on disk
- `:math` => math functions like `:math.pi/0`
- `:queue` => first-in first-out structure
- `:rand` => rand functions like `:rand.uniform/0`
- `:zip` => handle zip files
- `:zlib` => handle gzip files


================================================
FILE: Git/README.md
================================================
# git-cheat-sheet
This is my personal git cheat sheet. This is not a deep dive into how git works, just some of the simple stuff.

# Contribute

Feel free to add to the repo or fix any mistakes you see.  Get started by

- Forking the repo.
- Clone your forked repo into your local machine.
- Create a new branch `git checkout -b your-contribution`.
- After making your changes, `git commit -am 'small message about what you did'`.
- Then push up into the remote repo with `git push origin HEAD`.
- Go to GitHub, go to your forked repo and you should see a yellow bar mentioning your branch.
- After hitting that button and reviewing your changes, hit the `Make Pull Request` button near the bottom.
- I will get an email, notifying me of your Pull Request (PR) and if it's good, I will merge it.

To keep your fork up to date

- add a remote upstream repository with 

  `$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git` (the original HTTPS clone Url)

- see all your remotes with `git remote -v`
  ```
  origin  https://github.com/black-shadows/rails.git (fetch)
  origin  https://github.com/black-shadows/rails.git (push)
  upstream  https://github.com/rails/rails.git (fetch)
  upstream  https://github.com/rails/rails.git (push) 
  ```
  - now you have a remote called **upstream** which is the original repo

- Then run `git pull upstream master`, to see your merged contribution on your local machine

# Overview

1. [Starting](#starting)
1. [Git Structure](#git-structure)
1. [Git Logs](#git-logs)
1. [Undo](#undo)
1. [Branches](#branches)
1. [Merging](#merging)
1. [Example Workflow](#example-workflow)
1. [Tricks](#tricks)
  - [Stripspace](#stripspace)
  - [Previous Branch](#previous-branch)
  - [Clean Status](#clean-status)
  - [Auto Correct](#auto-correct)
  - [Alias](#alias)
1. [Remotes](#remotes)
1. [GitHub](#github)
1. [Creating a Git Repo](#creating-a-git-repo)
1. [Git Clone](#git-clone)
1. [Reset](#reset)
1. [Update and Delete](#update-and-delete)
1. [Stash](#stash)
1. [Gitignore](#gitignore)
1. [Compare](#compare)
1. [Version Tags](#version-tags)
1. [Collaborate](#collaborate)
1. [Archive](#archive)
1. [Troubleshooting](#troubleshooting)
1. [Security](#security)
1. [Large File Storage](#large-file-storage)

## Starting

Starting is the easy part.  Make sure you have git installed by opening up your terminal and running,
```
git --version
```
If you're running osx or some form of linux, chances are you already have git installed.  If you're running windows, and/or just don't have git installed (it'll be obvious since entering the above command will spit out an unknown command error), head over to the [official site](https://git-scm.com/downloads) to download and install git for your computer

Now that you are sure you have a working version of git, it's time to create your working repository.

Go inside your project directory (in the terminal) and run `git init`, this will let git know you want it to start keeping track of your changes for this folder.
```
$ cd my_project
$ git init 
```
To verify, run `ls -al` and you should see the `.git` file, that is how you know you have git for this directory. If you no longer want to use git for this directory then simply delete the `.git` file.

**[⬆ back to top](#overview)**

## Git Structure

Git breaks things up into three 'trees' which are all maintained by git.

**Working Directory** : This is your current **local** tree. This just holds what's in your repository. 

**Staging** : (Or sometimes known as _index_) is - as the name implies - a staging tree. This will hold all the recent changes you have selected to go into the next commit (more on that later).

**HEAD** : Basically, a reference that usually points to the latest _commit_ for the repository.

Moving from one tree to another is simple.
```
# You must first move files that you have changed to the staging area.
# To specify a single file,
$ git add <filename>

# Alternatively, you can add all files that you have updated, added, or remove by entering,
$ git add -A

# This will put all the changes you've staged into a new commit. HEAD will now point to this newest commit.
$ git commit -m "commit message"

# You can do this all in online with.
$ git commit -am "commit message"
```

There is a caveat to using `git commit -am "commit message"`, it will not pick up on brand new files or files that have been deleted since the last commit.
We personally recommend going through this workflow:

```
git add -A # add all changes to the repo.
git commit -m "commit message"` # creates a new commit with all the changes you made.
```

**[⬆ back to top](#overview)**

## Git logs

The `git log` command is a way to see all previous commits made to the repository (whether by you or someone else)

```
$ git log

commit cd62a7d33d8c20255ef4ba59da61ff21acbf903b
Author: black-shadows <abhisheksharma.0517@gmail.com>
Date:   Fri Apr 3 03:14:41 2015 -0400

    one more method

commit 7b1db82140dc678eb869c742f0479ccf86168da5
Author: rperryng <ryanperrynguyen@gmail.com>
Date:   Fri Apr 3 03:14:08 2015 -0400

    succesfull merges ?

commit bdc7ede1047a698955bd5b419de1ad9cada68b2c
Merge: 8bc63cf cb6ae5f
Author: black-shadows <abhisheksharma.0517@gmail.com>
Date:   Fri Apr 3 03:12:54 2015 -0400

    Merge branch 'master' into random-branch
```

The large assortment of numbers and letters right next to the word commit is the sha_key, it's a specific hexadecimal value that references that particular commit.

- The author line is simple, it's the user that made the commit

- The date line is self-explanatory

- and finally the commit message. The commit message helps you understand what work you did within that commit so make sure to make them as verbose as you can, especially if you are working with a team. 

There is one more thing that I should point out here. If the git log is large enough, git will open it in `vim`, an editor for the terminal. To exit the git log, simply press `esc`, then `:`, then `q` and hit enter.

But if you want cleaner more readable information, definitely try the following:
```
$ git log --oneline -5

70693a1 Merge branch 'master' into random-branch
9f4b039 conflict feature 2 on master
aa87d8a branch conflict feature
1bde9e5 added a conflict feature
6f1c4d9 fourth feature was added
```
where `-5` is an option that lets you specify the number of most recent commits you want to see.  (You can use these options together with the other ones listed below).

To see all the commits made by one author,
```
$ git log --author=black-shadows
```
To see all your merges (we will talk about what a merge is later),
```
$ git log --merges
```
To see the repo history in a visual branching format,
```
$ git log --graph
```
To see all the other ways of viewing git logs, you can check out the [documentation](http://git-scm.com/docs/git-log).

**[⬆ back to top](#overview)**

## Undo

One of the most compelling reasons to use Git is that you can roll back to a previous snapshot (commit) of the repository, in case you've made a mistake.
However, reverting back to a specific commit can be really confusing if you've never done it before. Git gives you several ways to do it, and depending on the situation, one way is easier than another.

First, you'll want to identify which commit you want to roll back to.  enter `git log --oneline` and select the first 5-6 digits of the sha_key for the commit you want to return to.
I will be using the sha_key of 184353d9 (you usually only need the first 6-7 digits of your commit).  as the commit key that we want to return to.

##### Go back and checkout
1. There are no changes that have not been committed.
2. You just want to go back to an older commit, but you don't want to delete all your newer commits.

```
$ git checkout 184353d9

# Or 

$ git checkout -b new_branch_name 184353d9
```

##### Delete everything and just start restart from chosen commit
1. There are no changes that have not been committed.
2. You made a mistake and just need to go back to that commit, erasing everything you have done since then.

```
$ git reset --hard  184353d9
```
##### Start over from head or master
1. You just made some changes to files for testing ( you do not want to commit ).
2. You have not committed your changes yet.

```
$ git reset --hard HEAD
```
Remember that HEAD is (almost always) a pointer to the latest commit on that branch.

##### Ctrl + Z

1. You have no idea what you did, no idea where you are and you just want to go back

- The reflog command is the ultimate safety net. It keeps track of everything you just did, from checking out new branches, to rebases, the reflog is essentially a way to move back through time.


```
$ git reflog

# after finding the place you want to go back to 

$ git reset --hard <sha_key>
```

##### Correcting small mistakes
1. You've already made your commit and you've noticed something small that *should* have been in that commit (usually grammar, stale debug statements or comments).

This will allow you to *add* the changes to that most recent commit, as if it was there all along!
```
$ git commit --amend --no-edit
```

It's important to note that if you've already pushed the commit before fixing your mistake, you won't be able to push the corrected commit. This is because the remote repo and the local repo have conflicting versions of the same commit.  If you've been working on a branch that *only* you have been working on, you can force the remote repository to accept the corrected commit.  **you should only do this if you know no one else has pulled the *non* corrected commit already**.  This will almost always be the case if you have been working on your own branch!
```
$ git push -f
```

**[⬆ back to top](#overview)**

## Branches

The Master branch is the branch that you start in and it's the branch that you should never work directly on. Anytime you want to make changes to the project, you should checkout a different branch. Once you have finished implementing said feature you can then merge your branch into master. This is great because it allows you to organize your features and keep a controlled working version of the app to compare with.

Branches are a great way to start implementing new features. When you start making a new feature, you first run `git pull` on the master branch to make sure you have all the latest code.

- You should never be getting a merge error when doing a `git pull`. If you find yourself in this situation that means that you made a few commits on the master branch by accident. Stop the merge and make sure you're on a clean tree, then do this:

  ```
  $ git checkout -b temp-changes
  $ git reset --hard origin/master
  ```
- All your changes that should not have been on master have been moved to a separate branch (temp-changes). The second line then looks at the remote directory and just sets your local version of the master branch to the same one that is on origin (origin is the name of the remote branch, usually hosted on GitHub).

To create a new branch:
```
$ git checkout -b new_branch_name
```
Branch names should be descriptive to what you are trying to do. Their names cannot contain any spaces and its most common to use either `-` or `_` to separate the words

```
$ git checkout -b getting-live-messages-from-websocket
```
To see which branch you are currently in:

```
$ git status

# Or 

$ git branch
```
To merge a branch once you are done. We will be merging the `getting-live-messages-from-websocket` branch _into_ master

```
$ git checkout master
$ git merge getting-live-messages-from-websocket
```
**[⬆ back to top](#overview)**

## Merging 

##### Merge 
```
$ git merge branch_name
```

The `git merge` command by itself just puts all the commits into master, as if the branch you made never existed.  We personally recommend using the `--no-ff` (no fast forward) flag.  This will create a commit just for the act of merging your commits.  It will also preserve the fact that those commits were made on a branch.  If you are going to use the `--no-ff` flag, I also recommend using the `--no-edit` flag with it as well.  This will automatically create the commit message for you (something like `Merge branch <branch_name>`)
```
$ git merge add-tests-for-app-version --no-ff --no-edit
```

* When merging, you are usually on the master branch and merge with your own branch

##### Rebase

* When rebasing, you are usually on the branch you are working on.
* Rebase right before you decide merge with master

```
$ git rebase master
```
_Why Rebase?_, It's a great to make a clean looking tree, it appears as if you never created a branch to begin with. Remember a rebase is simply shifting the commit that your branch branched off of, to be the HEAD of master.

**[⬆ back to top](#overview)**

## Tricks

### Stripspace

- Removes trailing whitespace
- Collapse New lines
- Adds new lines to end of file

  - Simply pass in the file that you want to strip

  ```bash
  $ git stripspace < text_file.txt
  ```

### Previous Branch

- Quickly go back to your last branch

  ```bash
  $ git checkout - 
  ```

### Clean Status

- Add `-sb` to get a cleaner `git status`

  ```bash
  $ git status -sb
  ```

### Auto Correct

- Set auto correct to true for Git commands

  ```bash
  $ git config --global help.autocorrect 1
  ```

- Results in:

  ```bash
  $ git comit -m "commit message"
  # WARNING: You called a Git command named 'comit', which does not exist.
  # Continuing under the assumption that you meant 'commit'
  # in 0.1 seconds automatically...
  ```

### Alias

- Add shortcuts to reduce your typing

  ```bash
  $ git config --global alias.alias_command git_command
  ```

Examples:

- Set `git stat` to `git status -sb`

  ```bash
  $ git config --global alias.stat 'status -sb'
  ```

- Combine functions with `&&`

  ```bash
  $ git config --global alias.ac '!git add -A  && git commit'
  ```
  - The commit messages needs to be entered in from the editor if using the above alias 

## Merge Conflicts

If you try and perform a merge, there is a chance that you will end up with a merge conflict. Before we go over how to solve these problems, an important thing to learn is how to back out of the current predicament

```
$ git merge --abort
# or 
$ git rebase --abort
```
To see which files contain merge conflicts (assuming you haven't backed out yet). Just run:

```
$ git status
```
The important thing to remember here is that you have final say as to how the merge conflict is handled. If a co-worker spent hours and days on a feature that conflicted with yours, You can simply overwrite all their hard work. ( But let's try our best not to be so selfish ;) ).

##### Edit Conflicts
* Happens when two users edit the same lines of a file.

After opening up the file with the conflict you should see

```
<<<<<<< HEAD
def function_one
=======
def function_two
>>>>>>> your_branch
```
`your_branch` is the name of the branch that you are merging, `HEAD` is the latest commit on the branch that you are merging with. Going back to our example, `HEAD` would be, and usually is, the _HEAD_ of the master branch

After correcting the conflict,
```
$ git add .
$ git commit -am "fixing merge conflicts"
```

* If you want to simply take the changes that are in `HEAD`

```
$ git checkout --theirs <file_name_that_has_merge_conflict>
```

* If you want to keep your own changes

```
$ git checkout --yours <file_name_that_has_merge_conflict>
```

##### Removed files conflict 
* One person modified the file, while another deleted the file

you actually have two choices here, delete the file, or keep the changes

1. Keeping the file with new changes

    Simply add the file back and commit. (let's say the README.md file was modified)

    ```
    $ git add README.md 
    $ git commit 
    ```

2. deleting the file and disregarding the changes

Simply remove the file and commit:

```
$ git rm REAMDE.md 
$ git commit
```

If you had a conflict in the middle of a rebase, after fixing your conflicts run:

```
$ git add .
$ git rebase --continue
```
**[⬆ back to top](#overview)**

## Example Workflow

Now that you've seen all the bits and pieces, it would probably be helpful to see what the workflow with all these different commands looks like.

This is the typical situation.  You're working on a project which is being tracked by git.  You want to begin adding a feature or fixing a bug.
Begin by checking out a new branch with a descriptive branch name.  For demo purposes, the branch name will be `fix-readme-grammar`.
```
$ git checkout -b fix-readme-grammar
```

after making your changes, review your changes by running
```
$ git status
```
and usually
```
$ git diff
```
This will allow you to do a last minute review of your changes before deciding to make a new commit

Once you're satisfied, add the files to the staging area
```
$ git add -A
```

Now, create your new commit
```
$ git commit -m "Restructured commit section.  Fix spelling mistakes for introductory paragraph."
```
Of course, you can always combine these by entering `git add -A && git commit -m "commit message"`

Now you'll want to push your changes to the remote repo.  Since it's a new branch, you'll have to tell the remote repo that you want it to start tracking this new branch as well.  You can set up remote tracking and push at the same time by entering
```
$ git push -u origin fix-readme-grammar
```
After your first push, you can simply use `git push` for future commits on this branch.

Once you've made enough changes, commits, and pushes that you're happy enough to merge it back into master, you'll want to head over to github (or whatever service you're using for your remote repo) to submit a pull request.  Once you've got the OK to merge it back in to master,
```
$ git checkout master
$ git pull
$ git merge fix-readme-grammar --no-ff --no-edit
```

Lastly, you'll want to delete the branches, first on your remote...
```
$ git push origin --delete fix-readme-grammar
```

...and then on your local machine
```
$ git branch -d fix-readme-grammar
```

**[⬆ back to top](#overview)**

## Remotes

We are nearing the GitHub section so it's time to introduce **Remotes**

- When you use `git init` you just started git version control on that local directory (and child directory). But everything is maintained in your local machine. The concept of a remote is to start keeping a central version of the repository online, usually on a service like Github.

- First you have to actually create the remote repository, which is very simple to do. Just go on github.com and click the `New Repository` icon the nav bar

- Github will give you all the needed instructions as to how we move our project into the remote repo 

- By default the name of your repo and all remote repos are set to **origin**. Note that you never have to change this if you don't want to (most people don't) 

##### Push

- To push a new branch onto the remote repo

  ```
  $ git push -u <remote\_repo_name> <branch_name>
  ```

- Or to make things a little nicer 

  ```
  $ git push -u origin HEAD
  ```
- After that, you can usually just use `git push` to push to the matching branch on remote (though you may to have tell git you want `git push` to only push to the matching branch on the remote `git config --global push.default simple`, more on this [here](http://stackoverflow.com/a/948397/3194316))

  ```
  $ git push 
  ```
- This will push the current branch that you are working on 

The `-u` is short for `--set-upstream`, which just means that if you ever want to `pull` the remote branch, you simply have to type 
`git pull` while you are currently checked out in the local branch.

**[⬆ back to top](#overview)**

## GitHub

Github is a website that anyone can access and a great way to work on projects with other people. You can also use Github to contribute to open source, a great way to help everyone!

## Creating a Git Repo

- Go to the top right of the page and click on the create new button. Then pick `New repository`. 

- pick the name of the repo, the name should be the name for the project that you are working on. For example the name of this repo is
**git-cheat-sheet**

- You'll want to initialize with a README.md file. The README.md is a file that you want other people to read before looking at your project
For example, what you are reading right now is a README.md file. If you want to learn about Markdown, which is how you can make things look cool, read here: https://help.github.com/articles/github-flavored-markdown/

- And that's all! You have just created your remote repository. If you have an existing projects, you can import that project to this repo. If this is just the beginning, you can clone the remote repo to your local machine. 

## Git Clone

- If you look at the right side of a git repo's main page, you will see its _git clone_ URL. Copy that link to your clipboard, either with just `cmd + c` or by clicking on the clipboard icon. Then go to the local directory you want to clone the project to and run:

```
$ git clone <clone_link>

# example

$ git clone https://github.com/black-shadows/git-cheat-sheet.git
```

## Reset

Go back to commit:
`git revert 073791e7dd71b90daa853b2c5acc2c925f02dbc6`

Soft reset (move HEAD only; neither staging nor working dir is changed):
`git reset --soft 073791e7dd71b90daa853b2c5acc2c925f02dbc6`

Undo latest commit: `git reset --soft HEAD~ `

Mixed reset (move HEAD and change staging to match repo; does not affect working dir):
`git reset --mixed 073791e7dd71b90daa853b2c5acc2c925f02dbc6`

Hard reset (move HEAD and change staging dir and working dir to match repo):
`git reset --hard 073791e7dd71b90daa853b2c5acc2c925f02dbc6`


## Update and Delete

Test-Delete untracked files:
`git clean -n`

Delete untracked files (not staging):
`git clean -f`

Unstage (undo adds):
`git reset HEAD index.html`

Update most recent commit (also update the commit message):
`git commit --amend -m "New Message"`


## Stash

Put in stash:
`git stash save "Message"`

Show stash:
`git stash list`

Show stash stats:
`git stash show stash@{0}`

Show stash changes:
`git stash show -p stash@{0}`

Use custom stash item and drop it:
`git stash pop stash@{0}`

Use custom stash item and do not drop it:
`git stash apply stash@{0}`

Delete custom stash item:
`git stash drop stash@{0}`

Delete complete stash:
`git stash clear`


## Gitignore

About: https://help.github.com/articles/ignoring-files

Useful templates: https://github.com/github/gitignore

Add or edit gitignore: 
`nano .gitignore`

Track empty dir: 
`touch dir/.gitkeep`


## Compare

Compare modified files:
`git diff`

Compare modified files and highlight changes only:
`git diff --color-words index.html`

Compare modified files within the staging area:
`git diff --staged`

Compare branches:
`git diff master..branchname`

Compare branches like above:
`git diff --color-words master..branchname^`

Compare commits:
`git diff 6eb715d`
`git diff 6eb715d..HEAD`
`git diff 6eb715d..537a09f`

Compare commits of file:
`git diff 6eb715d index.html`
`git diff 6eb715d..537a09f index.html`

Compare without caring about spaces:
`git diff -b 6eb715d..HEAD` or:
`git diff --ignore-space-change 6eb715d..HEAD`

Compare without caring about all spaces:
`git diff -w 6eb715d..HEAD` or:
`git diff --ignore-all-space 6eb715d..HEAD`

Useful comparings:
`git diff --stat --summary 6eb715d..HEAD`

Blame:
`git blame -L10,+1 index.html`


## Version Tags

Show all released versions:
`git tag`

Show all released versions with comments:
`git tag -l -n1`

Create release version:
`git tag v1.0.0`

Create release version with comment:
`git tag -a v1.0.0 -m 'Message'`

Checkout a specific release version:
`git checkout v1.0.0`


## Collaborate

Show remote:
`git remote`

Show remote details:
`git remote -v`

Add remote upstream from GitHub project:
`git remote add upstream https://github.com/user/project.git`

Add remote upstream from existing empty project on server:
`git remote add upstream ssh://root@123.123.123.123/path/to/repository/.git`

Fetch:
`git fetch upstream`

Fetch a custom branch:
`git fetch upstream branchname:local_branchname`

Merge fetched commits:
`git merge upstream/master`

Remove origin:
`git remote rm origin`

Show remote branches:
`git branch -r`

Show all branches:
`git branch -a`

Create and checkout branch from a remote branch:
`git checkout -b local_branchname upstream/remote_branchname`

Compare:
`git diff origin/master..master`

Push (set default with `-u`):
`git push -u origin master`

Push:
`git push origin master`

Force-Push:
`git push origin master --force

Pull:
`git pull`

Pull specific branch:
`git pull origin branchname`

Fetch a pull request on GitHub by its ID and create a new branch:
`git fetch upstream pull/ID/head:new-pr-branch`

Clone to localhost:
`git clone https://github.com/user/project.git` or:
`git clone ssh://user@domain.com/~/dir/.git`

Clone to localhost folder:
`git clone https://github.com/user/project.git ~/dir/folder`

Clone specific branch to localhost:
`git clone -b branchname https://github.com/user/project.git`

Delete remote branch (push nothing):
`git push origin :branchname` or:
`git push origin --delete branchname`


## Archive

Create a zip-archive: `git archive --format zip --output filename.zip master`

Export/write custom log to a file: `git log --author=sven --all > log.txt`


## Troubleshooting

Ignore files that have already been committed to a Git repository: http://stackoverflow.com/a/1139797/1815847


## Security

Hide Git on the web via `.htaccess`: `RedirectMatch 404 /\.git` 
(more info here: http://stackoverflow.com/a/17916515/1815847)


## Large File Storage

Website: https://git-lfs.github.com/

Install: `brew install git-lfs`

Track `*.psd` files: `git lfs track "*.psd"` (init, add, commit and push as written above)

================================================
FILE: Golang/README.md
================================================
# Go Cheat Sheet

# Index
1. [Basic Syntax](#basic-syntax)
2. [Operators](#operators)
    * [Arithmetic](#arithmetic)
    * [Comparison](#comparison)
    * [Logical](#logical)
    * [Other](#other)
3. [Declarations](#declarations)
4. [Functions](#functions)
    * [Functions as values and closures](#functions-as-values-and-closures)
    * [Variadic Functions](#variadic-functions)
5. [Built-in Types](#built-in-types)
6. [Type Conversions](#type-conversions)
7. [Packages](#packages)
8. [Control structures](#control-structures)
    * [If](#if)
    * [Loops](#loops)
    * [Switch](#switch)
9. [Arrays, Slices, Ranges](#arrays-slices-ranges)
    * [Arrays](#arrays)
    * [Slices](#slices)
    * [Operations on Arrays and Slices](#operations-on-arrays-and-slices)
10. [Maps](#maps)
11. [Structs](#structs)
12. [Pointers](#pointers)
13. [Interfaces](#interfaces)
14. [Embedding](#embedding)
15. [Errors](#errors)
16. [Concurrency](#concurrency)
    * [Goroutines](#goroutines)
    * [Channels](#channels)
    * [Channel Axioms](#channel-axioms)
17. [Printing](#printing)
18. [Reflection](#reflection)
    * [Type Switch](#type-switch)
    * [Examples](https://github.com/a8m/reflect-examples)
19. [Snippets](#snippets)
    * [Http-Server](#http-server)

## Credits

Most example code taken from [A Tour of Go](http://tour.golang.org/), which is an excellent introduction to Go.
If you're new to Go, do that tour. Seriously.

## Go in a Nutshell

* Imperative language
* Statically typed
* Syntax tokens similar to C (but less parentheses and no semicolons) and the structure to Oberon-2
* Compiles to native code (no JVM)
* No classes, but structs with methods
* Interfaces
* No implementation inheritance. There's [type embedding](http://golang.org/doc/effective%5Fgo.html#embedding), though.
* Functions are first class citizens
* Functions can return multiple values
* Has closures
* Pointers, but not pointer arithmetic
* Built-in concurrency primitives: Goroutines and Channels

# Basic Syntax

## Hello World
File `hello.go`:
```go
package main

import "fmt"

func main() {
    fmt.Println("Hello Go")
}
```
`$ go run hello.go`

## Operators
### Arithmetic
|Operator|Description|
|--------|-----------|
|`+`|addition|
|`-`|subtraction|
|`*`|multiplication|
|`/`|quotient|
|`%`|remainder|
|`&`|bitwise and|
|`\|`|bitwise or|
|`^`|bitwise xor|
|`&^`|bit clear (and not)|
|`<<`|left shift|
|`>>`|right shift|

### Comparison
|Operator|Description|
|--------|-----------|
|`==`|equal|
|`!=`|not equal|
|`<`|less than|
|`<=`|less than or equal|
|`>`|greater than|
|`>=`|greater than or equal|

### Logical
|Operator|Description|
|--------|-----------|
|`&&`|logical and|
|`\|\|`|logical or|
|`!`|logical not|

### Other
|Operator|Description|
|--------|-----------|
|`&`|address of / create pointer|
|`*`|dereference pointer|
|`<-`|send / receive operator (see 'Channels' below)|

## Declarations
Type goes after identifier!
```go
var foo int // declaration without initialization
var foo int = 42 // declaration with initialization
var foo, bar int = 42, 1302 // declare and init multiple vars at once
var foo = 42 // type omitted, will be inferred
foo := 42 // shorthand, only in func bodies, omit var keyword, type is always implicit
const constant = "This is a constant"
```

## Functions
```go
// a simple function
func functionName() {}

// function with parameters (again, types go after identifiers)
func functionName(param1 string, param2 int) {}

// multiple parameters of the same type
func functionName(param1, param2 int) {}

// return type declaration
func functionName() int {
    return 42
}

// Can return multiple values at once
func returnMulti() (int, string) {
    return 42, "foobar"
}
var x, str = returnMulti()

// Return multiple named results simply by return
func returnMulti2() (n int, s string) {
    n = 42
    s = "foobar"
    // n and s will be returned
    return
}
var x, str = returnMulti2()

```

### Functions As Values And Closures
```go
func main() {
    // assign a function to a name
    add := func(a, b int) int {
        return a + b
    }
    // use the name to call the function
    fmt.Println(add(3, 4))
}

// Closures, lexically scoped: Functions can access values that were
// in scope when defining the function
func scope() func() int{
    outer_var := 2
    foo := func() int { return outer_var}
    return foo
}

func another_scope() func() int{
    // won't compile because outer_var and foo not defined in this scope
    outer_var = 444
    return foo
}


// Closures
func outer() (func() int, int) {
    outer_var := 2
    inner := func() int {
        outer_var += 99 // outer_var from outer scope is mutated.
        return outer_var
    }
    inner()
    return inner, outer_var // return inner func and mutated outer_var 101
}
```

### Variadic Functions
```go
func main() {
	fmt.Println(adder(1, 2, 3)) 	// 6
	fmt.Println(adder(9, 9))	// 18

	nums := []int{10, 20, 30}
	fmt.Println(adder(nums...))	// 60
}

// By using ... before the type name of the last parameter you can indicate that it takes zero or more of those parameters.
// The function is invoked like any other function except we can pass as many arguments as we want.
func adder(args ...int) int {
	total := 0
	for _, v := range args { // Iterates over the arguments whatever the number.
		total += v
	}
	return total
}
```

## Built-in Types
```
bool

string

int  int8  int16  int32  int64
uint uint8 uint16 uint32 uint64 uintptr

byte // alias for uint8

rune // alias for int32 ~= a character (Unicode code point) - very Viking

float32 float64

complex64 complex128
```

## Type Conversions
```go
var i int = 42
var f float64 = float64(i)
var u uint = uint(f)

// alternative syntax
i := 42
f := float64(i)
u := uint(f)
```

## Packages
* Package declaration at top of every source file
* Executables are in package `main`
* Convention: package name == last name of import path (import path `math/rand` => package `rand`)
* Upper case identifier: exported (visible from other packages)
* Lower case identifier: private (not visible from other packages)

## Control structures

### If
```go
func main() {
	// Basic one
	if x > 0 {
		return x
	} else {
		return -x
	}

	// You can put one statement before the condition
	if a := b + c; a < 42 {
		return a
	} else {
		return a - 42
	}

	// Type assertion inside if
	var val interface{}
	val = "foo"
	if str, ok := val.(string); ok {
		fmt.Println(str)
	}
}
```

### Loops
```go
    // There's only `for`, no `while`, no `until`
    for i := 1; i < 10; i++ {
    }
    for ; i < 10;  { // while - loop
    }
    for i < 10  { // you can omit semicolons if there is only a condition
    }
    for { // you can omit the condition ~ while (true)
    }
```

### Switch
```go
    // switch statement
    switch operatingSystem {
    case "darwin":
        fmt.Println("Mac OS Hipster")
        // cases break automatically, no fallthrough by default
    case "linux":
        fmt.Println("Linux Geek")
    default:
        // Windows, BSD, ...
        fmt.Println("Other")
    }

    // as with for and if, you can have an assignment statement before the switch value
    switch os := runtime.GOOS; os {
    case "darwin": ...
    }

    // you can also make comparisons in switch cases
    number := 42
    switch {
        case number < 42:
            fmt.Println("Smaller")
        case number == 42:
            fmt.Println("Equal")
        case number > 42:
            fmt.Println("Greater")
    }

    // cases can be presented in comma-separated lists
    var char byte = '?'
    switch char {
        case ' ', '?', '&', '=', '#', '+', '%':
            fmt.Println("Should escape")
    }
```

## Arrays, Slices, Ranges

### Arrays
```go
var a [10]int // declare an int array with length 10. Array length is part of the type!
a[3] = 42     // set elements
i := a[3]     // read elements

// declare and initialize
var a = [2]int{1, 2}
a := [2]int{1, 2} //shorthand
a := [...]int{1, 2} // elipsis -> Compiler figures out array length
```

### Slices
```go
var a []int                              // declare a slice - similar to an array, but length is unspecified
var a = []int {1, 2, 3, 4}               // declare and initialize a slice (backed by the array given implicitly)
a := []int{1, 2, 3, 4}                   // shorthand
chars := []string{0:"a", 2:"c", 1: "b"}  // ["a", "b", "c"]

var b = a[lo:hi]	// creates a slice (view of the array) from index lo to hi-1
var b = a[1:4]		// slice from index 1 to 3
var b = a[:3]		// missing low index implies 0
var b = a[3:]		// missing high index implies len(a)
a =  append(a,17,3)	// append items to slice a
c := append(a,b...)	// concatenate slices a and b

// create a slice with make
a = make([]byte, 5, 5)	// first arg length, second capacity
a = make([]byte, 5)	// capacity is optional

// create a slice from an array
x := [3]string{"Лайка", "Белка", "Стрелка"}
s := x[:] // a slice referencing the storage of x
```

### Operations on Arrays and Slices
`len(a)` gives you the length of an array/a slice. It's a built-in function, not a attribute/method on the array.

```go
// loop over an array/a slice
for i, e := range a {
    // i is the index, e the element
}

// if you only need e:
for _, e := range a {
    // e is the element
}

// ...and if you only need the index
for i := range a {
}

// In Go pre-1.4, you'll get a compiler error if you're not using i and e.
// Go 1.4 introduced a variable-free form, so that you can do this
for range time.Tick(time.Second) {
    // do it once a sec
}

```

## Maps

```go
var m map[string]int
m = make(map[string]int)
m["key"] = 42
fmt.Println(m["key"])

delete(m, "key")

elem, ok := m["key"] // test if key "key" is present and retrieve it, if so

// map literal
var m = map[string]Vertex{
    "Bell Labs": {40.68433, -74.39967},
    "Google":    {37.42202, -122.08408},
}

```

## Structs

There are no classes, only structs. Structs can have methods.
```go
// A struct is a type. It's also a collection of fields

// Declaration
type Vertex struct {
    X, Y int
}

// Creating
var v = Vertex{1, 2}
var v = Vertex{X: 1, Y: 2} // Creates a struct by defining values with keys
var v = []Vertex{{1,2},{5,2},{5,5}} // Initialize a slice of structs

// Accessing members
v.X = 4

// You can declare methods on structs. The struct you want to declare the
// method on (the receiving type) comes between the the func keyword and
// the method name. The struct is copied on each method call(!)
func (v Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X + v.Y*v.Y)
}

// Call method
v.Abs()

// For mutating methods, you need to use a pointer (see below) to the Struct
// as the type. With this, the struct value is not copied for the method call.
func (v *Vertex) add(n float64) {
    v.X += n
    v.Y += n
}

```
**Anonymous structs:**
Cheaper and safer than using `map[string]interface{}`.
```go
point := struct {
	X, Y int
}{1, 2}
```

## Pointers
```go
p := Vertex{1, 2}  // p is a Vertex
q := &p            // q is a pointer to a Vertex
r := &Vertex{1, 2} // r is also a pointer to a Vertex

// The type of a pointer to a Vertex is *Vertex

var s *Vertex = new(Vertex) // new creates a pointer to a new struct instance
```

## Interfaces
```go
// interface declaration
type Awesomizer interface {
    Awesomize() string
}

// types do *not* declare to implement interfaces
type Foo struct {}

// instead, types implicitly satisfy an interface if they implement all required methods
func (foo Foo) Awesomize() string {
    return "Awesome!"
}
```

## Embedding

There is no subclassing in Go. Instead, there is interface and struct embedding.

```go
// ReadWriter implementations must satisfy both Reader and Writer
type ReadWriter interface {
    Reader
    Writer
}

// Server exposes all the methods that Logger has
type Server struct {
    Host string
    Port int
    *log.Logger
}

// initialize the embedded type the usual way
server := &Server{"localhost", 80, log.New(...)}

// methods implemented on the embedded struct are passed through
server.Log(...) // calls server.Logger.Log(...)

// the field name of the embedded type is its type name (in this case Logger)
var logger *log.Logger = server.Logger
```

## Errors
There is no exception handling. Functions that might produce an error just declare an additional return value of type `Error`. This is the `Error` interface:
```go
type error interface {
    Error() string
}
```

A function that might return an error:
```go
func doStuff() (int, error) {
}

func main() {
    result, err := doStuff()
    if err != nil {
        // handle error
    } else {
        // all is good, use result
    }
}
```

# Concurrency

## Goroutines
Goroutines are lightweight threads (managed by Go, not OS threads). `go f(a, b)` starts a new goroutine which runs `f` (given `f` is a function).

```go
// just a function (which can be later started as a goroutine)
func doStuff(s string) {
}

func main() {
    // using a named function in a goroutine
    go doStuff("foobar")

    // using an anonymous inner function in a goroutine
    go func (x int) {
        // function body goes here
    }(42)
}
```

## Channels
```go
ch := make(chan int) // create a channel of type int
ch <- 42             // Send a value to the channel ch.
v := <-ch            // Receive a value from ch

// Non-buffered channels block. Read blocks when no value is available, write blocks until there is a read.

// Create a buffered channel. Writing to a buffered channels does not block if less than <buffer size> unread values have been written.
ch := make(chan int, 100)

close(ch) // closes the channel (only sender should close)

// read from channel and test if it has been closed
v, ok := <-ch

// if ok is false, channel has been closed

// Read from channel until it is closed
for i := range ch {
    fmt.Println(i)
}

// select blocks on multiple channel operations, if one unblocks, the corresponding case is executed
func doStuff(channelOut, channelIn chan int) {
    select {
    case channelOut <- 42:
        fmt.Println("We could write to channelOut!")
    case x := <- channelIn:
        fmt.Println("We could read from channelIn")
    case <-time.After(time.Second * 1):
        fmt.Println("timeout")
    }
}
```

### Channel Axioms
- A send to a nil channel blocks forever

  ```go
  var c chan string
  c <- "Hello, World!"
  // fatal error: all goroutines are asleep - deadlock!
  ```
- A receive from a nil channel blocks forever

  ```go
  var c chan string
  fmt.Println(<-c)
  // fatal error: all goroutines are asleep - deadlock!
  ```
- A send to a closed channel panics

  ```go
  var c = make(chan string, 1)
  c <- "Hello, World!"
  close(c)
  c <- "Hello, Panic!"
  // panic: send on closed channel
  ```
- A receive from a closed channel returns the zero value immediately

  ```go
  var c = make(chan int, 2)
  c <- 1
  c <- 2
  close(c)
  for i := 0; i < 3; i++ {
      fmt.Printf("%d ", <-c)
  }
  // 1 2 0
  ```

## Printing

```go
fmt.Println("Hello, 你好, नमस्ते, Привет, ᎣᏏᏲ") // basic print, plus newline
p := struct { X, Y int }{ 17, 2 }
fmt.Println( "My point:", p, "x coord=", p.X ) // print structs, ints, etc
s := fmt.Sprintln( "My point:", p, "x coord=", p.X ) // print to string variable

fmt.Printf("%d hex:%x bin:%b fp:%f sci:%e",17,17,17,17.0,17.0) // c-ish format
s2 := fmt.Sprintf( "%d %f", 17, 17.0 ) // formatted print to string variable

hellomsg := `
 "Hello" in Chinese is 你好 ('Ni Hao')
 "Hello" in Hindi is नमस्ते ('Namaste')
` // multi-line string literal, using back-tick at beginning and end
```

## Reflection
### Type Switch
A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.
```go
func do(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Printf("Twice %v is %v\n", v, v*2)
	case string:
		fmt.Printf("%q is %v bytes long\n", v, len(v))
	default:
		fmt.Printf("I don't know about type %T!\n", v)
	}
}

func main() {
	do(21)
	do("hello")
	do(true)
}
```

# Snippets

## HTTP Server
```go
package main

import (
    "fmt"
    "net/http"
)

// define a type for the response
type Hello struct{}

// let that type implement the ServeHTTP method (defined in interface http.Handler)
func (h Hello) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello!")
}

func main() {
    var h Hello
    http.ListenAndServe("localhost:4000", h)
}

// Here's the method signature of http.ServeHTTP:
// type Handler interface {
//     ServeHTTP(w http.ResponseWriter, r *http.Request)
// }
```




================================================
FILE: Java/README.md
================================================
# Java Cheat Sheet
Review Java 9 Concepts at Jet Speed.

### Complete Java Course
- https://www.udemy.com/java-programming-tutorial-for-beginners/

## Introduction

## Background

### Popularity of Java
- Platform Independent or Portable
- Object Oriented Language
- Security 
- Rich API
- Great IDE's
- Omnipresent 
   - Web Applications (Java EE (JSP, Servlets), Spring, Struts..)
   - Mobile Apps(Android) 
   - Microservices (Spring Boot)

### Platform Independence
- Build once, run anywhere
![alt text](images/java-write-once-run-anywhere.png)
- Java bytecode is the instruction set of the Java virtual machine


```
graph TD
A[Java Code] -->|Compiled| B(Bytecode)
B --> C{Run}
C -->|bytecode| D[Windows JVM] 
D --> K[Windows Instructions]
C -->|bytecode| E[Unix  JVM]
E --> L[Unix Instructions]
C -->|bytecode| F[Linux  JVM]
F --> M[Linux Instructions]
C -->|bytecode| G[Any other platform  JVM]
G --> N[Linux Instructions]
```

### JDK vs JVM VS JRE

- JVM (Java Virtual Machine)
  - runs the Java bytecode.
- JRE
  - JVM + Libraries + Other Components (to run applets and other java applications)
- JDK
  - JRE + Compilers + Debuggers

### ClassLoader

- Find and Loads Java Classes!

Three Types
- System Class Loader - Loads all application classes from CLASSPATH
- Extension Class Loader - Loads all classes from extension directory
- Bootstrap Class Loader - Loads all the Java core files

Order of execution of ClassLoaders
- JVM needs to find a class, it starts with System Class Loader. 
- If it is not found, it checks with Extension Class Loader. 
- If it not found, it goes to the Bootstrap Class Loader. 
- If a class is still not found, a ClassNotFoundException is thrown.

### First Java Program

```java
public class HelloWorld {
    public static void main(String[] args) {
System.out.println("Hello World");
    }

}
```

Notes
- Every line of code we write in Java is part of something called Class. We will talk about Class later. 
- First line defines a public class called HelloWorld. All the code in a class is between { and }.
- When a program runs, Java should know which line of code has to be run first. public static void main(String[] args) is the first method that is run when a program is executed.


> Java, like any other programming language, is particular about syntax!!


### Using Java and JavaC
There are two steps involved in running a Java Program
- Compilation
- Execution

#### Compilation
We use javac to compile java code. 
- Open CommandPrompt/Terminal and cd to the folder where HelloWorld.java file is present
- execute the command below
```
javac HelloWorld.java
```
- You should see two files HelloWorld.java and HelloWorld.class in the folder.
- HelloWorld.class contains the java bytecode

#### Execution
- Now we can run the program using JVM
- execute the command below
```
java HelloWorld
```
- You should see the output "Hello World" printed in the console.

### Class and Object
- What is a class?
- Definining an instance of a class - an object
- Invoking a method on the object

### Variables
- Value of a variable changes during the course of a program execution.

```
int number;
number = 5;
System.out.println(number);//5
number = number + 2;
System.out.println(number);//7
number = number + 2;
System.out.println(number);//9
```

Declaring and Initializing Variables
- Declaration is give a variable a name and type

```
TYPE variableName;
```

#### Tips
- Two or more variables of single type can be declared together.
- All six numeric types in Java are signed.

### Primitive Variables

Variables that store value.


Java defines few types like int (numbers), float(floating point numbers), char (characters). Variables of these types store the value of the variable directly. These are not objects. These are called primitive variables. 

An example is shown below: Primitive Variables contains bits representing the value of the variable.

```
int value = 5;

```
Different primitive types in java are char, boolean, byte, short, int, long, double, or float. Because of these primitive types, Java is NOT considered to be a pure objected oriented language.

Numeric Data Types
- Types  : byte, short, int, long, float, double
- Number of bits : 8, 16, 32, 64, 32, 64
- Range  : -x to x-1 where x = Power(2, number of bits -1)

char Data Type
- Used to store characters. Size of character is 16 bits.

Examples

```
int i = 15;
long longValue = 1000000000000l;
byte b = (byte)254;

float f = 26.012f;
double d = 123.567;
boolean isDone = true;
boolean isGood = false;
char ch = 'a';
char ch2 = ';';
```

### Reference Variables

```
Animal dog = new Animal();
```

The instance of new Animal - Animal object - is created in memory. The memory address of the object created is stored in the dog reference variable.

Reference Variables contains a reference or a guide to get to the actual object in memory.

#### Puzzles

```
Animal dog1 = new Animal();
dog1 = new Animal();
```

What will happen?
Two objects of type Animal are created. Only one reference variable is created.


```
Animal animal1 = new Animal();
Animal animal2 = new Animal();
animal1 = animal2;

```

What will happen? What would happen if the same was done with primitive variables?

### Identifiers
Names given to a class, method, interface, variables are called identifiers.

Legal Identifier Names
- Combination of letters, numbers, $ and under-score(_)
- Cannot start with a number
- Cannot be a keyword
- No limit on length of identifier

### Java Keywords
List of Java Keywords
- Primitives DataTypes    : byte,short,int,long,float,double,char,boolean
- Flow Control    : if, else,for,do, while, switch, case, default, break,
      continue,return
- Exception Handling      : try, catch, finally,throw,throws,assert
- Modifiers       : public,private,protected,final,static,native,abstract,
      synchronized,transient,volatile,strictfp
- Class Related   : class,interface,package,extends,implements,import
- Object Related  : new, instanceof,super,this
- Literals    : true, false, null
- Others      : void, enum
- Unused  : goto,const

### Literals
Any primitive data type value in source code is called Literal.

There are four types of literals:
- Integer & Long
- Floating Point
- Boolean
- Double

#### Literals

Integer Literals
- There are 3 ways of representing an Integer Literal. 
  - Decimal. Examples: 343, 545
  - Octal. Digits 0 to 7. Place 0 before a number. Examples : 070,011
  - Hexadecimal. Digits 0 to 9 and alphabets A to F (10-15). Case insensitive.
- An integer literal by default is int.

Long Literals 
- All 3 integer formats: Decimal, Octal and Hexadecimal can be used to represent long by appending with L or l.

Floating point Literals
- Numbers with decimal points. Example: ```double d = 123.456;```
- To declare a float, append f. Example: float f = 123.456f;
- Floating point literals are double by default.
- Appending d or D at end of double literal is optional Example: ```double d = 123.456D;```

Boolean Literals
- Valid boolean values are true and false. 
- TRUE, FALSE or True, False are invalid.

Character Literals
- Represented by single character between single quotes  Example: ```char a = 'a'```
- Unicode Representation also can be used. Prefix with \u. Example: char letterA = '\u0041';
- A number value can also be assigned to character. Example: char letterB = 66; Numeric value can be from 0 to 65535;
- Escape code can be used to represent a character that cannot be typed as literal. Example: char newLine = '\n';

#### Puzzles 

```
int eight = 010; 
int nine=011;  
int invalid = 089;//COMPILER ERROR! 8 and 9 are invalid in Octal
int sixteen = 0x10; 
int fifteen = 0XF; 
int fourteen = 0xe;
int x = 23,000;
long a = 123456789l; 
long b = 0x9ABCDEFGHL; 
long c = 0123456789L;

float f = 123.456;//COMPILER ERROR! A double value cannot be assigned to a float.

boolean b = true; boolean b=false;
boolean b = TRUE;//COMPILATION ERROR
boolean b = 0; //COMPILER ERROR. This is not C Language

char ch = a;
char a = 97;
char ch1 = 66000; //COMPILER ERROR!
```

### Tip - Assignment Operator
Assignment operator evaluates the expression on the right hand side and copies the value into the variable on the left hand side. 

#### Basic Examples
```
int value = 35;//35 is copied into 35

int squareOfValue = value * value;//value * value = 35 * 35 is stored into squareOfValue

int twiceOfValue = value * 2;
```

#### Puzzles

```
int a1 = 5;
int b1 = 6;
b1 = a1; // value of a1 is copied into b1
a1 = 10; // If we change a1 or b1 after this, it would not change the other variable.. b1 will remain 6

Actor actor1 = new Actor();
actor1.setName("Actor1");
//This creates new reference variable actor1 of type Actor  new Actor() on the heap assigns the new Actor on the heap to reference variable

Actor actor2 = actor1;
actor2.setName("Actor2");
System.out.println(actor1.getName());//Actor2

```

### Casting -  Implicit and Explicit

Casting is used when we want to convert one data type to another. 

- A literal integer is by default int. Operation involving int-sized or less always result in int.
- Floating point literals are by default double

#### Implicit Casting

- Implicit Casting is done directly by the compiler.
  - Example : Widening Conversions i.e. storing smaller values in larger variable types.


```
byte b = 10; //byte b = (int) 10; Example below compiles because compiler introduces an implicit cast.

short n1 = 5;
short n2 = 6;
//short sum = n1 + n2;//COMPILER ERROR
short sum = (short)(n1 + n2);//Needs an explicit cast

byte b = 5;
b += 5; //Compiles because of implicit conversion

int value = 100;
long number = value; //Implicit Casting
float f = 100; //Implicit Casting 
```

#### Explicit Casting
- Explicit Casting needs to be specified by programmer in code.
  - Example: Narrowing Conversions. Storing larger values into smaller variable types;
- Explicit casting would cause truncation of value if the value stored is greater than the size of the variable.

```
long number1 = 25678;
int number2 = (int)number1;//Explicit Casting
//int x = 35.35;//COMPILER ERROR
int x = (int)35.35;//Explicit Casting

int bigValue = 280;
byte small = (byte) bigValue;
System.out.println(small);//output 24. Only 8 bits remain.

//float avg = 36.01;//COMPILER ERROR. Default Double
float avg = (float) 36.01;//Explicit Casting
float avg1 = 36.01f;
float avg2 = 36.01F; //f or F is fine

//byte large = 128; //Literal value bigger than range of variable type causes compilation error
byte large = (byte) 128;//Causes Truncation!
```

#### Compound Assignment Operators

- Examples : +=, -=, *= 

```
int a = 5;
a += 5; //similar to a = a + 5;
a *= 10;//similar to a = a * 10;
a -= 5;//similar to a = a - 5;
a /= 5;//similar to a = a / 5;
```


### Other Operators

#### Remainder(%) Operator

- Remainder when one number is divided by another.

```
System.out.println(10 % 4);//2
System.out.println(15 % 4);//3
```

#### Conditional Operator
- Conditional Operator is a Ternary Operator (3 Operands)
- syntax : ```booleanCondition ? ResultIfTrue: ResultIfFalse;```

```
int age = 18;

System.out.println(
age >= 18 ? "Can Vote": "Cannot Vote");//Can Vote

age = 15;

System.out.println(
age >= 18 ? "Can Vote": "Cannot Vote");//Cannot Vote
```

### Passing Variables to Methods

- All variables , primitives and references , in Java, are passed to functions using copy-of-variable-value.

#### Passing Variables to Methods : Example
- Passing a primitive variable and modifying the value in a method
- Passing a reference variable and modifying the value in a method

#### Returning a Value From Method
- null is a valid return value for an object.
- You can return andy type that can be implicitly coverted to return type.
- You cannot return anything from a void method.

### Types of Variables

- Different Types of Variables: Static, Member (or instance), Local, Block

#### Instance Variables
- Declared inside a class outside any method.
- Each instance of the class would have its own values.
- Also called member value, field or property.

#### Local Variables
- Variables declared in a method
- Local Variables can only be marked with final modifier
- If the name of a Local Variable is same as the name of an instance variable, it results in shadowing.

#### Member Variables
- Defined at class level and without keyword static.

#### Static Variable
- Defined at class level and using keyword static.

#### Member Variable and Static Variable
- Member Variables can be accessed only through object references.
- Static Variables can be accessed through a. Class Name and b. Object Reference. It is NOT recommended to use object reference to refer to static variables.

#### Example Static and Member Variables
```
public class StaticAndMemberVariables {
    public static void main(String[] args) {
Actor actor1 = new Actor();
actor1.name = "ACTOR1";
//Actor.name //Compiler Error

//Below statement can be written as actor1.count++
//But NOT recommended.
Actor.count++;

Actor actor2 = new Actor();
actor2.name = "ACTOR2";

//Below statement can be written as actor2.count++
//But NOT recommended.
Actor.count++;

System.out.println(actor1.name);//ACTOR1
System.out.println(actor2.name);//ACTOR2

//Next 3 statements refer to same variable
System.out.println(actor1.count);//2
System.out.println(actor2.count);//2
System.out.println(Actor.count);//2
    }
}

class Actor {
    //RULE 1: Member Variables can be accessed 
    //only through object references
    String name;
    
    //RULE 2:Static Variables can be accessed 
    //through a.Class Name and b.Object Reference
    //It is NOT recommended to use object reference 
    //to refer to static variables.
    static int count;    
}
```

### Scope of a Variable
- Scope of a variable defines where (which part of code) a variable can be accessed.

#### Important Rules
- Static Variable can be used anywhere in the class.
- Member Variable can be used in any non-static method.
- Local Variable can be used only in the method where it is declared.
- Block Variable can be used only in the block (code between { and }) where it is declared.

#### Variable Scope Examples
Below code shows all these Rules in action:
```

public class VariablesExample {
    //RULE 1:Static Variable can be used anywhere in the class. 
    static int staticVariable;
    
    //RULE 2:Member Variable can be used in any non-static method. 
    int memberVariable;
    
    void method1() {
		//RULE 3: method1LocalVariable can be used only in method1.
		int method1LocalVariable;

		memberVariable = 5;//RULE 2
		staticVariable = 5;//RULE 1

		//Some Code
		{
		    //RULE 4:blockVariable can be used only in this block.
		    int blockVariable;
		    //Some Code
		}

		//blockVariable = 5;//COMPILER ERROR - RULE 4
    }
    
    void method2() {
		//method1LocalVariable = 5; //COMPILER ERROR - RULE3
    }
    
    static void staticMethod() {
		staticVariable = 5;//RULE 1
		//memberVariable = 5; //COMPILER ERROR - RULE 2
    }
}
```

#### Scope Example 1
- staticVariable is declared using keyword static. 
- It is available in the instance method method1 and static method named staticMethod.

#### Scope Example 2
- memberVariable is declared directly in the class  and does NOT use keyword static. So, it is an instance variable. 
- It is available in the instance method method1 but not accessible in the static method named staticMethod.

#### Scope Example 3
- method1LocalVariable is declared in the method method1. So, it is a local variable. 
- It is available in the instance method method1 but available in any other  instance or static methods.

#### Scope Example 4
- blockVariable is declared in a block in method1. So, it is a block variable. 
- It is available only in the block where it is defined. 
- It is not accessible any where out side the block , even in the same method.

### Variable Initialization
- Initialization defines the default value assigned to a variable if it is not initialized.

#### Important Rules
- Member/Static variables are alway initialized with default values.
- Default values for numeric types is 0, floating point types is 0.0, boolean is false, char  is '\u0000' and for a object reference variable is null.
- Local variables are not initialized by default by compiler. 
- Using a local variable before initialization results in a compilation error.
- Assigning a null value is a valid initialization for reference variables.

#### Variable Initialization Examples
Lets look at an example program to understand all the rules regarding variable initialization.

```
package com.in28minutes.variables;

//RULE1:Member/Static variables are alway initialized with 
//default values.Default values for numeric types is 0, 
//floating point types is 0.0, boolean is false, 
//char  is '\u0000' and object reference variable is null.

//RULE2:Local/block variables are NOT initialized by compiler. 

//RULE3    :If local variables are used before initialization, 
//it would result in Compilation Error

public class VariableInitialization {
    public static void main(String[] args) {
		Player player = new Player();

		//score is an int member variable - default 0
		System.out.println(player.score);//0 - RULE1

		//name is a member reference variable - default null
		System.out.println(player.name);//null - RULE1

		int local; //not initialized
		//System.out.println(local);//COMPILER ERROR! RULE3

		String value1;//not initialized
		//System.out.println(value1);//COMPILER ERROR! RULE3

		String value2 = null;//initialized
		System.out.println(value2);//null - NO PROBLEM.
    }
}


class Player{
    String name;
    int score;
}
```
#### Initialization Example 1
- player  is an instance of the class Player. It contains member variables named name and score. 
- All member variables are initialized by default. Since name refers to a String i.e a reference variable it is initialized to null. score is an int variable and hence initialized to 0.

#### Initialization Example 2 
- local  is a local variable defined in the main method. 
- An attempt to access a local variable without initialization would result in a compilation error. 
- Same is the case with value1 which is a String local variable. 
- If null is assigned to a reference variable, reference variable is considered to be assigned.

### Wrapper Classes
- [Example 1](src/main/java/com/in28minutes/java/wrapper/WrapperExamples.java)
- A wrapper class wraps (encloses) around a data type and gives it an object appearance
- Wrapper: Boolean,Byte,Character,Double,Float,Integer,Long,Short 
- Primitive: boolean,byte,char ,double, float, int , long,short
- Examples of creating wrapper classes are listed below.
  - Integer number = new Integer(55);//int;
  - Integer number2 = new Integer("55");//String
  - Float number3 = new Float(55.0);//double argument  
  - Float number4 = new Float(55.0f);//float argument  
  - Float number5 = new Float("55.0f");//String 
  - Character c1 = new Character('C');//Only char constructor 
  - Boolean b = new Boolean(true); 
- Reasons
  - null is a possible value
  - use it in a Collection
  - Object like creation from other types.. like String

- A primitive wrapper class in the Java programming language is one of eight classes provided in the java.lang package to provide object methods for the eight primitive types. All of the primitive wrapper classes in Java are immutable.

Wrapper classes are final and immutable.


#### Creating Wrapper Classes

```
Integer number = new Integer(55);//int
Integer number2 = new Integer("55");//String

Float number3 = new Float(55.0);//double argument
Float number4 = new Float(55.0f);//float argument
Float number5 = new Float("55.0f");//String

Character c1 = new Character('C');//Only char constructor
//Character c2 = new Character(124);//COMPILER ERROR

Boolean b = new Boolean(true);

//"true" "True" "tRUe" - all String Values give True
//Anything else gives false
Boolean b1 = new Boolean("true");//value stored - true
Boolean b2 = new Boolean("True");//value stored - true
Boolean b3 = new Boolean("False");//value stored - false
Boolean b4 = new Boolean("SomeString");//value stored - false

b = false;
```
#### Wrapper Class Utility Methods

- A number of utility methods are defined in wrapper classes to create and convert them.

#### valueOf  Methods

Provide another way of creating a Wrapper Object

```
Integer seven = 
    Integer.valueOf("111", 2);//binary 111 is converted to 7

Integer hundred = 
    Integer.valueOf("100");//100 is stored in variable
```

#### xxxValue methods 

xxxValue methods help in creating primitives

```
Integer integer = Integer.valueOf(57);
int primitive = seven.intValue();//57
float primitiveFloat = seven.floatValue();//57.0f

Float floatWrapper = Float.valueOf(57.0f);
int floatToInt = floatWrapper.intValue();//57
float floatToFloat = floatWrapper.floatValue();//57.0f
```

#### parseXxx methods

parseXxx methods are similar to valueOf but they return primitive values

```
int sevenPrimitive = 
    Integer.parseInt("111", 2);//binary 111 is converted to 7

int hundredPrimitive = 
    Integer.parseInt("100");//100 is stored in variable
```

#### static toString method

Look at the example of the toString static method below.

```
Integer wrapperEight = new Integer(8);
System.out.println(Integer.
toString(wrapperEight));//String Output: 8
```

#### Overloaded static toString method

2nd parameter: radix

```
System.out.println(Integer
.toString(wrapperEight, 2));//String Output: 1000
```

#### static toYyyyString methods. 

Yyyy can be Hex,Binary,Octal

```
System.out.println(Integer
.toHexString(wrapperEight));//String Output:8 
System.out.println(Integer
.toBinaryString(wrapperEight));//String Output:1000
System.out.println(Integer
.toOctalString(wrapperEight));//String Output:10
```

#### Wrapper Class , Auto Boxing
```
Integer ten = new Integer(10);
ten++;//allowed. Java does the work behind the screen for us

```
#### Boxing and new instances
- Auto Boxing helps in saving memory by reusing already created Wrapper objects. However wrapper classes created using new are not reused.
- Two wrapper objects created using new are not same object.

```
Integer nineA = new Integer(9);
Integer nineB = new Integer(9);
System.out.println(nineA == nineB);//false
System.out.println(nineA.equals(nineB));//true
```

- Two wrapper objects created using boxing are same object.

```
Integer nineC = 9;
Integer nineD = 9;
System.out.println(nineC == nineD);//true
System.out.println(nineC.equals(nineD));//true
```

### String Class

- A String class can store a sequence of characters. String is not a primitive in Java but a Class in its own right.

#### Strings are immutable

- Value of a String Object once created cannot be modified. Any modification on a String object creates a new String object.

```
String str3 = "value1";
str3.concat("value2");
System.out.println(str3); //value1
```

Note that the value of str3 is not modified in the above example.  The result should be assigned to a new reference variable (or same variable can be reused).

```
String concat = str3.concat("value2");
System.out.println(concat); //value1value2
```

## Where are string literals stored in memory?
All strings literals are stored in "String constant pool". If compiler finds a String literal,it checks if it exists in the pool. If it exists, it is reused.
Following statement creates 1 string object (created on the pool) and 1 reference variable.
```
String str1 = "value"; 
```
However, if new operator is used to create string object, the new object is created on the heap. Following piece of code create 2 objects.
```
//1. String Literal "value" - created in the "String constant pool"
//2. String Object - created on the heap
String str2 = new String("value");
```
## String vs StringBuffer vs StringBuilder
- Immutability : String
- Thread Safety : String(immutable), StringBuffer
- Performance : StringBuilder (especially when a number of modifications are made.)
- [Example 1](src/main/java/com/in28minutes/java/string/StringBufferBuilderExamples.java)


#### String Constant Pool

- All strings literals are stored in "String constant pool". If compiler finds a String literal,it checks if it exists in the pool. If it exists, it is reused.

- Following statement creates 1 string object (created on the pool) and 1 reference variable.

```
String str1 = "value"; 
```

- However, if new operator is used to create string object, the new object is created on the heap. Following piece of code create 2 objects.

```
//1. String Literal "value" - created in the "String constant pool"
//2. String Object - created on the heap
String str2 = new String("value");
```

#### String Method Examples

String class defines a number of methods to get information about the string content.

```
String str = "abcdefghijk";
```

##### Get information from String

Following methods help to get information from a String.

```
//char charAt(int paramInt)
System.out.println(str.charAt(2)); //prints a char - c
System.out.println("ABCDEFGH".length());//8
System.out.println("abcdefghij".toString()); //abcdefghij
System.out.println("ABC".equalsIgnoreCase("abc"));//true

//Get All characters from index paramInt
//String substring(int paramInt)
System.out.println("abcdefghij".substring(3)); //cdefghij

//All characters from index 3 to 6
System.out.println("abcdefghij".substring(3,7)); //defg
```

#### String Manipulation methods

Most important thing to remember is a String object cannot be modified. When any of these methods are called, they return a new String with the modified value. The original String remains unchanged.

```
//String concat(String paramString)
System.out.println(str.concat("lmn"));//abcdefghijklmn

//String replace(char paramChar1, char paramChar2)
System.out.println("012301230123".replace('0', '4'));//412341234123

//String replace(CharSequence paramCharSequence1, CharSequence paramCharSequence2)
System.out.println("012301230123".replace("01", "45"));//452345234523

System.out.println("ABCDEFGHIJ".toLowerCase()); //abcdefghij

System.out.println("abcdefghij".toUpperCase()); //ABCDEFGHIJ

//trim removes leading and trailings spaces
System.out.println(" abcd  ".trim()); //abcd
```
### String Concatenation Operator

#### Three Rules of String Concatenation
- RULE1: Expressions are evaluated from left to right.Except if there are parenthesis.
- RULE2: number + number = number
- RULE3: number + String = String

```
System.out.println(5 + "Test" + 5); //5Test5
System.out.println(5 + 5 + "Test"); //10Test
System.out.println("5" + 5 + "Test"); //55Test
System.out.println("5" + "5" + "25"); //5525
System.out.println(5 + 5 + "25"); //1025
System.out.println("" + 5 + 5 + "25"); //5525
System.out.println(5 + (5 + "25")); //5525
System.out.println(5 + 5 + 25); //35
```

### Increment and Decrement Operators

- Lets learn about the increment and decrement operators in Java.

#### Basics of Increment and Decrement Operators

Except for a minor difference ++i,i++ is similar to i = i+1 and --i,i-- is similar to i = i-1

++i is called pre-increment and i++ post increment

#### Increment Operators

Pre increment statement returns value after increment. Post increment statement returns value before increment

```
int i = 25;
int j = ++i;//i is incremented to 26, assigned to j
System.out.println(i + " " + j);//26 26

i = 25;
j = i++;//i value(25) is assigned to j, then incremented to 26
System.out.println(i + " " + j);//26 25
```
#### Decrement Operators

Decrement Operators are similar to increment operators.

```
i = 25;
j = --i;//i is decremented to 24, assigned to j
System.out.println(i + " " + j);//24 24

i = 25;
j = i--;//i value(25) is assigned to j, then decremented to 24
System.out.println(i + " " + j);//24 25
```

### Relational Operators

- Relation Operators are used to compare operands. They a always return true or false. List of Relation Operators include <, <=, >, >=, ==, and !=.

#### Relation Operators Examples
Let's consider a few examples of relational operators. Let's assume a int variable named number with a value 7.

```
int number = 7;
```

#### greater than operator

```
System.out.println(number > 5);//true
System.out.println(number > 7);//false
```

#### greater than equal to operator
```
System.out.println(number >= 7);//true
```

#### less than operator
```
System.out.println(number < 9);//true
System.out.println(number < 7);//false
```

#### less than equal to operator
```
System.out.println(number <= 7);//true
```

#### is equal to operator
```
System.out.println(number == 7);//true
System.out.println(number == 9);//false
```

#### NOT equal to operator
```
System.out.println(number != 9);//true
System.out.println(number != 7);//false
```

> single = is assignment operator and == is comparison. Below statement uses =.

```
System.out.println(number = 7);//7
```
#### == (equals) operator
Let's look at how == equals operator works with primitives and reference variables.

#### Primitive Variables

- Equality for Primitives only compares values

```
int a = 5;
int b = 5;
```

Below statement compares if a and b have same value.

```
System.out.println(a == b);//true
```
#### Reference Variables

```
Integer aReference = new Integer(5);
Integer bReference = new Integer(5);
```

For reference variables, == compares if they are referring to the same object.

```
System.out.println(aReference == bReference);//false

bReference = aReference;

//Now both are referring to same object
System.out.println(aReference == bReference);//true
```

### Logical Operators
- Logical Operators are &&, ||, |, &, ! and ^.

#### Short Circuit And Operator - &&
- True when both operands are true.

```
System.out.println(true && true);//true
System.out.println(true && false);//false
System.out.println(false && true);//false
System.out.println(false && false);//false
```
#### Short Circuit Or Operator - ||

True when atleast one of operands are true.

```
System.out.println(true || true);//true
System.out.println(true || false);//true
System.out.println(false || true);//true
System.out.println(false || false);//false
```

> Certification Tip : Logical Operators work with boolean values but not numbers.

```
//System.out.println(5 || 6);//COMPILER ERROR
```
#### Short circuit operators are Lazy 

- They stop execution the moment result is clear.  
   - For &&, if first expression is false,result is false.  
   - For ||, if first expression is true, the result is true. 
   - In above 2 situations, second expressions are not executed.

```
int i = 10;
System.out.println(true || ++i==11);//true
System.out.println(false && ++i==11);//false
System.out.println(i);//i remains 10, as ++i expressions are not executed.
```

#### Operator & and |
- Logical Operators &, | are similar to &&, || except that they don't short ciruit. 
- They execute the second expression even if the result is decided.

> Certification Tip : While & and | are very rarely used, it is important to understand them from a certification perspective.

```
int j = 10;
System.out.println(true | ++j==11);//true
System.out.println(false & ++j==12);//false
System.out.println(j);//j becomes 12, as both ++j expressions are executed
```

#### Operator exclusive-OR (^)
- Result is true only if one of the operands is true.
```
System.out.println(true ^ false);//true
System.out.println(false ^ true);//true
System.out.println(true ^ true);//false
System.out.println(false ^ false);//false
```
#### Not Operator (!)
Result is the negation of the expression.
```
System.out.println(!false);//true
System.out.println(!true);//false
```
### Arrays
- TODO : Why do we need arrays?

```
//Declaring an Array
int[] marks;

// Creating an array
marks = new int[5]; // 5 is size of array

int marks2[] = new int[5];//Declaring and creating an array in same line.

System.out.println(marks2[0]);//New Arrays are always initialized with default values - 0

//Index of elements in an array runs from 0 to length - 1
marks[0] = 25;
marks[1] = 30;
marks[2] = 50;
marks[3] = 10;
marks[4] = 5;

System.out.println(marks[2]);//Printing a value from array

//Printing a 1D Array
int marks5[] = { 25, 30, 50, 10, 5 };
System.out.println(marks5); //[I@6db3f829
System.out.println(
    Arrays.toString(marks5));//[25, 30, 50, 10, 5]

int length = marks.length;//Length of an array: Property length

//Enhanced For Loop
for (int mark: marks) {
    System.out.println(mark);
}

//Fill array with a value
Arrays.fill(marks, 100); //All array values will be 100

//String Arrays
String[] daysOfWeek = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
```

#### 2D Arrays

Best way to visualize a 2D array is as an array of arrays.

```
int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 } };

int[][] matrixA = new int[5][6]; 

//Accessing elements from 2D array:
System.out.println(matrix[0][0]); //1
System.out.println(matrix[1][2]); //6

//Looping a 2D array
for (int[] array: matrix) {
    for (int number: array) {
         System.out.println(number);
    }
}

// Printing a 2D Array
int[][] matrix3 = { { 1, 2, 3 }, { 4, 5, 6 } };
System.out.println(matrix3); //[[I@1d5a0305
System.out.println(

Arrays.toString(matrix3)); 
//[[I@6db3f829, [I@42698403]

System.out.println(Arrays.deepToString(matrix3)); 
//[[1, 2, 3], [4, 5, 6]]

System.out.println(matrix3[0]);//[I@86c347 - matrix3[0] is a 1D Array
System.out.println(Arrays.toString(matrix3[0]));//[1, 2, 3]
```

#### Other Array Operations

```
//Comparing Arrays
int[] numbers1 = { 1, 2, 3 };
int[] numbers2 = { 4, 5, 6 };

System.out.println(Arrays
.equals(numbers1, numbers2)); //false

int[] numbers3 = { 1, 2, 3 };

System.out.println(Arrays
.equals(numbers1, numbers3)); //true

// Sorting an Array

int rollNos[] = { 12, 5, 7, 9 };
Arrays.sort(rollNos);
System.out.println(Arrays.toString(rollNos));//[5, 7, 9, 12]

```

#### Array of Objects

```
Person[] persons = new Person[3];

//By default, an array of 3 reference variables is created.
//The person objects are not created
System.out.println(persons[0]);//null

//Let's create the new objects
persons[0] = new Person();
persons[1] = new Person();
persons[2] = new Person();

//Creating and initializing person array in one statement
Person[] personsAgain = { new Person(),new Person(),new Person()};

//Another example
Person[][] persons2D = 
    {
		{ new Person(),new Person(),new Person()},
		{ new Person(),new Person()}
    };
```


#### Array Certification Tips and Puzzles
```

//You can Declare, Create and Initialize Array on same line.
int marks3[] = { 25, 30, 50, 10, 5 };

//Leaving additional comma is not a problem. (note that comma after 5)
int marks4[] = { 25, 30, 50, 10, 5, };


int marks[]; //Not Readable
int[] runs; //Not Readable


//int values[5];//Compilation Error!Declaration of an Array should not include size. 

//marks = new int[];//COMPILER ERROR! Size of an array is mandatory to create an array.


//Declaring 2D Array Examples:
int[][] matrix1; //Recommended
int[] matrix2[]; //Legal but not readable. Avoid.

//Access 10th element when array has only length 5
//Runtime Exception: ArrayIndexOutOfBoundsException
//System.out.println(marks[10]);

//Array can contain only values of same type.

//COMPILE ERROR!!
//int marks4[] = {10,15.0}; //10 is int 15.0 is float

//Cross assigment of primitive arrays is ILLEGAL
int[] ints = new int[5];
short[] shorts = new short[5];
//ints = shorts;//COMPILER ERROR
//ints = (int[])shorts;//COMPILER ERROR


//The first dimension of a 2D array is mandatory
matrixA = new int[3][];//FINE
//matrixA = new int[][5];//COMPILER ERROR
//matrixA = new int[][];//COMPILER ERROR

//Each row in a 2D Array can have a different size. This is called a Ragged Array.
matrixA = new int[3][];//FINE
matrixA[0] = new int[3];
matrixA[0] = new int[4];
matrixA[0] = new int[5];
```


### If Else Condition
- Conditionally execute code! 
- Code inside If is executed only if the condition is true.

// Basic Example
```
if(true){
    System.out.println("Will be printed");
}

if(false){
    System.out.println("Will NOT be printed");//Not executed
}

//Example 1
int x = 5;

if(x==5){
    System.out.println("x is 5");//executed since x==5 is true
}

//Example 2
x = 6;
if(x==5){
    System.out.println("x is 5");//Not executed since x==5 is false
}

//Example 3
int y = 10;

if(y==10){
    System.out.println("Y is 10");//executed-condn y==10 is true
} else {
    System.out.println("Y is Not 10");
}

//Example 4
y = 11;

if(y==10){
    System.out.println("Y is 10");//NOT executed
} else {
    System.out.println("Y is Not 10");//executed
}

//Example 5
int z = 15;
//Only one condition is executed. Rest of the conditions are skipped.
if(z==10){
    System.out.println("Z is 10");//NOT executed
} else if(z==12){
    System.out.println("Z is 12");//NOT executed
} else if(z==15){
    System.out.println("Z is 15");//executed. 
} else {
    System.out.println("Z is Something Else.");//NOT executed
}

z = 18;
if(z==10){
    System.out.println("Z is 10");//NOT executed
} else if(z==12){
    System.out.println("Z is 12");//NOT executed
} else if(z==15){
    System.out.println("Z is 15");//NOT executed
} else {
    System.out.println("Z is Something Else.");//executed
}

//If else Example: without Blocks
int number = 5;
if(number < 0) 
    number = number + 10; //Not executed
    number++; //This statement is not part of if. Executed.
System.out.println(number);//prints 6
```
#### If else Puzzles

```
//Puzzle 1
int k = 15;
if (k > 20) {
    System.out.println(1);
} else if (k > 10) {
    System.out.println(2);
} else if (k < 20) {
    System.out.println(3);
} else {
    System.out.println(4);
}

//Output is 2. 
//Once a condition in nested-if-else is true the rest of the code is not executed.  


//Puzzle 2
int l = 15;

if(l<20)
    System.out.println("l<20");
if(l>20)
    System.out.println("l>20");
else
    System.out.println("Who am I?");
```

//Output is "l<20" followed by "Who am I?" on next line. 
//else belong to the last if before it unless brackets ({}) are used.
```

Puzzle 3

```
int m = 15;

if(m>20)
    if(m<20)
System.out.println("m>20");
    else
System.out.println("Who am I?");

//Nothing is printed to output. 

//Code above is similar to the code snippet shown below

if(m>20) {//Condn is false. So, code in if is not executed
    if(m<20)
System.out.println("m>20");
    else
System.out.println("Who am I?");
}
```

Puzzles Continued

```

//Puzzle 4

int x1 = 0;
//Condition in if should always be boolean
//if(x1) {} //COMPILER ERROR
//if(x1=0) {}//COMPILER ERROR. Using = instead of ==
//If else condition should be boolean

//Puzzle 5

boolean isTrue = false;

if(isTrue==true){
    System.out.println("TRUE TRUE");//Will not be printed
}

if(isTrue=true){
    System.out.println("TRUE");//Will be printed.
}

//Condition is isTrue=true. This is assignment. Returns true. So, code in if is executed.
```

### Switch Statement
- Choose between a set of options.
- From Java 6, String can be used as the switch argument.

```
//Example 1

int number = 2;
switch (number) {
case 1:
    System.out.println(1);
    break;
case 2:
    System.out.println(2);//PRINTED
    break;
case 3:
    System.out.println(3);
    break;
default:
    System.out.println("Default");
    break;
}
// Output of above example is 2.The case which is matched is executed.

```
Important Tips
- There is a break statement in every case. If there is no break statement, switch continues to execute other cases.
- There is a case named default.  If none of the cases match default case is executed.


```
//Switch Statement Example 2 , No Breaks
number = 2;
switch (number) {
case 1:
    System.out.println(1);
case 2:
    System.out.println(2);
case 3:
    System.out.println(3);
default:
    System.out.println("Default");
}
```

Output of above switch
```
2
3
Default
```

Since there is no break after case 2, execution falls through to case 3. There is no break in case 3 as well. So, execution falls through to default. 

> Code in switch is executed from a matching case until a break or end of switch statement is encountered.


Switch Statement Example 3 , Few Break's
```
number = 2;
switch (number) {
case 1:
    System.out.println(1);
    break;
case 2:
case 3:
    System.out.println("Number is 2 or 3");
    break;
default:
    System.out.println("Default");
    break;
}
```
Program Output 
```
Number is 2 or 3.
```
Case 2 matches. Since there is no code in case 2, execution falls through to case 3, executes the println. Break statement takes execution out of the switch.

Switch Statement Example 4 , Let's Default
- default is executed if none of the case's match. 

```
number = 10;
switch (number) {
case 1:
    System.out.println(1);
    break;
case 2:
    System.out.println(2);
    break;
case 3:
    System.out.println(3);
    break;
default:
    System.out.println("Default");
    break;
}
```
Code Output
```
Default
```

Switch Statement Example 5 - Default need not be Last 
```
number = 10;
switch (number) {
default:
    System.out.println("Default");
    break;
case 1:
    System.out.println(1);
    break;
case 2:
    System.out.println(2);
    break;
case 3:
    System.out.println(3);
    break;
}
```
Output 
```
Default
```
#### Switch statement Example 6


Switch can be used only with char, byte, short, int, String or enum
```
long l = 15;
/*switch(l){//COMPILER ERROR. Not allowed.
}*/

Case value should be a compile time constant.
```
number = 10;
switch (number) {
//case number>5://COMPILER ERROR. Cannot have a condition
//case number://COMPILER ERROR. Should be constant.
}    
```

## Loops
A loop is used to run same code again and again.

### While Loop
```
int count = 0;

while(count < 5){//while this condn is true, loop is executed.
    System.out.print(count);
    count++;
}
//Output - 01234
```

While loop Example 2

```
count = 5;
while(count < 5){//condn is false. So, code in while is not executed.
    System.out.print(count);
    count++;
}//Nothing is printed to output
```

### Do While Loo
Download .txt
gitextract_5wy5wbdt/

├── Angular/
│   └── README.md
├── C++/
│   ├── C++ Syntax.md
│   ├── Data Structures and Algorithms.md
│   └── README.md
├── Command Line/
│   └── README.md
├── Django/
│   └── README.md
├── Elixir/
│   └── README.md
├── Git/
│   └── README.md
├── Golang/
│   ├── README.md
│   └── golang_refcard.odt
├── Java/
│   ├── README.md
│   └── todo.md
├── JavaScript/
│   ├── README.md
│   ├── _config.yml
│   └── translations/
│       ├── fr-FR.md
│       ├── ja-JP.md
│       ├── pl_PL.md
│       ├── pt-BR.md
│       ├── ru-RU.md
│       ├── th-TH.md
│       ├── zh-CN.md
│       └── zh-TW.md
├── Kotlin/
│   └── README.md
├── MATLAB/
│   └── README.md
├── Markdown/
│   └── README.md
├── MongoDB/
│   ├── README.md
│   └── sql_mongo_comparison.md
├── Oracle SQL/
│   ├── README.md
│   └── SQL_commands.md
├── PHP/
│   └── README.md
├── Perl/
│   └── README.md
├── Python/
│   ├── CODE_OF_CONDUCT.md
│   ├── CONTRIBUTING.md
│   ├── README.md
│   ├── _config.yml
│   ├── blog_files/
│   │   ├── about.md
│   │   └── pysheet.md
│   ├── pyproject.toml
│   └── python_cheat_sheet.ipynb
├── README.md
├── React/
│   ├── README.md
│   └── react-placar.md
├── Ruby/
│   └── README.md
├── Ruby on Rails/
│   └── README.md
├── Scala/
│   └── README.md
├── Swift/
│   └── README.md
└── TypeScript/
    └── README.md
Condensed preview — 47 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,949K chars).
[
  {
    "path": "Angular/README.md",
    "chars": 32420,
    "preview": "# Angular Cheatsheet\r\n\r\n##### Table of Contents  \r\n[Basics](#basics)  \r\n[Loop](#loop)  \r\n[Html](#html)  \r\n[Directives](#"
  },
  {
    "path": "C++/C++ Syntax.md",
    "chars": 12474,
    "preview": "# C++ Syntax Cheat Sheet\r\n\r\n## Table of Contents\r\n\r\n<!-- TOC depthFrom:1 depthTo:6 withLinks:1 updateOnSave:0 orderedLis"
  },
  {
    "path": "C++/Data Structures and Algorithms.md",
    "chars": 19400,
    "preview": "# C++ Data Structures and Algorithms Cheat Sheet\r\n\r\n## Table of Contents\r\n\r\n<!-- TOC depthFrom:1 depthTo:6 withLinks:1 u"
  },
  {
    "path": "C++/README.md",
    "chars": 412,
    "preview": "# C++ and Data Structures & Algorithms Cheat Sheet\r\n\r\nThese are two cheat sheets I put together describing both basic [C"
  },
  {
    "path": "Command Line/README.md",
    "chars": 4852,
    "preview": "[back to overwiev](/../..)\r\n\r\n# Command Line Cheatsheet\r\n\r\n##### Table of Contents  \r\n[Basics](#basics)  \r\n[Showing & Na"
  },
  {
    "path": "Django/README.md",
    "chars": 9013,
    "preview": "# Cheatsheet for Django QuerySets\r\nCurrent Django Version: [2.0](https://docs.djangoproject.com/en/2.0/ref/models/querys"
  },
  {
    "path": "Elixir/README.md",
    "chars": 32467,
    "preview": "# Elixir Cheat Sheet\r\n\r\n```elixir\r\nelixir -v\r\n1.3.1\r\n```\r\n\r\nElixir is a dynamic functional compiled language that runs o"
  },
  {
    "path": "Git/README.md",
    "chars": 26704,
    "preview": "# git-cheat-sheet\r\nThis is my personal git cheat sheet. This is not a deep dive into how git works, just some of the sim"
  },
  {
    "path": "Golang/README.md",
    "chars": 17348,
    "preview": "# Go Cheat Sheet\r\n\r\n# Index\r\n1. [Basic Syntax](#basic-syntax)\r\n2. [Operators](#operators)\r\n    * [Arithmetic](#arithmeti"
  },
  {
    "path": "Java/README.md",
    "chars": 243068,
    "preview": "# Java Cheat Sheet\r\nReview Java 9 Concepts at Jet Speed.\r\n\r\n### Complete Java Course\r\n- https://www.udemy.com/java-progr"
  },
  {
    "path": "Java/todo.md",
    "chars": 32541,
    "preview": "## Java Certification\r\n\r\nSource - https://education.oracle.com/education/pdf/JavaCertificationMap.pdf\r\n\r\nThe Oracle Cert"
  },
  {
    "path": "JavaScript/README.md",
    "chars": 66469,
    "preview": "# Modern JavaScript Cheatsheet\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n\r\n## Introduction\r\n\r"
  },
  {
    "path": "JavaScript/_config.yml",
    "chars": 57,
    "preview": "theme: jekyll-theme-cayman\r\ntitle: Modern JS Cheatsheet\r\n"
  },
  {
    "path": "JavaScript/translations/fr-FR.md",
    "chars": 68890,
    "preview": "# Modern JavaScript Cheatsheet\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>Crédits de l’"
  },
  {
    "path": "JavaScript/translations/ja-JP.md",
    "chars": 58517,
    "preview": "# <a name=\"modern-javascript-cheatsheet\"></a> モダン JavaScript チートシート\r\n\r\n![モダン JavaScript チートシート](https://i.imgur.com/aexP"
  },
  {
    "path": "JavaScript/translations/pl_PL.md",
    "chars": 69292,
    "preview": "# <a name=\"modern-javascript-cheatsheet\"></a>Współczesny JavaScript - ściągawka\r\n\r\n![Modern JavaScript cheatsheet](htt"
  },
  {
    "path": "JavaScript/translations/pt-BR.md",
    "chars": 20593,
    "preview": "# Cheatsheet de JavaScript Moderno\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>Crédito d"
  },
  {
    "path": "JavaScript/translations/ru-RU.md",
    "chars": 69792,
    "preview": "# Памятка по современному JavaScript\r\n![Памятка по современному JavaScript](https://i.imgur.com/aexPxMb.png)\r\n<small>За "
  },
  {
    "path": "JavaScript/translations/th-TH.md",
    "chars": 57683,
    "preview": "# Modern JavaScript Cheatsheet\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>เครดิตรูปภาพ:"
  },
  {
    "path": "JavaScript/translations/zh-CN.md",
    "chars": 9180,
    "preview": "# Modern JavaScript Cheatsheet 简体中文版\r\n\r\n![Modern JavaScript cheatsheet](https://i.imgur.com/aexPxMb.png)\r\n<small>Image C"
  },
  {
    "path": "JavaScript/translations/zh-TW.md",
    "chars": 36384,
    "preview": "<a name=\"#modern-javascript-cheatsheet\"></a>\r\n# Modern JavaScript Cheatsheet 繁體中文版\r\n\r\n![Modern JavaScript cheatsheet](ht"
  },
  {
    "path": "Kotlin/README.md",
    "chars": 14874,
    "preview": "# Introduction\r\n\r\nKotlin is a new programming language for the JVM. It produces Java bytecode, supports Android and gene"
  },
  {
    "path": "MATLAB/README.md",
    "chars": 17904,
    "preview": "# MATLAB Cheat Sheet\r\n\r\nBased off of [Learn X in Y Minutes](http://learnxinyminutes.com/docs/matlab/).\r\n\r\nMATLAB stands "
  },
  {
    "path": "Markdown/README.md",
    "chars": 3860,
    "preview": "Markdown Cheatsheet\r\n===================\r\n\r\n- - - - \r\n\r\n# Heading 1 #\r\n\r\n    Markup :  # Heading 1 #\r\n\r\n    -OR-\r\n\r\n    "
  },
  {
    "path": "MongoDB/README.md",
    "chars": 3032,
    "preview": "# MongoDB Cheat Sheet\n\n## Show All Databases\n\n```\nshow dbs\n```\n\n## Show Current Database\n\n```\ndb\n```\n\n## Create Or Switc"
  },
  {
    "path": "MongoDB/sql_mongo_comparison.md",
    "chars": 55866,
    "preview": "[SQL to MongoDB Mapping Chart](http://docs.mongodb.org/manual/reference/sql-comparison/#sql-to-mongodb-mapping-chart)\n<d"
  },
  {
    "path": "Oracle SQL/README.md",
    "chars": 22252,
    "preview": "# SQL cheatsheet\r\n\r\n#### This is note taken from the [SQL course on Codecademy](https://www.codecademy.com/learn/learn-s"
  },
  {
    "path": "Oracle SQL/SQL_commands.md",
    "chars": 5041,
    "preview": "## COMMANDS\r\n\r\n### ALTER TABLE\r\n\r\n```\r\nALTER TABLE table_name ADD column datatype;\r\n```\r\n\r\n`ALTER TABLE` lets you add co"
  },
  {
    "path": "PHP/README.md",
    "chars": 11328,
    "preview": "# PHP Help Sheet\r\n\r\n## Treehouse PHP Classes\r\n\r\n> PHP OOP\r\n    > classes\r\n        > recipe.php\r\n        > cookbook.php\r\n"
  },
  {
    "path": "Perl/README.md",
    "chars": 4462,
    "preview": "# Perl 5 Cheatsheet\r\n\r\n## Table of Contents\r\n\r\n- [General](#general)\r\n- [Strings and Numbers 1](#strings-and-numbers-1)\r"
  },
  {
    "path": "Python/CODE_OF_CONDUCT.md",
    "chars": 3272,
    "preview": "# Contributor Covenant Code of Conduct\r\n\r\n## Our Pledge\r\n\r\nIn the interest of fostering an open and welcoming environmen"
  },
  {
    "path": "Python/CONTRIBUTING.md",
    "chars": 2366,
    "preview": "## Contributing 🎉\r\n\r\nFirst off, thank you for taking the time to contribute!\r\n\r\nThe following is a set of guidelines for"
  },
  {
    "path": "Python/README.md",
    "chars": 118532,
    "preview": "# Python Cheat Sheet\r\n\r\nBasic cheatsheet for Python mostly based on the book written by Al Sweigart, [Automate the Borin"
  },
  {
    "path": "Python/_config.yml",
    "chars": 26,
    "preview": "theme: jekyll-theme-cayman"
  },
  {
    "path": "Python/blog_files/about.md",
    "chars": 1849,
    "preview": "## About Python Cheat Sheet\r\n\r\nThis is a basic [cheatsheet](https://www.pythoncheatsheet.org) for Python mostly based on"
  },
  {
    "path": "Python/blog_files/pysheet.md",
    "chars": 98914,
    "preview": "## The Zen of Python\r\n\r\nFrom the [PEP 20 -- The Zen of Python](https://www.python.org/dev/peps/pep-0020/):\r\n\r\n> Long tim"
  },
  {
    "path": "Python/pyproject.toml",
    "chars": 234,
    "preview": "[tool.poetry]\r\nname = \"python-cheatsheet\"\r\nversion = \"0.1.0\"\r\ndescription = \"\"\r\nauthors = [\"'Carlos <'carlos.w.montecino"
  },
  {
    "path": "Python/python_cheat_sheet.ipynb",
    "chars": 210585,
    "preview": "{\r\n \"cells\": [\r\n  {\r\n   \"cell_type\": \"markdown\",\r\n   \"metadata\": {},\r\n   \"source\": [\r\n    \"# About [![Binder](https://my"
  },
  {
    "path": "README.md",
    "chars": 2913,
    "preview": "# Cheat-Sheets\n\n<p align=\"center\">\n  <img src=\"Cheat Sheets.png\">\n</p>\n\nA cheat sheets can be really helpful when you're"
  },
  {
    "path": "React/README.md",
    "chars": 11642,
    "preview": "# 🌈 React Cheat Sheet\r\n\r\n> A simple cheat sheet for facilitate the process in the workshops and event about React. Let m"
  },
  {
    "path": "React/react-placar.md",
    "chars": 4522,
    "preview": "\r\n![template-placar](img/template-placar.PNG)\r\n\r\n# React Placar\r\n\r\n> Um Simples exemplo de uso da biblioteca React.js by"
  },
  {
    "path": "Ruby/README.md",
    "chars": 11423,
    "preview": "# Ruby Cheatsheet\r\n\r\nRuby is a language of careful balance. Its creator, Yukihiro “Matz” Matsumoto, blended parts of his"
  },
  {
    "path": "Ruby on Rails/README.md",
    "chars": 6534,
    "preview": "Looking for [Ruby](../Ruby-Cheatsheet.md)?  \r\n\r\n#Ruby on Rails Cheatsheet\r\n\r\n##### Table of Contents  \r\n[Basics](#basics"
  },
  {
    "path": "Scala/README.md",
    "chars": 19194,
    "preview": "---\r\nlayout: page\r\ntitle: Cheat Sheet\r\n---\r\n\r\nThere are certainly a lot of things that can be improved! If you would lik"
  },
  {
    "path": "Swift/README.md",
    "chars": 154050,
    "preview": "# Swift Cheat Sheet\r\n\r\nNotes taken from [The Swift Programming Language](https://developer.apple.com/library/ios/documen"
  },
  {
    "path": "TypeScript/README.md",
    "chars": 22231,
    "preview": "# TypeScript Cheatsheet\nSet of basic functionalities from TypeScript in one place. <br>\nPlease note that some functional"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the black-shadows/Cheat-Sheets GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 47 files (1.6 MB), approximately 460.8k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!