text:
# ** Vehicle Detection *

This project is MaxEtzo's submission for **Vehicle Detection** aassignment which is a part of [**Self-Driving Car Engineer Nanodegree's**](https://eu.udacity.com/course/self-driving-car-engineer-nanodegree--nd013) by **Udacity**

The goals / steps of this project are the following:

* Perform a Histogram of Oriented Gradients (HOG) feature extraction on a labeled training set of images and train a classifier Linear SVM classifier
* Optionally, apply a color transform and append binned color features, as well as histograms of color, to your HOG feature vector.
* Note: for those first two steps don't forget to normalize your features and randomize a selection for training and testing.
* Implement a sliding-window technique and use your trained classifier to search for vehicles in images.
* Run your pipeline on a video stream (start with the test_video.mp4 and later implement on full project_video.mp4) and create a heat map of recurring detections frame by frame to reject outliers and follow detected vehicles.
* Estimate a bounding box for vehicles detected.

## Rubric points.
Here I will consider the [rubric](https://review.udacity.com/#!/rubrics/513/view) points individually and describe how I addressed each point in my implementation.

### Features: Spatial + Histogram of Oriented Gradients (HOG) + Color Histogram

##### Final settings:
* Spatial features: **24x24x3**
* HOG: **18 orientations**, **16x16 pixels per cell**, **1x1 cells per block** for each color channel
* Color histogram: **24 bins** for each color channel
* Colorspace: **YCrCb**

#### 1. Extraction of features from the training images

As a basis for features extraction functions/methods provided in video lessons with some adjustments were taken (see file "core_functions.py"). As examples of such adjustments:
* HOG features can be of any color channel combinations, not just 0, 1, 2 or 'ALL' (see lines 7-10, and 87-94)
* Color histogram range depends on color space. In particular, for colorspaces 'HSV' and 'HLS' the range for Hue is between 0 and 180.
* Note: data format of images is uint8 (0 to 255)

First, `car` and `noncar` images of both KITTI and GTI datasets are read using `glob` module. In order to *partially* avoid time-series problem of GTI dataset only every 4th car image is taken. As the result, `car` dataset contains 6673 images against 8986 of `noncar`. To avoid biasing towards `noncar` images, only random 6673 are chosen. The code for the aforementioned operations is contained in code cell 1 of "main" IPython notebook. Below are examples of a `car` and a `noncar` images:

![Example of a 'car' and a 'noncar' images](./output_images/example_images.png)

In code cell 2 of the notebook, you can see a final choice of binned color, histogram of colors and HOG features. Final choice of colorspace fell on `YCrCb` for a reason that will be explained in further sections. `Y`, `Cr` and `Cb` channels for the example 'car' and 'noncar' images are as follows:

![Example 'car' image in 'YCrCb' colorspace](./output_images/car_YCrCb.png)
![Example 'noncar' image in 'YCrCb' colorspace](./output_images/noncar_YCrCb.png)

Below, you can see a visualization of the HOG on those channels with the parameters of `orientations=18`, `pixels_per_cell=(16,16)` and `cells_per_block=(1,1)`:

![HOG of 'car' image in 'YCrCb' colorspace](./output_images/car_hog.png)
![HOG of 'noncar' image in 'YCrCb' colorspace](./output_images/noncar_hog.png)

And last but not least, the histograms are:
![Histogram of'YCrCb' colors of 'car' image](./output_images/car_hist.png)
![Histogram of'YCrCb' colors of 'noncar' image](./output_images/noncar_hist.png)

(there is no real reason in representing spatial binned color features). Code snippets responsible for feature extraction can be found in code cells 6 and 7 (with the core functions from `core_functions.py`).

#### 2. Final choice of features settings

I started with features setting provided in video lessons:
* Spatial features: **32x32x3** (where 32x32 resized image dimensions, and 3 color channels)
* HOG: **9 orientations**, **8x8 pixels per cell**, **2x2 cells per block** for each color channel
* Color histogram: **32 bins** for each color channel
* Colorspace: **HSV**

Linear SVM trained on features set above does perform relatively well (test accuracy of >99%). Slight tweaking the settings above does not result in any distinguishable changes, i.e. delta in test accuracy is in the order of the noise. Mere different partitionings of training and test set results in similar order of delta.

Although, the performance is satisfactory the number of features is extremely high - **8460**, and as the result so is computational and memory requirements for both training and the image processing pipeline. The goal was to reduce number of features without compromising the performance.

Removing any of the three feature classes (spatial, HOG or histogram), immediately resulted in substantial accuracy drop (up to ~5%) as well as in visible performance fails of pipeline, in terms of increased number of false negatives or false positives (when applied on test images).

The strategy was to slowly reduce number of histogram bins (32 -> 24), spatial features size (32x32 -> 24x24), and hog feature size, while monitoring the effect both in terms of test accuracy and the visual performance of image processing pipeline. Reducing HOG feature size is not a trivial task. Since original images are of 64x64 resolution pixel_per_cell can only be a power of 2, i.e. pix_per_cell can only be increased by factor of 2x2: from 8x8 to 16x16. Alternatively, original images can be scaled/resized to a different resolution, e.g. 60x60 and the pix_per_cell can be chosen as either 10x10 or 12x12. I found impracticle to scale/resize all training and test images and instead went with the former approach. As cell size increased to 16x16, I could also reduce cells_per_block number to 1. In order to partially compromise such a dramatic change of cell numbers per image, I increased number of histogram bins from 9 to 18.

I tried out multiple colorspace, however, many of them have demonstrated bias (hotter regions in heatmap) towards either dark/black or bright/white cars (as in test images). Surprisingly, `YCrCb` has shown the least of such bias.

All in all, I managed to reduce number of features to **2664** (~x3 less) and still stay in **99% test accuracy** region.

#### 3. Training a linear classifier

Before training linear SVM, I used `StandardScaler` to normalize the features and split dataset into `training` and `test` in ratio of 8:2. It took 7.19 seconds to train linear SVM and test accuracy of 0.9925 was achieved. Code can be found in code cells 7 and 8.

### Sliding Window Search
The core sliding window search function is called `car_heatmap`, and can be found in code cell 11, which returns heatmap (and not bounding boxes as suggested in video lessons).

#### 1. Sliding window search: window sizes, y-limits, overlaps.

After multiple iterations, I stopped on the following choice of window sizes:
```python
window_size = [160, 112, 80, 64]
```
For the sake of beauty as well as optimization, in reality `window_size` was kept the same, and instead the complete image was scaled appropriately. Corresponding scale factors are as follows:
```python
scale = [2.5, 1.75, 1.25, 1.0]
```
Clearly, the limits in y-dimensions depend on the window size. For example, we do not expect to see a really small car projection in close proximity (i.e. y coordinates close to the bottom). Also, we do not expect to see any car in the sky (unless flying cars, thanks to another Udacity program, really kick in!). In general, as `window_size` gets smaller y-limits converge to horizon.
```python
y_min = [400, 400, 400, 400]
y_max = [640, 568, 520, 496]
```
As of overlap, due to the optimization (global hog estimation, see below) the biggest overlap that my choice of `pix_per_cell` of 16x16 allows is 0.75:
```python
xy_overlap  = [(0.75, 0.5), (0.75, 0.75), (0.75, 0.75), (0.75, 0.75)]
```
Why the window size of 160 has a y overlap of 0.5? I just felt like it.
![Window sizes, y-limits and overlaps](./output_images/windows.png)

#### 2. Global HOG optimization (and why not spatial and histogram of color features):
In order to optimize performance, on each scale (i.e. for different window sizes, see above), first global HOG is estimated on cropped image (based on y-limits) and HOG features for each window are sampled as pipeline progresses. I wrote a similar implementations for spatial and histogram of colors features, but they did not result in any performance boost. Global histogram of colors was estimated in a similar way as HOG by introducing histogram cells based on overlapping factor. However, stupid me later realized that amount of histogram operations did not reduced at all, but additional memory costs were added for storing all the histograms for individual cells. As for spatial features, resizing a complete image once or individual windows apparently does not make a big difference due to cheapness of the operation in the first place.

#### 3. L2 floating heatmap via `clasifier.decision_function`:
One of the **best decision** I have made was to switch from `classifier.predict()` to `classifier.decision_function`. Output of `predict` is highly compressed data as information about *confidence level* is absolutely lost. Instead, in my implementation the heatmap is constructed based on confidence level given by `decision_function` method. Another nice feature, is that **hyperplane can be artificially moved up or down**! For example, if you want the algorithm to be more robust against false-positives, raise confidence threshold above 0.0. In contrast, if you want the algorith to pick up a weaker signals, lower confidence threshold below 0.0 (do not forget to subtract threshold from a confidence level back!). Extremely important is to adjust your postprocessing (for example, final heatmap thresholding) according to your confidence threshold. After playing a bit with a hyperplane, I decided to leave at 0.0 for now, although I see potential use-cases for changing it.

Final heatmap is a sum of squares of confidence levels. Heatmap pre-processing step includes taking square root of the heatmap, sort of L2 normalization. Reason it is not performed in `car_heatmap` method is because by returning heatmaps squared you can sum heatmaps across multiple frames for a video pipeline.

#### 4. Heatmap thresholding (hard + otsu) on interpolated heatmap
`threshold_otsu` is a very powerful adaptive thresholding algorithm. The advantage of the otsu is that it adapts to the noise floor, but the downsight is that in case there is no *real* signal, individual noise spikes are counted as a signal. By combining, `threshold_otsu` with hard threshold overall performance can be improved.

`heatmap_threshold` is applied on preprocessed heatmap (code cell 12) that includes taking square root of it (L2 normalization, see above) as well as applying `GaussianBlur`. Gaussian blurring is one way to interpolate heatmap values between discrete windows!

#### 5. Results on test images:
On the left you can see final heatmaps (after preprocessing and thresholding) and on the right resulting bounding boxes (based on `scipy.ndimage.measurements.label()` method).
![Test image 1](./output_images/test1.png)
![Test image 2](./output_images/test2.png)
![Test image 3](./output_images/test3.png)
![Test image 4](./output_images/test4.png)
![Test image 5](./output_images/test5.png)
![Test image 6](./output_images/test6.png)

### Video Implementation

Video processing pipeline can be found in code cell 14.

#### 1. Provide a link to your final video output.  Your pipeline should perform reasonably well on the entire project video (somewhat wobbly or unstable bounding boxes are ok as long as you are identifying the vehicles most of the time with minimal false positives.)
Here's a [link to my video result](./project_video_output.mp4)

#### 2. Infinite impulse response filter

Instead of averaging across multiple frames I implemented infinite impulse response filter for it's computational and memory cheapness and elegance (although finite impulse response is for obvious reasons is a better choice). The decay factor of choice is 0.2. IIR results in *smoother* bounding boxes dynamics.

#### 3. Spatio-Temporal Correlation

Every now and then (when stars align), a really strong false positive appears on the heatmap. Unfortunately, IIR is not able to deal with such cases. In order to avoid such false positives, an additional filter of Spatio-Temporal Correlation is implemented. Spatio-Temporal Correlation means that a heatmap value for a single pixel (spatial correlation) is considered when it is confirmed across multiple frames (temporal correlation). Number of frames can be set arbitrarily, but I have chosen 3. Basic implementation is taking a minimum values across last 3 heatmaps (I call it floating equivalent of logical AND). In such way, instanteneous noise spikes that only last for 1 or 2 frames are filtered out.

#### 4. Example:
Below is an example of *instant* heatmap (top-left) and *integrated/filtered* heatmap (top-right) with a resulting bounding boxes:

![Video frame](./output_images/video_frame.jpg)

### Discussion

#### 1. Briefly discuss any problems / issues you faced in your implementation of this project.  Where will your pipeline likely fail?  What could you do to make it more robust?

In general, any low pass filters such as IIR or Spatio-Temporal correlation that we used adds a delay / latency. This is a highly unwanted effect in dynamic and safety critical environment such as automotive. In our case, Spatio-Temporal correlation across 3 frames results in a delay of 2 frames, so IIR approximately of 3-4, totaling in approx. 5-6 frame delay. This can be clearly observed when on one occasion a bounding box of a car in the opposite lane appeared with a delay. Also, a car in the end of the video (SUV) was not recognized in time. Changing decay factor of IIR from 0.2 to 0.3 or above gives enough time of SUV to be recognized, but also results in more false-positive noise.

It can be seen that Spatio-Temporal correlation and IIR are not effective to eliminate all false-positives, as certain noise spikes last for more than 3-5 frames. More advanced *predictive!* filters, such as Kalman filter must be applied to avoid aforementioned challenges. (it will also help to more correctly identify bounding boxes).

Another disadvantage is that bounding boxes are not confining a car, but rather inside due to thresholding (edges of a car fall under threshold). This can be avoided by applying a more advanced thresholding algorithm based on local noise estimate (such as CFAR) + predictive filters such as Kalmann.

And last but not least, `scipy.ndimage.measurements.label()` does a poor job of discriminating two different objects. In certain video segments (around 35s) two clear heatmap peaks can be identified (hence two cars can be discriminated), however `scipy.ndimage.measurements.label()` labels them as one since they are touching.

repository: MaxEtzo/SDC-Vehicle-Detection

repo_name: MaxEtzo/SDC-Vehicle-Detection


text:
---
layout: default
---

# 1993-11-05 - Re: ANON: mail concerns

## Header Data

From: "Christian D. Odhner"<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: 4a6c5c4ce2afab13b000d6ab72db2e8feaab5e368b01761738a999634e06ccf6

Message ID<EMAIL_ADDRESS>Reply To<EMAIL_ADDRESS>UTC Datetime: 1993-11-05 02:17:50 UTC

Raw Date: Thu, 4 Nov 93 18:17:50 PST

## Raw message

```
{% raw  %}From: "Christian D. Odhner"<EMAIL_ADDRESS>Date: Thu, 4 Nov 93 18:17:50 PST
To<EMAIL_ADDRESS>Subject: Re: ANON: mail concerns
In-Reply-To<EMAIL_ADDRESS>Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

On Wed, 3 Nov 1993<EMAIL_ADDRESS>wrote:

> >::
> >Request-Encryption-To: X
> >
> >If user ID X is on the remailer's pubkey ring, the outgoing message is
> >encrypted to X. This could be usefull for anonymous return-address blocks.
>
> Encryption should be the default. Err on the side of caution.
>
What if the "To" address has more than one key associated with it? Maybe
even more than one entity? Another (not publicized) remailer?

Maybe this wouldn't be a problem. Hmmm.....

Happy Hunting, -Chris

Christian Douglas Odhner     | "The NSA can have my secret key when they pry
<EMAIL_ADDRESS>    | it from my cold, dead, hands... But they shall
pgp 2.3 public key by finger | NEVER have the password it's encrypted with!"
My opinions are shareware. To register your copy, send me 15$ in DigiCash.
  Key fingerprint =  58 62 A2 84 FD 4F 56 38  82 69 6F 08 E4 F1 79 11

> -----BEGIN PGP SIGNATURE-----
> Version: 2.3
>
> iQCVAgUBLNgXzIjvfLxJbYYtAQEK4AP9HrSaMSOnlsxzEjgLbAgvsCSw3vMxLJ4u
> 856ZbKI2cZTNLoPzyWLNW68gZ7kcNeaF7MHKzWbI9tLEDePpWN34sB11wBlpfzcf
> WzcYVLI6JBLVERq2seyKU3cqAhWuxldSDeAlsKkMsrzI0tGgOaLkxCxhxn9weZf8
> 58mZeANd3sg=
> =8F9u
> -----END PGP SIGNATURE-----

{% endraw %}
```

## Thread

+ Return to [November 1993](/archive/1993/11)

+ Return to "["Christian D. Odhner" <cdodhner@indirect.com>](/authors/christian_d_odhner_cdodhner_at_indirect_com_)"
+ Return to<EMAIL_ADDRESS>Eternal Optimist <na26436@anon.penet.fi>](/authors/nobody_at_alumni_cco_caltech_edueternal_optimist_na26436_at_anon_penet_fi_)"

+ 1993-11-04 (Wed, 3 Nov 93 18:57:31 PST) - [Re: ANON: mail concerns](/archive/1993/11/db7580b15d0ce9acf01e807ce109e5b508b0db37c2230ebed4b6beccad3e39e6) -<EMAIL_ADDRESS>Eternal Optimist<EMAIL_ADDRESS>  + 1993-11-05 (Thu, 4 Nov 93 18:17:50 PST) - Re: ANON: mail concerns - _"Christian D. Odhner"<EMAIL_ADDRESS>

license: MIT

branch_name: refs/heads/master

extension: md

gha_license_id: MIT

license_type: permissive


text:
# Data Structures

## Primitive Data Types (Java)

Data Type |       Description       | Default  |  Size
:-------: | :---------------------: | :------: | :-----:
`boolean` |    `true` or `false`    | `false`  |  1 bit
 `char`   |    Unicode character    | `\u0000` | 16 bits
 `byte`   | twos complement integer |   `0`    |  8 bits
 `short`  | twos complement integer |   `0`    | 16 bits
  `int`   | twos complement integer |   `0`    | 32 bits
 `long`   | twos complement integer |   `0`    | 64 bits
 `float`  | IEEE 754 floating point |  `0.0`   | 32 bits
`double`  | IEEE 754 floating point |  `0.0`   | 64 bits

## Array

- Stores data elements based on a sequential (usually zero-based) index.

### Important Points

- Optimal for indexing. Bad for searching, inserting and deleting.
- **Linear Arrays**, or one dimensional arrays, are the most basic.
- **Two Dimensional Arrays** have `x` & `y` indices like a grid or nested arrays.
- **Dynamic Arrays** are like one dimensional arrays but have reserved space for additional elements.
    - If a dynamic array is full, it copies its contents to a larger array (usually 2x in size).

### Time Complexity

- **Access:** `O(1)` (unsorted & sorted)
- **Search:** `O(n)` (unsorted), `O(log n)` (sorted)
- **Insertion:** `O(1)` (without shifting / unsorted), `O(n)` (with shifting / sorted)
- **Deletion:** `O(1)` (without shifting / unsorted), `O(n)` (with shifting / sorted)
- **Insertion at End of Dynamic Array:** `O(1)` amortized

### Java

- **`Array`:** [Oracle Docs](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html), [TutorialsPoint](https://www.tutorialspoint.com/java/java_arrays.htm).
- **`ArrayList`:** [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html), [TutorialsPoint](https://www.tutorialspoint.com/java/java_arraylist_class.htm).
- **`Vector`:** Similar to `ArrayList` but synchronized. [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html).
- **`String`:** [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html).
- **`StringBuilder`:** [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html).

## Linked List

- Stores data using **nodes** that have a datum and pointers to other nodes.

### Important Points

- Designed to optimize insertion and deletion during iteration. Slow at indexing and searching.
- **Singly Linked Lists** have nodes that reference the next node.
- **Doubly Linked Lists** have nodes that also reference the previous node.
- **Circularly Linked Lists** are linked lists whose *tail* reference the *head*.
- **Stacks** are commonly implemented using linked lists.
    - Stacks are **last in, first out (LIFO)** data structures. `push()` & `pop()`.
    - Implemented with a linked list where the head is the only place for insertion and removal.
- **Queues** are commonly implemented using linked lists.
    - Queues are **first in, first out (FIFO)** data structures. `enqueue()` & `dequeue()`.
    - Implemented with a linked list that only removes from the head and adds to the tail.
- **Double-Ended Queues** or **Deques** are also commonly implemented using linked lists.
    - Deques allow elements to be added and removed from either the head or tail of the queue.

### Time Complexity

- **Access:** `O(n)` (unsorted & sorted)
- **Search:** `O(n)` (unsorted & sorted)
- **Insertion:** `O(1)` (unsorted), `O(n)` (sorted)
- **Deletion:** `O(1)` (unsorted & sorted)

### Java

- [Java Implementation of Linked List](1.1%20-%20Linked%20List.md)
- [Java Implementation of Stack](1.2%20-%20Stack.md)
- [Java Implementation of Queue](1.3%20-%20Queue.md)
- **`LinkedList`:** [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html), [TutorialsPoint](https://www.tutorialspoint.com/java/util/java_util_linkedlist.htm).
- **`Iterator`:** [TutorialsPoint](https://www.tutorialspoint.com/java/java_using_iterator.htm).
- **`Stack`:** [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html).
- **`Queue`:** [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html).
- **`Deque`:** [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html).

## Hash Table

- Stores data as key-value pairs in a direct access table.
- Designed to optimize searching, insertion and deletion.

### Important Points

- **Hash Functions** accept a key (from an arbitrarily sized dataset) and map it to an output i.e. hash code (from a fixed sized dataset). This hash code is then mapped to an index for storage.
    - This is known as **hashing**, whose motivation is to assign a unique index to every possible key.
    - This is done because the actual key space may be too large while only a fraction of those keys may appear.
- A good **hash function** must:
    - return a value within the hash table range.
    - achieve an even distribution of indices from the keys that actually occur.
    - be easy and quick to compute.
- **Hash Collisions** occur when a hash function returns the same hash code for two distinct keys or two different hash codes are mapped to the same index.
    - Most hash functions have this problem.
    - **Closed Address Hashing -** Chain together the keys that generate the same index in a linked list (`O(n)`) or binary search tree (`O(log n)`).
        - **Load Factor** is `n/h`, where `n` is the number of records and `h` is the number of hash cells.
    - **Open Address Hashing -** Store all the elements in the hash table and handle hash collisions by **rehashing** i.e. look for an alternative slot.
        - **Linear Probing -** Insert the colliding record in the next slot recursively. However, this can result in long runs of occupied slots.
        - **Quadratic Probing/Double Hashing -** Use two hash functions to hash the key twice in case of a collision.
        - Using open address hashing requires a hash cell to be marked as *obsolete* when a record is deleted to avoid stopping search.
- Hashes are important for associative arrays (i.e. key-value pairs) and database indexing.

### Time Complexity

- **Search:** Average Case: `O(1)`, Worst Case: `O(n)`
- **Insertion:** Average Case: `O(1)`, Worst Case: `O(n)`
- **Deletion:** Average Case: `O(1)`, Worst Case: `O(n)`

### Java

- **`HashMap`:** `<K, V>`, no guarantee about iteration order, `O(1)`. [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html), [TutorialsPoint](https://www.tutorialspoint.com/java/java_hashmap_class.htm).
- **`TreeMap`:** `<K, V>`, iteration according to natural order of keys or externally supplied `Comparator`, `O(log n)`. [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html).
- **`LinkedHashMap`:** `<K, V>`, iteration according to insertion order, `O(1)`. [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html).
- **`HashSet`:** `<T>`, no guarantee about iteration order, `O(1)`. [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html), [TutorialsPoint](https://www.tutorialspoint.com/java/java_hashset_class.htm).
- **`TreeSet`:** `<T>`, iteration according to natural order of keys or externally supplied `Comparator`, `O(log n)`. [Oracle Docs](https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html).
- **`LinkedHashSet`:** `<T>`, iteration according to insertion order, `O(1)`. [Oracle Docs](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashSet.html).

## Tree

- A tree is a data structure composed of nodes.
- Each tree has one *root node* that has zero or more child nodes and each of these child nodes has zero or more child nodes.
- Nodes without children are called *leaves*.
- A tree cannot contain cycles and nodes may not have links back to their parent nodes.

## Binary Tree

- Is a tree data structure where every node has at most two children.
    - There is one left and one right child node.

### Important Points

- A **complete binary tree** is one where every level of the tree is fully filled, except for perhaps the last level. To the extent that the last level is filled, it is filled from left to right.
- A **full binary tree** is one where every node has either zero or two children.
- A **perfect binary tree** is one that is both full and complete. Perfect binary trees must have exactly `2^k - 1` nodes, where `k` is the number of levels.
- A **degenerate tree** is an unbalanced tree, which if entirely one-sided is essentially a linked list.
- Used to implement [**binary search trees**](1.4%20-%20Binary%20Search%20Tree.md) & [**binary heaps**](1.5%20-%20Binary%20Heap.md).

## Trie (Prefix Tree)

- Is a variant of an n-ary tree in which characters are stored at each node. Each path down the tree represents a word.

### Important Points

- `*` nodes (or `null` nodes) are used to indicate complete words.
- A node in a trie could have anywhere from 1 through `ALPHABET_SIZE + 1` children (or 0 through `ALPHABET_SIZE` children if a boolean value is used to indicate `*` nodes).
- Tries are usually used to store words for quick prefix lookups. While a hash table can quickly look up whether a string is a valid word, it cannot quickly verify if a string is a prefix of any valid words.

### Time Complexity

- **Validate Prefix:** `O(n)` (where `n` is length of prefix)

### Java

- [Java Implementation of Trie](1.6%20-%20Trie.md)

## Segment Tree

- A segment tree is a tree data structure for storing intervals or segments.
- It allows querying which of the stored segments contain a given element.
- It is usually a static structure i.e. it cannot be modified easily once it's built.

### Time Complexity

- A segment tree for a set `I` of `n` intervals uses `O(n log n)` storage and can be built in `O(n log n)` time.
- Segment trees support searching for all the intervals that contain a query point in `O(log n + k)`, `k` being the number of retrieved intervals or segments.

## Graph

- A linked list based data structure where links (edges) can exist between any two nodes (vertices).
- Edges may be directed/undirected and weighted/unweighted. The graph may be cyclic.
- **LL-based Implementation:**
    - A 1-D array is used to represent the vertices.
    - A linked list or array is used for each vertex `v`, which contains the vertices that are adjacent to `v` (adjacency list).
    - Vertices adjacent to a vertex can be found quickly.
    - In an undirected graph, edges will be stored twice.
- **Array-based Implementation:**
    - A 1-D array is used to represent the vertices.
    - A 2-D boolean array (adjacency matrix) is used to represent the edges.
    - Connectivity between two vertices can be verified quickly.
    - In an undirected graph, the adjacency matrix will be symmetrical.
- An adjacency matrix is usually better for storing dense graphs while an adjacency list is better for storing sparse graphs.
- Traversal in an adjacency list implementation is more efficient than an adjacency matrix implementation since it is not necessary to iterate through all the nodes to find a node's neighbors.

### Important Points

- Two nodes are **adjacent** if they are connected by an edge.
- The **degree** of a node `i` is the number of nodes adjacent to `i`.
- A **path** is a sequence of edges that connect two nodes.
- A **connected graph** is a graph where a path exists between any two nodes.
- A **complete graph** is a graph where every vertex is directly connected to every other vertex.
- A **clique** is a complete subgraph.
- Traversal is similar to trees but vertices must be marked as visited (due to multiple possible paths) and all adjacent vertices must be visited (as opposed to just two in binary trees).

### Time Complexity

- **Add Vertex:** Adjacency List: `O(1)`, Adjacency Matrix: `O(|V|^2)`
- **Add Edge:** Adjacency List: `O(1)`, Adjacency Matrix: `O(1)`
- **Remove Vertex:** Adjacency List: `O(|V| + |E|)`, Adjacency Matrix: `O(|V|^2)`
- **Remove Edge:** Adjacency List: `O(|E|)`, Adjacency Matrix: `O(1)`
- **Query for Adjacency:** Adjacency List: `O(|V|)`, Adjacency Matrix: `O(1)`
- **Storage Size:** Adjacency List: `O(|V| + |E|)`, Adjacency Matrix: `O(|V|^2)`

repository: apollomat/TechInterview

path: /1 - Data Structures.md

filename: 1 - Data Structures.md

repo_name: apollomat/TechInterview


text:
# OSX Swift ANE Starter Project

Example Xcode project showing how to create Air Native Extensions for OSX using Swift.
It supports OSX 10.10+

#### Xcode 9.4.1 (9F2000) must be used with Apple Swift version 4.1.2 (swiftlang-902.0.54 clang-9<IP_ADDRESS>)
It is not possible to mix Swift versions in the same app. Therefore all Swift based ANEs must use the same exact version.
ABI stability is planned for Swift 5 in late 2018

##### Dependencies
From the command line cd into /example and run:
- OSX
````shell
bash get_mac_dependencies.sh
`````
----------

The ANE is comprised of 2 parts.

1. A dynamic Swift Framework which contains the translation of FlashRuntimeExtensions to Swift.
2. A dynamic Swift Framework which contains the main logic of the ANE.

HelloWorldANE_LIB/HelloWorldANE_LIB.m is the entry point of the ANE. It acts as a thin layered API to your Swift controller.
Add the number of methods here

````objectivec
static FRENamedFunction extensionFunctions[] =
{
    MAP_FUNCTION(TRSOA, load)
   ,MAP_FUNCTION(TRSOA, goBack)
};
`````

HelloWorldANE_FW/SwiftController.swift
Add Swift method(s) to the functionsToSet Dictionary in getFunctions()

````swift
@objc public func getFunctions(prefix: String) -> Array<String> {
    functionsToSet["\(prefix)load"] = load
    functionsToSet["\(prefix)goBack"] = goBack
}
`````

Add Swift method(s)

````swift
func load(ctx: FREContext, argc: FREArgc, argv: FREArgv) -> FREObject? {
    //your code here
    return nil
}

func goBack(ctx: FREContext, argc: FREArgc, argv: FREArgv) -> FREObject? {
    //your code here
    return nil
}
`````

----------

**Dependencies**
From the command line cd into example/ and run:

````shell
bash get_ios_dependencies.sh
`````

### Prerequisites

You will need

- Xcode 9.4.1
- Xcode 9.1 for iOS Simulator
- IntelliJ IDEA
- AIR 30

repository: DmitryF/Swift-IOS-ANE

repo_name: DmitryF/Swift-IOS-ANE


text:
---
Layout:
Title: "Context API"
Date: 2018-04-13 09:24
Categories:
---

# Context API

## Context

Context provides a way to pass data through the component tree without having to pass props down manually at every level. Data is passed from parent to child via props, but this can be difficult to use for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like this between components without having to explicitly pass a prop through every level of the tree.

## When to Use Context

Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a “theme” prop in order to style the Button component:

class App extends React.Component {
  render() {
    return <Toolbar theme="dark" />;
  }
}

function Toolbar(props) {
  // The Toolbar component must take an extra "theme" prop
  // and pass it to the ThemedButton. This can become painful
  // if every single button in the app needs to know the theme
  // because it would have to be passed through all components.
  return (

      <ThemedButton theme={props.theme} />

  );
}

function ThemedButton(props) {
  return <Button theme={props.theme} />;
}

Using context, we can avoid passing props through intermediate elements:

// Context lets us pass a value deep into the component tree
// without explicitly threading it through every component.
// Create a context for the current theme (with "light" as the default).
const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    // Use a Provider to pass the current theme to the tree below.
    // Any component can read it, no matter how deep it is.
    // In this example, we're passing "dark" as the current value.
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

// A component in the middle doesn't have to
// pass the theme down explicitly anymore.
function Toolbar(props) {
  return (

      <ThemedButton />

  );
}

function ThemedButton(props) {
  // Use a Consumer to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  // In this example, the current theme is "dark".
  return (
    <ThemeContext.Consumer>
      {theme => <Button {...props} theme={theme} />}
    </ThemeContext.Consumer>
  );
}

# API

const {Provider, Consumer} = React.createContext(defaultValue);

Creates a { Provider, Consumer } pair. When React renders a context Consumer, it will read the current context value from the closest matching Provider above it in the tree.

The defaultValue argument is used when you render a Consumer without a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them.

## Provider

<Provider value={/* some value */}>

A React component that allows Consumers to subscribe to context changes.

Accepts a value prop to be passed to Consumers that are descendants of this Provider. One Provider can be connected to many Consumers. Providers can be nested to override values deeper within the tree.

## Consumers

<Consumer>
  {value => /* render something based on the context value */}
</Consumer>

A React component that subscribes to context changes.

Requires a function as a child. The function receives the current context value and returns a React node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the value argument will be equal to the defaultValue that was passed to createContext().

All Consumers are re-rendered whenever the Provider value changes. Changes are determined by comparing the new and old values using the same algorithm as Object.is. (This can cause some issues when passing objects as value:)

gha_language: HTML


text:
# Text Formatting

The **MLEM** package contains a simple text formatting system that supports coloring, bold and italic font modifiers, in-text icons and text animations.

Text formatting makes use of [generic fonts](font_extensions.md).

It should also be noted that [MLEM.Ui](https://github.com/Ellpeck/MLEM/wiki/MLEM.Ui)'s `Paragraph`s support text formatting out of the box.

*This documentation is about the new text formatting that was introduced in MLEM 3.3.1. You can see the documentation for the legacy text formatting system [here](text_formatting_legacy.md).*

## Formatting codes
To format your text, you can insert *formatting codes* into it. Almost all of these codes are single letters surrounded by `<>`, and some formatting codes can accept additional parameters after their letter representation.

By default, the following formatting options are available:
- Colors using `<c ColorName>`. All default MonoGame colors are supported, for example `<c CornflowerBlue>`. Reset using `</c>`.
- Bold and italic text using `<b>` and `<i>`, respectively. Reset using `</b>` and `</i>`.
- Drop shadows using `<s>`. Optional parameters for the shadow's color and positional offset are accepted: `<s #AARRGGBB 2.5>`. Reset using `</c>`.
- Underlined text using `<u>`. Reset using `</u>`.
- A wobbly sine wave animation using `<a wobbly>`. Optional parameters for the wobble's intensity and height are accepted: `<a wobbly 10 0.25>`. Reset using `</a>`.

## Getting your text ready
To get your text ready for rendering with formatting codes, it has to be tokenized. For that, you need to create a new text formatter first. Additionally, you need to have a [generic font](font_extensions.md) ready:
```cs
var font = new GenericSpriteFont(this.Content.Load<SpriteFont>("Fonts/ExampleFont"));
var formatter = new TextFormatter();
```
You can then tokenize your string like so:
```cs
var tokenizedString = formatter.Tokenize(font, "This is a <c Green>formatted</c> string!");
```
Additionally, if you want your tokenized string to be split based on a certain maximum width automatically, you can split it like so:
```cs
tokenizedString.Split(font, maxWidth, scale);
```
## Drawing the formatted text
To draw your tokenized text, all you have to do is call its `Draw` method like so:
```cs
tokenizedString.Draw(gameTime, spriteBatch, position, font, color, scale, depth);
```
Note that, if your tokenized text contains any animations, you have to updated the tokenized string every `Update` call like so:
```cs
tokenizedString.Update(gameTime);
```
## Adding custom codes
Adding custom formatting codes is easy! There are two things that a custom formatting code requires:
- A class that extends `Code` that does what your formatting code should do (we'll use `MyCustomCode` in this case)
- A regex that determines what strings your formatting code matches
- A formatting code constructor that creates a new instance of your code's class

You can then register your formatting code like this:
```cs
formatter.Codes.Add(new Regex("<matchme>"), (form, match, regex) => new MyCustomCode(match, regex));
```

## Macros
The text formatting system additionally supports macros: Regular expressions that cause the matched text to expand into a different string. Macros can be resolved recursively, meaning that you can have macros that resolve into other macros, and so on.

By default, the following macros are available:
- `~` expands into a non-breaking space, much like in LaTeX.

Adding custom macros is very similar to adding custom formatting codes:
```cs
formatter.Macros.Add(new Regex("matchme"), (form, match, regex) => "replacement string");
```

repository: AtomicBlom/MLEM

branch_name: refs/heads/main

repo_name: AtomicBlom/MLEM


text:
# [Charges](https://github.com/jlinn/stripe-api-php/blob/master/src/Api/Charges.php)
## Create a charge
The `createCharge()` method takes a [`CreateChargeRequest`](https://github.com/jlinn/stripe-api-php/blob/master/src/Request/Charges/CreateChargeRequest.php) object as its only parameter.
```php
$request = $stripe->charges->createChargeRequest(350, "usd");
$stripe->charges->createCharge($request);
```

## Retrieve a charge
```php
$charge = $stripe->charges->getCharge("charge_id");
```

## Update a charge
```php
$stripe->charges->updateCharge("charge_id", "A new description.");
```

## Refund a charge
```php
$stripe->charges->refundCharge("charge_id");
```

## Capture a charge
```php
$stripe->charges->captureCharge("charge_id");
```

## List multiple charges
```php
$charges = $stripe->carges->listCharges();
```

repository: jlinn/stripe-api-php

gha_language: PHP

repo_name: jlinn/stripe-api-php


text:
## User Model

This model controls the `users` table of the application (see `database/migration/CreateUsersTable.php` for migration file). Using Eloquent ORM for database interaction you can add and remove tables to the `protected $fillable` declaration.

The User model is considered the base model seeing that the application revolves around the user, its fair to state that all prebuilt modules and model relationships be owned by the User model.

### Declared Methods

#### setDobAttribute
`setDobAttribute` responsible for converting `_dob` value into unix format. (`setDobAttribute` comes with an `$dob` arguement)

```php
protected function setDobAttribute($dob)
```
#### getAge
`getAge` responsible for calculating users age

```php
protected function getAge()
```
#### scopeUsername
`scopeUsername` returns user value based on `username` search

- Arguement 2 accepts the searched username value.

```php
public function scopeUsername($query, $value)
```

### Relational Models

#### userData
 - `userData` Has One ORM relationship (an extended model for holding additional user information).

```php
public function userData(){
    return $this->hasOne('App\userData');
}
```

#### usersPhotos
 - `usersPhotos` Has Many ORM relationship.

```php
public function usersPhotos(){
    return $this->hasMany('App\UsersPhotos');
}
```

#### online
 - `online` Has One ORM relationship.

```php
public function online(){
    return $this->hasOne('App\Online');
}
```

repository: ctlpages/laz-docs

repo_name: ctlpages/laz-docs


text:
# readmeio

Track your API metrics within ReadMe.

[![npm](https://img.shields.io/npm/v/readmeio.svg)](https://npm.im/readmeio)
[![Build](https://github.com/readmeio/metrics-sdks/workflows/nodejs/badge.svg)](https://github.com/readmeio/metrics-sdks)

[![](https://d3vv6lp55qjaqc.cloudfront.net/items/1M3C3j0I0s0j3T362344/Untitled-2.png)](https://readme.io)

## Installation

```
npm install readmeio
```

## Usage

Just add the middleware to [Express](https://expressjs.com/), and that's it!

```javascript
const readme = require('readmeio');

app.use(readme.metrics('<<apiKey>>', req => ({
  id: req.<userId>,
  label: req.<userNameToShowInDashboard>,
  email: req.<userEmailAddress>,
})));
```

View full documentation here: [https://docs.readme.com/docs/sending-logs-to-readme-with-nodejs](https://docs.readme.com/docs/sending-logs-to-readme-with-nodejs)

### `res.headers['x-documentation-url']`
With the middleware loaded, all requests that funneled through it will receive a `x-documentation-url` header applied to the response. The value of this header will be the URL on ReadMe Metrics with which you can view the log for that request.

Note that in order to generate this URL, an API request is made to ReadMe once a day, and cached to a local file in `node_modules/.cache/readmeio`, to retrieve your projects `baseUrl`. If this request to ReadMe fails, the `x-documentation-url` header will not be added to responses.

If you wish to not rely on this cache, you can opt to supply a `baseLogUrl` option into the middleware, which should evaluate to the public-facing URL of your ReadMe project.

### Configuration Options
There are a few options you can pass in to change how the logs are sent to ReadMe. These are passed in an object as the third parameter to the `readme.metrics`.

```js
const readme = require('readmeio');
const env = process.env.NODE_ENV;

app.use(readme.metrics('', req => ({
  id: req.<userId>,
  label: req.<userNameToShowInDashboard>,
  email: req.<userEmailAddress>,
}), {
  development: env !== 'production',
  bufferLength: 1,
  blacklist: [[arrayOfSensitiveKeysToOmit]],
  whitelist: [[arrayofKeysOnlyToSend]],
}));
```

| Option | Use |
| :--- | :--- |
| development | **default: false** If true, the log will be separate from normal production logs. This is great for separating staging or test data from data coming from customers |
| bufferLength | **default: 10** By default, we only send logs to ReadMe after 10 requests are made. Depending on the usage of your API it make make sense to send logs more or less frequently |
| blacklist | **optional** An array of keys from your API requests and responses headers and bodies that you wish to blacklist from sending to ReadMe.

If you configure a blacklist, it will override any whitelist configuration. |
| whitelist | **optional** An array of keys from your API requests and responses headers and bodies that you only wish to send to ReadMe. |
| baseLogUrl | **optional** This is the base URL for your ReadMe project. Normally this would be `https://projectName.readme.io` or `https://docs.yourdomain.com`, however if this value is not supplied, a request to the ReadMe API will be made once a day to retrieve it. This data is cached into `node_modules/.cache/readmeio`.

### Limitations
- Currently only supports JSON request bodies. Adding a whitelist/blacklist for non-JSON bodies will not work (unless they're added to `req.body`) the same way that `body-parser` does it. The properties will be passed into [`postData`](http://www.softwareishard.com/blog/har-12-spec/#postData) as a `params` array.
- Needs more support for getting URLs when behind a reverse proxy: `x-forwarded-for`, `x-forwarded-proto`, etc.
- Needs more support for getting client IP address when behind a reverse proxy.
- Logs are "fire and forget" to the metrics server, so any failed requests (even for incorrect API key!) will currently fail silently.

license: ISC

repository: dldinternet-rs/metrics-sdks

repo_name: dldinternet-rs/metrics-sdks


text:
# Jumpsuit Counter Example

To view this exmample, follow these steps:

```bash
$ npm install jumpsuit-cli -g
$ npm install
$ npm run watch
$ open http://localhost:8000
```

repository: Jason-Cooke/jumpsuit

repo_name: Jason-Cooke/jumpsuit


text:
# FormManager

[![Build Status](https://travis-ci.org/oscarotero/form-manager.png?branch=master)](https://travis-ci.org/oscarotero/form-manager)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/oscarotero/form-manager/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/oscarotero/form-manager/?branch=master)

Created by Oscar Otero <http://oscarotero.com><EMAIL_ADDRESS>
## Installation:

This package needs php>=5.4 and is available on [Packagist](https://packagist.org/packages/form-manager/form-manager):

```
composer require form-manager/form-manager
```

## Usage

### Namespace import

FormManager is namespaced, but you only need to import a single class into your context:

```php
use FormManager\Builder as F;
```

### Create a field

All HTML5 field types are supported.

```php
//Create an input type="text" element
$name = F::text();

//Use the jQuery syntax to set/get/remove attributes:
$name->attr('name', 'username');

$name->attr([
	'maxlength' => 50,
	'required' => true
]);

$maxlength = $name->attr('maxlength');

$name->removeAttr('required');

//Get/set values
$name->val('MyName');

//Get/set css classes
$name->addClass('cool-input');
$name->removeClass('cool-input');

//Get/set/remove data-* attributes
$name->data('id', 23);
$name->data([
	'name' => 'value',
	'foo' => 'bar'
]);
$foo = $name->data('foo');

$name->removeData('id');

$name->removeData(); //Remove all data

//You can chain various methods:
$email = F::email()->addClass('cool-input')->id('my-email')->val('my@email.com');

//And use the __call() magic method to add attributes:
$email->required(); //same than $email->attr('required', true);
$email->required(false); //same than $email->attr('required', false);
```

### Generate the html code

The html code is created automatically on convert the object into a string:

```php
$name = F::text()->class('my-input')->required();

echo $name; //<input type="text" class="my-input" required>

//print the input with extra attributes
echo $name->addClass('text-input')->placeholder('Your name');
```

### Working with data

Inputs can validate the data depending of the type and other validation attributes:

```php
$url = F::url();

//Set the input as required
$url->required();

//Check if the value is valid
if (!$url->validate()) {
	echo $url->error(); //This value is required
}

//set an invalid url
$url->val('invalid-url');

//check the value and get the error
if (!$url->validate()) {
	echo $url->error(); //This value is not a valid url
}
```

The inputs can handle custom validators:
```php
$name = F::text();

function isDave($input)
{
	if ($input->val() !== 'dave') {
		throw new FormManager\InvalidValueException('This value must be "dave"');
	}
}

//Add custom validators
$name->addValidator('isDave');

$name->val('tom');

if (!$name->validate()) {
	echo $name->error(); //This value must be "dave"
}

//Remove the validator
$name->removeValidator('isDave');
```

The `load()` method is like `val()` but it handles the data sent by the client:

```php
$name = F::text();

//Add a function to sanitize the data
$name->sanitize(function($value)
{
	return strip_tags($value);
});

//if you use val(), the value remains as is
$name->val('<strong>earl</strong>');
echo $name->val(); //<strong>earl</strong>

//if you use load(), the value will be sanitized
$name->load('<strong>earl</strong>');
echo $name->val(); //earl
```

### Labels

You can use labels with your inputs, just use the property `->label` and it will be created automatically. It may also generate an extra label with the error message.

```php
$name = F::text();

//Define a label
$name->label('User name');

//And modify the label using the same syntax than inputs:
$name->label->class('main-label');

//Print all (label + input)
echo $name;

//Print label and inputs separately
echo $name->label . '<br>' . $name->input;

//Use errorLabel to print a secondary label with the validation error:
echo $name->label . '<br>' . $name->input . $name->errorLabel;
```

### Datalist

[Datalist](http://www.w3.org/TR/html5/forms.html#the-datalist-element) are also allowed, just use the `datalist()` method to set/get values:

```php
$name = F::search();

//Define the datalist values
$name->datalist([
	'female' => 'Female',
	'male' => 'Male'
]);
```

### Custom renders

You can configure how each field must be rendered. First, you need to know all properties of each field:

* `$field->input` The input/select/textarea element
* `$field->label` The label element
* `$field->errorLabel` A secondary label with the validation error
* `$field->datalist` An optional datalist instance
* `$field->wrapper` A div element containing all the stuff above

```php
$field->render(function ($field) {
	$html = (string) $field->label;
	$html .= '<p>'.$field->input.$field->errorLabel.'</p>';
	$html .= $field->datalist;

	return $html;
});
```

## Special fields

In addition with regular fields (the html5 equivalents: text, textarea, select, datetime, etc...) there are some special fields useful to create more complicate data schemes:

### Group

A group is a simple field to store other fields under a name. The following example shows a group of three fields:

```php
$date = F::group([
	'day' => F::number()->min(1)->max(31)->label('Day'),
	'month' => F::number()->min(1)->max(12)->label('Month'),
	'year' => F::number()->min(1900)->max(2013)->label('Year')
]);

//Set values to group
$date->val([
	'day' => 21,
	'month' => 6,
	'year' => 1979
]);

//Get values
$values = $date->val();

//Use array syntax to access to the fields by name
$year = $date['year']->val();

//Add more fields dinamically
$date['hour'] = F::number()->min(0)->max(23)->label('Hour');

//Add other html attributes to the group:
$date->addClass('field-day')->attr(['id' => 'date-field']);
```

### Choose

This field stores other fields with the same name but different values. Useful for radio inputs or to define various submit buttons.

```php
//Create a choose container
$colors = F::choose();

//Add some fields. The keys are the values
$colors->add([
	'red' => F::radio()->label('Red'),
	'blue' => F::radio()->label('Blue'),
	'green' => F::radio()->label('Green')
]);

//Access to the fields by value
$red_radio = $colors['red'];

//Add more fields dinamically
$colors['yellow'] = F::radio()->label('Yellow');

//Set the value
$colors->val('red');

//Get value
$color_choosen = $colors->val();
```

### Collection

It's like a [group](#group), but stores a collection of values:

```php
//Create a collection container
$people = F::collection([
	'name' => F::text()->label('Name'),
	'email' => F::email()->label('email'),
	'age' => F::number()->label('Age')
]);

//Set two values
$people->val([
	[
		'name' => 'Xaquín',
		'email' =><EMAIL_ADDRESS>		'age' => '24'
	],[
		'name' => 'Uxío',
		'email' =><EMAIL_ADDRESS>		'age' => '37'
	]
]);

//Access to the first group of values:
$group = $people[0];

//Access to any field
echo $people[0]['name']->val(); //returns 'Xaquín'

//Push a new value
$people->pushVal([
	'name' => 'Manoela',
	'email' =><EMAIL_ADDRESS>	'age' => '18'
]);

//Returns the group container used as template for each value inserted.
//useful to use the html template in javascript

$template = $people->getTemplate();

echo '<div class="template">'.$template.'</div>';
```

### CollectionMultiple

If you need different types of values in your collection, CollectionMultiple is the answer:

```php
//Create a collectionMultiple container
$article = F::collectionMultiple([
	'section' => [
        'title' => F::text()->label('Title'),
        'text' => F::textarea()->label('Text')
    ],
    'picture' => [
        'caption' => F::text()->label('Caption'),
        'image' => F::file()->label('Image')
    ],
    'quote' => [
        'text' => F::textarea()->label('Text'),
        'author' => F::text()->label('Author')
    ]
]);

//Set values. Note that we need a "type" value to know the type of each row
$article->val([
	[
		'type' => 'section',
		'title' => 'This is the section title',
        'text' => 'Lorem ipsum...',
	],[
		'type' => 'quote',
		'text' => 'You have to learn the rules of the game. And then you have to play better than anyone else.',
		'author' => 'Albert Einstein'
	]
]);

// Note that a hidden input will be created for you to store the group type
$article[0]['type']->val(); //section
$article[0]['type']->attr('type'); //hidden

//Push more values
$article->pushVal([
	'type' => 'section',
	'title' => 'This is another section',
    'text' => 'The world of dogs are better than the cats because...'
]);

//Add new types
$article->add([
	'video' => [
		'title' => F::text()->label('Title'),
		'video' => F::url()->label('Youtube url')
	]
]);

//Returns an array with all templates used
$templates = $article->getTemplate();

foreach ($templates as $name => $template) {
	echo '<div class="template-'.$name.'">'.$template.'</div>';
}
```

## Loader

The main aim of the loader field is to separate the way to load the data with the way to store and keep this data once it's loaded. Let's say for example, an input type file: if a file is loaded, the value is an array with the same structure than any $_FILES value, but if user doesn't upload anything, the value is empty. So, what is supposed to do in this case? remove the file or keep the previous value?
The loader field has two fields: a "loader" field and a "field" field. The first one is responsive to load the new values (for example, it can be an input type file) and the second keeps the previous value (for example, it can be an input type hidden, or text, etc). Let's see an example:

```php
$fileUpload = F::loader([
    'loader' => F::file()->label('Upload a file here'),
    'field' => F::hidden() //this hidden input stores the old value
]);

//Set a value
$fileUpload->val('my-file.png');

//we have this value
echo $fileUpload->val(); //my-file.png

//load empty data
$fileUpload->load(null);

//Nothing was loaded, so we keep the old value
echo $fileUpload->val(); //my-file.png

//load new value
$fileUpload->load($_FILES['file-upload']);

//we have the new value
echo ($fileUpload->val() === $_FILES['file-upload']); //true
```

## Forms

We need a form to put all this things together. The form is just another field, in fact, it's like a [Group](#group).

```php
$form = F::form();

//Set the form attributes:
$form->attr([
	'action' => 'test.php',
	'method' => 'post'
]);

//Add some fields and containers
$form->add([
	'name' => F::text()->maxlength(50)->required()->label('Your name'),
	'email' => F::email()->label('Your email'),
	'telephone' => F::tel()->label('Telephone number'),

	'gender' => F::choose([
		'm' => F::radio()->label('Male'),
		'f' => F::radio()->label('Female')
	]),

	'born' => F::group([
		'day' => F::number()->min(1)->max(31)->label('Day'),
		'month' => F::number()->min(1)->max(12)->label('Month'),
		'year' => F::number()->min(1900)->max(2013)->label('Year')
	]),

	'language' => F::select()->options(array(
		'gl' => 'Galician',
		'es' => 'Spanish',
		'en' => 'English'
	))->label('Language'),

	'friends' => F::collection([
		'name' => F::text()->label('Name'),
		'email' => F::email()->label('email'),
		'age' => F::number()->label('Age')
	]),

	'action' => F::choose([
		'save' => F::submit()->html('Save changes'),
		'duplicate' => F::submit()->html('Save changes')
	])
]);

//You can also add new fields using the array syntax (the key will be the input name):
$form['new-input'] = F::range()->min(0)->max(100)->val(50);

//Print the form
echo $form;

//Access to the fields using key names
echo $form['website'];

//Or fields inside fields
echo $form['born']['day'];

//Set the values to all fields:
$form->val([
	'name' => 'Oscar',
	'email' =><EMAIL_ADDRESS>	'gender' => 'm',
	'born' => [
		'day' => 21,
		'month' => 6,
		'year' => 1979
	],
	'language' => 'gl',
	'friends' => [
		[
			'name' => 'Friend 1',
			'email' =><EMAIL_ADDRESS>			'age' => 25,
		],[
			'name' => 'Friend 2',
			'email' =><EMAIL_ADDRESS>			'age' => 30,
		],[
			'name' => 'Friend 3',
			'email' =><EMAIL_ADDRESS>			'age' => 35,
		]
	],
	'action' => 'save'
]);

//Get the values
$values = $form->val();

//To load the raw values from globals $_GET, $_POST and $_FILES:
$form->loadFromGlobals();

//Or specify your own globals
$form->loadFromGlobals($_my_GET, $_my_POST, $_my_FILES);

//Check the errors
if (!$form->validate()) {
	echo 'there are errors in the form';
}
```

## Builder

The `Builder` class is used to ease the creation of fields and containers. For example, instead of this:

```php
use FormManager\Containers\Form;
use FormManager\Inputs\Text;
use FormManager\Inputs\Textarea;

$form = new Form([
	'name' => new Text(),
	'bio' => new Textarea(),
]);
```

You can do simply this:

```php
use FormManager\Builder as F;

$form = F::form([
	'name' => F::text(),
	'bio' => F::textarea()
]);
```

The `FormManager\Builder` handles the instantation of all theses classes for you using factories. By default, it contains the `FormManager\Factory`, responsible of instantation of all fields and containers.

But you can add your owns factories, creating classes implementing `FormManager\FactoryInterface`.

This is useful for a lot of things. For example, to create custom fields:

```php
use FormManager\Builder as F;
use FormManager\FactoryInterface;

class CustomFields implements FactoryInterface
{
	/**
	 * Method required by the interface
	 */
	public function get($name, array $arguments)
	{
		if (method_exists($this, $name)) {
			return $this->$name();
		}
	}

	public function Year()
	{
		return F::number()->min(1900)->max(date('Y'));
	}
}
```

Use it in your app:

```php
use FormManager\Builder as F;

F::addFactory(new CustomFields());

$date = F::form([
	'name' => F::text(),
	'born-year' => F::year(),
	'dead-year' => F::year(),
]);
```

Other usage is to save all forms of your app under a namespace:

```php
namespace MyApp\Forms;

use FormManager\Builder as F;
use FormManager\Fields\Form;

class EditUserForm extends Form
{
	public function __construct()
	{

		$this->add([
			'name' => F::text()->maxlength(200)->label('Name'),
			'email' => F::email()->label('Email'),
			'password' => F::password()->label('Password'),
			'repeat_password' => F::password()->label('Repeat password')
		]);

		//Add a validator to check the password
		$this->addValidator('password-check', function($form)
		{
			$password1 = $form['password']->val();
			$password2 = $form['repeat_password']->val();

			if ($password1 !== $password2) {
				throw new FormManager\InvalidValueException('The passwords does not match');
			}
		});
	}
}
```

And create a factory

```php
use FormManager\FactoryInterface;

class MyForms implements FactoryInterface
{
	public function get($name, array $arguments)
	{
		$class = 'MyApp\\Forms\\'.ucfirst($name);

		if (class_exists($class)) {
			return new $class();
		}
	}
}
```

Use it:

```php
use FormManager\Builder as F;

F::addFactory(new MyForms());

$editUser = F::editUserForm();
```

Note: Each time you register a new factory, it will be prepended to the already registered ones, so if you register fields/containers called "Form", "Textarea", etc, they will be used instead the default. This allows extend them.

## Builder instances

The static builder is fine for most cases, but sometimes you need to combine differents builders with different factories. So you can create instances:

```php
use FormManager\Builder;
use FormManager\Factory;

//Create a builder instance adding the default FormManager factory:
$b1 = new Builder(new Factory());

//Create another builder instance with your custom factory:
$b2 = new Builder();
$b2->add(new MyCustomFactory());

//Now, you're ready to combine them:
$form = $b1->form([
	'name' => $b1->text(),
	'description' => $b2->textarea(),
	'email' => Builder::email()
]);
```


text:
---
layout: page
title: MB3N
subtitle: Rule Learning using NIRS
---

In this ongoing project, we extend [MB3]({{site.baseurl}}/MB3/) investigation on the ability to learn and to apply rules by adding a non-invasive brain imaging technique to the experimental design: near-infrared spectroscopy (NIRS).  With this addition, we may be able to identify neural correlates that inform whether and to what extent rules' processing and learning are abstract, rule-based, and/or language specific. We may also be able to explore the time course of learning, thereby adjudicating between statistical mechanisms requiring extended time for sampling and faster symbolic mechanisms.

NIRS is a relatively new imaging technique. Variation across instruments, analysis pipelines, and laboratories is wide and standardization is currently lacking. Using NIRS in this large-scale collaborative project will provide us with the unique opportunity to discuss and solve some of these issues in a global network of experts in developmental research and brain imaging.

### Leads
[Judit Gervain](https://sites.google.com/site/juditgervain/)

### Collaborators
For a detailed index of collaborators (+ institutions, countries, studies), check the [**MB** collaborator dashboard](https://rodrigodalben.shinyapps.io/shiny_mb_map/): <video muted autoplay="autoplay" loop="loop" width="768" height="512">
    <source src="/assets/img/dashboard_studies.mp4" type="video/mp4">
    </video>

### Status
Stimuli creation.

### Links

* **Listserv**: [join here](https://mailman.stanford.edu/mailman/listinfo/manybabies3).
* **News**: [MB3N-news]({{site.baseurl}}/tags/#MB3N).

### Contribute
We encourage everyone who is interested in the project to [contribute]({{site.baseurl}}/sign_up_log_in/) and/or contact the project leader by e-mailing: judit.gervain [at] parisdescartes.fr

Please note that access to infants/infant lab is **not** a prerequisite.


text:
---
layout: single
author_profile: false
---

# Good Day at Once!

I'm a theoretical physicist working in the field of cosmology. Currently, I'm a PhD candidate at the University of Sussex, Brighton (UK) in the research group of Robert E. Smith.

I'm broadly interested in using cosmology in order to challenge current models describing the evolution of our Universe. In particular, my work focuses on studying the large-scale structure of matter and galaxies and what we can learn from their clustering properties.


text:
# Float Text

[![Download](https://api.bintray.com/packages/lucasgomes-eti/floattext/fabtext/images/download.svg)](https://bintray.com/lucasgomes-eti/floattext/fabtext/_latestVersion)

A Custom implementation for android float action button where a text property and some other functions was added.

![](./FloatText.gif)

## Download

```groovy
implementation 'com.lucasgomes:fabtext:1.0.4'
```

## Getting Started

Add this to your layout file namespace:
```xml
xmlns:app="http://schemas.android.com/apk/res-auto"
```

Component declaration:

```xml
<com.lucas.fabtext.FabText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:text="@string/app_name"
        app:text_color="@android:color/white"
        app:icon_color="@android:color/white"
        app:color="@color/colorAccent"
        android:id="@+id/fabText"/>
```

XML Properties:

* text
* icon
* text_color
* icon_color
* color

### Expand/Collapse

After getting a reference from the component in your code you can just call **fabText.expand()** and **fabText.collapse()** to do the job, the animation are handle by the component.

You can use this with scroll view to collapse automatic when user is scrolling, this library is shipped with a custom scroll view that provides the events for your activity or fragment when user start and stop scrolling.

Observable Scroll View Declaration:

```xml
<com.lucas.fabtext.ObservableScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/myScrollView"
            android:fillViewport="true">
```

In your activity or fragment you must implement this interface:

```kotlin
class MyFragment : Fragment(), ObservableScrollView.ScrollViewListener {
    myScrollView.setScrollViewListener(this)

    override fun onScrollViewTouchEvent(event: MotionEvent?) {
        when(event?.action) {
            MotionEvent.ACTION_DOWN -> {
                fabText.collapse()
            }
            MotionEvent.ACTION_UP -> {
                fabText.expand()
            }
        }
    }
}
```

### Loading

After getting a reference from the component in your code you can just call **fabText.startLoading()** and **fabText.finishLoading()** to do the job, doesn't matter if your fab is collapsed or not.

repository: lucasgomes-eti/floattext

gha_language: Kotlin

repo_name: lucasgomes-eti/floattext


text:
# Hex & RGB Converter

## This is a small Firefox addon that willll convert between RGB and Hex colors and display the result

### Demo: https://codepen.io/mrenoe/pen/mZVqNy
![Demo Image from Codepen](https://i.imgur.com/VipXFhj.png)

### TODO:
### Add ContentScript to access functions from console

repository: mrenoe/ConvertHexAndRGB

gha_language: JavaScript

repo_name: mrenoe/ConvertHexAndRGB


text:
# Bashpass
Powerful password management from the command line

# Installation
You can easily setup Bashpass to be runable from any console.
```
git clone https://github.com/kcotugno/bashpass.git
cd bashpass
sudo chmod 755 bashpass.sh
sudo ln -s /full/path/to/bashpass/bashpass.sh /usr/local/bin/bashpass
```

# Usage
#### Commands
+ [KEY] Retreive a password with the given key.
+ -a [KEY] Add a password with the given key.
+ -d [KEY] Remove the password with the given key.
+ -l List all keys.
+ -c [KEY] [VALUE] Set configuration options.
 + 'key' A gpg key fingerprint so your're not prompted on every encryption.

# Mac OS X
Bashpass should run on Mac OS X.

# TODO
1. Copy to clipboard from command line.
2. Password generation.

repository: kcotugno/bashpass

repo_name: kcotugno/bashpass


text:
# Checkbox <badge text="stable" />
The custom checkbox and it's states.

## Example
<div class="p-3 border rounded-2 my-3">
  <v-checkbox id="checkbox1" label="Check me" v-model="checked" />
</div>

```html
 <v-checkbox id="checkbox1" label="Check me" v-model="checked" />
```

## Props
Name       | Type     | Description | Default | Required
---------- | -------- | ----------- | ------- | --------
id         | [String, Number]   | Unique identifier |    | false
Name       | String             | Name of input element |    | false
label      | [String, Number]   | Label text        |    | false
value, v-model      | any      | The model that the checkbox value syncs to. **If you are not using `v-model`, you should listen for the `input` event and update value.**        |    | true
checked    | Boolean  | Whether or not the checkbox is checked by default. | false | false
trueValue	 | any	    | The value that will be written to the model when the checkbox is checked | true | false
falseValue | any	    | The value that will be written to the model when the checkbox is unchecked | false | false
tabindex	 | [Number, String]   | The checkbox input tabindex | None | false
submittedValue | any  | The value that will be submitted for the checkbox when it is checked. Applied as the value attribute of the checkbox input element. | 'on' | false
disabled	 | Boolean  | Whether or not the checkbox is disabled | false | false

## Events
Name     | Params   | Description
---------| ---------| -------------------
@focus   | event    | Emitted when the checkbox is focused
@blur    | event    | Emitted when the checkbox loses focus
@input   | event    | Emitted when the checkbox value is changed. The handler is called with the new value
@change  | event    | Emitted when a change in the checkbox value is committed. The handler is called with the new value

## Methods
Name       | Description
---------- | -----------
focus()    | Call this method to programmatically focus the checkbox

<script>
export default {
  data() {
    return { checked: false };
  },
};
</script>

repository: simplystack/modulist-vue

repo_name: simplystack/modulist-vue


text:
---
title: Property or method "" is not defined
meta:
  - name: description
    content: Property or method "keyword" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
  - property: og:title
    content: Property or method "keyword" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
  - property: og:description
    content: Property or method "keyword" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
  - property: og:url
    content: https://kyounghwan01.github.io/blog/Vue/vue/property-not-defined/
tags: ["vue"]
---

# Property or method "" is not defined

개발 중, 아래와 같은 에러를 볼 수 있습니다.

```
[Vue warn]: Property or method "keyword" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
```

- 프로퍼티나 메소드가 정의되지는 않았는데, 렌더할때 사용되더라 그러니까 컴포넌트 초기실행할때 정의하고 사용해라 이런 뜻입니다.

## 발생 이유

1. 프로퍼티의 경우 `data(){}` 내부에 정의하지 않은 경우
2. 정의는 했는데, 이상한 자리에 넣은 경우

```js
data() {
  return {
    // 이렇게 해야 했는데
    keyword: '',

    // 요렇게 데이터 구조를 착각하고 넣은 경우죠. 제가 그렇드라구요...
    count: {
      keyword: ''
    }
  }
}
```

## 해결

제자리에 잘 넣어주면 이상 없이 실행됩니다.

<TagLinks />

<Comment />


text:
# WP_MVC_Boilerplate
## Who are you ?
Well, my name is Julien, and I'm a ~~noob~~ Junior web developer based in Brittany, France. I love PHP, JS, kittens, ducks, chickens and bad puns. That pretty much sums it up.

## What is it about ?

This is a pet project of mine, that intends to add a healthy dosage of MVC in the development of a wordpress theme.
### Why ?
Mainly because I can and I have too much time on my hands. And also because, if I do enjoy fiddling around with Wordpress, its code hurts my eyes.

So, with the help of custom classes, I put most of the logic in separate files and my templates get much more clearer. Soon(-ish), I may even have an example to show you !

## How does it work ?

It's kind of simple.
1. First, you need to define a constant, THEME_PREFIX, that will be used to autoload your custom classes (adding them as is, tends to break wordpress, especially if you use ACF Pro).
2. Create your classes : for instance, I created a generic class *THEME_PREFIX*_Controller.php which retrieve most of the useful data of a post. As a habit, I declare it as an abstract class, and extend it at will, but you may of course use it as it is. Store the data you need returned in the class' attributes and ...
3. Instanciate your object in your page (```$page = new *THEME_PREFIX*_Page;``` for instance), and, finally ...
4. Template at will ! Outputting data will look something like ```<div class="omg"><?= $page->content; ?></div>```, making your templates much more readable and esay to maintain

## What's next ?
1. Sass and other nice stuff
2. What about Twig support ? I'm aware there are very good plugins that would do the trick, but as the purpose of this project is to learn, I'm thinking about developing it (although, I don't have a clue about how)

## And after that ?
At some point, I'll get some sleep.

## Support ? Fork ?
Don't hesitate to open issues or ring a bell if you find anything that doesn't seems right, but bear in mind that I'm doing this on my free time, as I started a full time job (Drupal, yay!) recently. This project is open to forks and all, so have at it if you want. And if you reaaaaaaaally want to repay me, just send me food. I love food.


text:
# Challenge Summary
This is code challenge #31 - find the first repeated word in a book

## Authors:
Clement Buchanan & Kale Lesko

## Whiteboard Process
[whiteboard](asset/repeatedWord.png)

## Approach & Efficiency
<!-- What approach did you take? Why? What is the Big O space/time for this approach? -->

## Solution

[code was referenced from here:](https://stackoverflow.com/questions/25644056/how-to-find-the-most-repeat-word-in-string/63988392)


text:
# Reverse Proxy Setup

This part of the collection can be used to setup a reverse proxy.
My personal choice for reverse proxies is Traefik since it was specially designed for this purpose.
The configuration is simple but offers enough options for more complex applications.
The integrated ACME functionality is also very easy to configure.

In my setup I enable the API functionality which provides us with a dashboard for a good overview of the active backend services which we are routing to.
This comes with the problem that Traefik doesn't generate certificates for its own services by default.
To overcome this, we label the Traefik service itself to be a Traefik backend.
This makes Traefik generate a certificate for itself.
To at least get one layer of security for the dashboard, we use basic HTTP authentication using an *.htaccess* file.
The workaround used here is inspired by this [blog post](https://medium.com/@xavier.priour/secure-traefik-dashboard-with-https-and-password-in-docker-5b657e2aa15f).

Setup steps:
1. After cloning first change the rights of the `acme.json` file with `chmod 600 acme.json`.
The `acme.json` file is the "certificate storage" that we'll mount from the host system to the docker container.
2. Generate an md5 login in the form *user:md5hash* (for example using this [generator](http://www.htaccesstools.com/htpasswd-generator/)) and put it in the `.htaccess` file.
3. Update the `treafik.toml` file with an appropriate E-Mail address
4. Change the `traefik.frontend.rule` of the Traefik service in the `docker-compose.yaml` file to match your domain/subdomain.
5. Start the container using `docker-compose up -d`
6. To add backend services which you want to route to, simply label them appropriately and don't forget to attach them to the created *docker network*.
A detailed description of the labels can be found on the [Traefik Docs](https://docs.traefik.io/configuration/backends/docker/#on-containers)

repository: kasokz/DevOps-Collection

gha_language: Shell

repo_name: kasokz/DevOps-Collection


text:
# Implementation of the Ritt-Wu's algorithm.

This project implements the Characteristic set method developed by Ritt and Wu. We use Haskell programming language, massiv libary to be more precise, to compute the elements of an ascending chaing with parallel computing.

### Prerequisites

The project is under constant development using GHC 8.6.4. Compilers under this version doesn't work correctly. We recommend use versions higher than 8.6.x. Also, the proyect execution need the cabal (recommended) or stack CLT.
## Running the tests

The test are evaluated using cabal new-bench, for testing purposes the default test are 10 samples.
## Built With

* [Massiv](http://hackage.haskell.org/package/massiv-<IP_ADDRESS>/docs/Data-Massiv-Array.html) - Haskell library to manage parallesm using OS threads.

## Authors

* **Jose Seraquive** - *Initial work*

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

repository: xxAVOGADROxx/Ritt-Wu

gha_language: Haskell

repo_name: xxAVOGADROxx/Ritt-Wu


text:
### From Captions to Visual Concepts and Back
Code for detecting visual concepts in images.

#### Installation Instructions ####
0. Create directory, checkout code, caffe, coco-hooks

  ```shell
  git clone git@github.com:s-gupta/visual-concepts.git code
  git clone git@github.com:pdollar/coco.git code/coco
  cd code/coco
  git checkout 3736a0068b6e4634563b0c5847d7783dae9bd461
  cd ../../
  ```

0. Make caffe and pycaffe

  ```shell
  git clone git@github.com:s-gupta/caffe.git code/caffe
  cd code/caffe
  git checkout mil
  make -j 16
  make pycaffe
  cd ../../
  ```

0.
  # This python scripts does the required copying.
   The precomputed results in the previous tarball
  # were not complete. v2 tar ball fixes this.
  wget ftp://ftp.cs.berkeley.edu/pub/projects/vision/im2cap-cvpr15b/trained-coco.v2.tgz && tar -xf trained-coco.v2.tgz
  ```

#### Demo ####
Look at ``demo.ipynb`` for a demo in IPython notebook.

#### Training, Testing the model ####
``cd code`` and execute relevant commands from the file ``scripts/scripts_all.py``

#### Citing
If you find this codebase useful in your research, please consider citing the following paper:

    @InProceedings{Fang_2015_CVPR,
      author = {Fang, Hao and Gupta, Saurabh and Iandola, Forrest and Srivastava, Rupesh K. and Deng, Li and Dollar, Piotr and Gao, Jianfeng and He, Xiaodong and Mitchell, Margaret and Platt, John C. and Lawrence Zitnick, C. and Zweig, Geoffrey},
      title = {From Captions to Visual Concepts and Back},
      booktitle = {The IEEE Conference on Computer Vision and Pattern Recognition (CVPR)},
      month = {June},
      year = {2015}
    }

repository: buttomnutstoast/VCNN

repo_name: buttomnutstoast/VCNN


text:
# ALIYUN::ECS::Instance {#concept_51198_zh .concept}

ALIYUN::ECS::Instance is used to create an ECS instance.

## Syntax {#section_ljn_3d2_lfb .section}

``` {#codeblock_zfi_624_1ju .language-json}
{
  "Type": "ALIYUN::ECS::Instance",
  "Properties": {
    "DiskMappings": List,
    "IoOptimized": String,
    "InternetChargeType": String,
    "PrivateIpAddress": String,
    "SystemDiskDiskName": String,
    "VpcId": String,
    "Description": String,
    "Tags": List,
    "HostName": String,
    "ImageId": String,
    "InstanceChargeType": String,
    "VSwitchId": String,
    "Password": String,
    "InstanceType": String,
    "SystemDiskCategory": String,
    "SystemDiskSize": Number,
    "ZoneId": String,
    "InternetMaxBandwidthOut": Integer,
    "InstanceName": String,
    "InternetMaxBandwidthIn": Integer,
    "UserData": String,
    "SecurityGroupId": String,
    "Period": Number,
    "AllocatePublicIP": Boolean,
    "SystemDiskDescription": String,
    "KeyPairName": String,
    "RamRoleName": String,
    "SpotPriceLimit": String,
    "SpotStrategy": String,
    "DeletionProtection": Boolean,
    "DeploymentSetId": String
  }
}

```

## Properties {#section_atw_kd2_lfb .section}

|Name|Type|Required|Editable|Description|Validity|
|----|----|--------|--------|-----------|--------|
|ImageId|String|Yes|Yes|The ID of the image used to start the ECS instance. You can use a public image, custom image, or Alibaba Cloud Marketplace image.| When editing a template, you can specify either the image type and version or only the image type. ROS automatically selects an appropriate public image ID.

 You can use the wildcard character \(\*\) to represent part of an image ID.

 Take the Ubuntu public images provided by Alibaba Cloud as an example. You can use one of the following methods to specify the public image ID for the ECS instance:

 If you enter ubuntu,

 the system matches it with the following ID: ubuntu16\_0402\_64\_20G\_alibase\_20170818.vhd

 If you enter ubuntu\_14,

 the system matches it with the following ID: ubuntu\_14\_0405\_64\_20G\_alibase\_20170824.vhd

 If you enter ubuntu\*14\*32,

 the system matches it with the following ID: ubuntu\_14\_0405\_32\_40G\_alibase\_20170711.vhd

 If you enter ubuntu\_16\_0402\_32,

 the system matches it with the following ID: ubuntu\_16\_0402\_32\_40G\_alibase\_20170711.vhd

 |
|InstanceType|String|Yes|No|The type of the ECS instance. For more information, see [Instance type families](https://partners-intl.aliyun.com/help/doc-detail/25378.htm).|None|
|SecurityGroupId|String|Yes|No|The ID of the security group to which the created instance will belong.|None|
|Description|String|No|No|The description of the ECS instance.|The description can be up to 256 characters in length.|
|InstanceName|String|No|No|The name of the ECS instance.|The name can be up to 128 characters in length and can contain letters, digits, underscores \(\_\), periods \(.\), and hyphens \(-\).|
|Password|String|No|No|The password used to log on to the ECS instance.| The password must be 8 to 30 characters in length.

 It must contain letters, digits, and special characters.

 The following special characters are allowed: \( \) ' ~ ! @ \# $ % ^ & \* - + = | \{ \} \[ \] : ; ‘ < \> , . ? / - If you specify the Password parameter in the API request, use HTTPS to secure the API and protect your password.

 |
|HostName|String|No|No|The hostname of the ECS instance.| The hostname must be at least 2 characters in length.

 It cannot start or end with a period \(.\) or a hyphen \(-\). It cannot contain consecutive periods \(.\) or hyphens \(-\).

 For Windows-based instances, the hostname must be 2 to 15 characters in length and can contain letters, digits, and hyphens \(-\). It cannot contain periods \(.\) and cannot be composed of only digits.

 For Linux-based instances, the hostname must be 2 to 30 characters in length and can contain letters, digits, hyphens \(-\), and periods \(.\). You can use periods \(.\) to separate a name into multiple segments.

 |
|AllocatePublicIP|Boolean|No|No|Specifies whether the system allocates a public IP address to the instance. If InternetMaxBandwidthOut is set to 0, no public IP addresses will be allocated.|Default value: true|
|PrivateIpAddress|String|No|No|The private IP address of an instance in a VPC. The specified IP address must not be used by other instances in the VPC.|None|
|InternetChargeType|String|No|No|The billing method for Internet traffic.| Valid values: PayByBandwidth and PayByTraffic

 Default value: PayByTraffic

 |
|InternetMaxBandwidthIn|Integer|No|No|The maximum inbound bandwidth from the Internet. Unit: Mbit/s.|Valid values: 1 to 100. Default value: 100.|
|InternetMaxBandwidthOut|Integer|No|No|The maximum outbound bandwidth to the Internet. Unit: Mbit/s.| Valid values in PayByBandwidth mode: 0 to 200. Default value: 0.

 Valid values in PayByTraffic mode: 1 to 200. If you choose to use the PayByTraffic mode, you must specify this parameter.

 |
|IoOptimized|String|No|No|Specifies whether the created instance is I/O optimized.|Valid values: none \(non-I/O optimized\) and optimized \(I/O optimized\). Default value: none.|
|DiskMappings|List|No|No|The data disks to be attached to the ECS instance.|A maximum of 16 data disks can be attached.|
|SystemDiskCategory|String|No|No|The type of the ECS instance system disk.|Valid values: cloud, cloud\_efficiency, cloud\_ssd, and ephemeral\_ssd|
|SystemDiskDescription|String|No|No|The description of the ECS instance system disk.|None|
|SystemDiskDiskName|String|No|No|The name of the ECS instance system disk.|None|
|SystemDiskSize|Number|No|Yes|The size of the ECS instance system disk. Unit: GB.| Valid values: 40 to 500.

 If a custom image is used to create a system disk, make sure that the size of the system disk is greater than that of the custom image.

 |
|Tags|List|No|No|The custom tags of the ECS instance.|A maximum of 20 tags can be specified in the \[\{"Key":"tagKey","Value":"tagValue"\}, \{"Key":"tagKey2","Value":"tagValue2"\}\] format.|
|UserData|String|No|No|The user data you provide when you create the ECS instance.|The user data can be up to 16 KB in size. You must convert the data into Base64-encoded strings. If the data contains special characters, add a backslash \(\\\) immediately before each special character.|
|ZoneId|String|No|No|The ID of the zone where the ECS instance resides.|None|
|VpcId|String|No|No|The ID of the VPC to which the ECS instance will belong.|None|
|VSwitchId|String|No|No|The ID of the VSwitch for the ECS instance.|None|
|InstanceChargeType|String|No|No|The billing method of the ECS instance.| Valid values: PrePaid and PostPaid

 Default value: PostPaid. If you set this parameter to PrePaid, make sure you have sufficient balance in your account. Otherwise, the instance will fail to be created.

 |
|Period|Number|No|No|The subscription period of the ECS instance. This parameter must be set when the InstanceChargeType parameter is set to PrePaid. This parameter is ignored when the InstanceChargeType parameter is set to PostPaid.|Valid values: 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, and 36. Unit: months.|
|KeyPairName|String|No|No|The name of the key pair that is used to connect to the ECS instance.| For Windows-based instances, this parameter is empty by default.

 For Linux-based ECS instances, the Password parameter will still take effect if the KeyPairName parameter is specified. However, logon by password is disabled, and the KeyPairName value is used.

 |
|RamRoleName|String|No|No|The RAM role name of the instance. You can call the ListRoles API to query the role name. For more information, see [CreateRole](https://partners-intl.aliyun.com/help/doc-detail/28710.htm) and [ListRoles](https://partners-intl.aliyun.com/help/doc-detail/28713.htm).|None|
|SpotPriceLimit|String|No|No|The maximum hourly price of the instance.|This parameter is only valid when the `SpotStrategy` parameter is set to SpotWithPriceLimit. A maximum of three decimal places can be specified.|
|SpotStrategy|String|No|No|The spot strategy for a pay-as-you-go instance.|This parameter is only valid when the `InstanceChargeType` parameter is set to PostPaid. Valid values: NoSpot: specifies a regular pay-as-you-go instance.

 SpotWithPriceLimit: specifies a pay-as-you-go instance with a maximum hourly price.

 SpotAsPriceGo: specifies a pay-as-you-go instance priced at the market price at the time of purchase.

 Default value: NoSpot

 |
|DedicatedHostId|String|No|No| The ID of the dedicated host \(DDH\) for the ECS instance. You can use the API to query the list of DDH IDs.

 After you set the DedicatedHostId parameter, the system automatically ignores the SpotStrategy and SpotPriceLimit settings in the request. This is because you cannot create preemptible instances on DDHs.

 |None|
|PeriodUnit|String|No|No|The unit of billing cycle for the ECS instance. When the PeriodUnit parameter is set to Week:

 -   Valid values for the Period parameter: 1, 2, 3, and 4
-   Valid values for the AutoRenewPeriod parameter: 1, 2, and 3

 When the PeriodUnit parameter is set to Month: -   Valid values for the Period parameter: 1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36, 48, and 60
-   Valid values for the AutoRenewPeriod parameter: 1, 2, 3, 6, and 12

 Default value: Month|Valid values: Week and Month. Default value: Month.|
|AutoRenewPeriod|Number|No|No|The automatic subscription renewal period for the ECS instance. This parameter is required when AutoRenew is set to True. Valid values: 1, 2, 3, 6, and 12.|Valid values: 1, 2, 3, 6, and 12|
|AutoRenew|String|No|No|Specifies whether to enable automatic renewal for the ECS instance. Default value: False. This parameter is only valid when InstanceChargeType is set to PrePaid.|Valid values: -   True: specifies to enable automatic renewal for the instance.
-   False: specifies to disable automatic renewal for the instance.

 |
|DeletionProtection|Boolean|No|No|The release protection property of the instance. It specifies whether the instance can be released from the ECS console or through the DeleteInstance API.|Valid values: true and false|
|DeploymentSetId|String|No|Yes|The ID of the deployment set used to create the ECS instance.|None|

## DiskMappings syntax {#section_3b8_74v_45b .section}

``` {#codeblock_0yd_jyo_omg .language-json}
"DiskMappings": [
  {
    "Category": String,
    "DiskName": String,
    "Description": String,
    "Device": String,
    "SnapshotId": String,
    "Size": String
  }
]
```

## DiskMappings properties {#section_8il_fs8_t3z .section}

|Name|Type|Required|Editable|Description|Validity|
|----|----|--------|--------|-----------|--------|
|Size|String|Yes|No|The size of a data disk. Unit: GB.|None|
|Category|String|No|No|The type of a data disk.| Valid values: cloud, cloud\_efficiency, cloud\_ssd, and ephemeral\_ssd

 Default value: cloud

 |
|DiskName|String|No|No|The name of a data disk.|The name can be up to 128 characters in length and can contain letters, digits, underscores \(\_\), periods \(.\), and hyphens \(-\).|
|Description|String|No|No|The description of a data disk.|The description must be 2 to 256 characters in length. Default value: null.|
|Device|String|No|No|The device name of a data disk to be attached to the instance.|If you do not set this parameter, the system allocates a device name in alphabetical order from /dev/xvdb to /dev/xvdz.|
|SnapshotId|String|No|No|The ID of the snapshot used to create a data disk.|None|

## Tags syntax {#section_gff_lrv_g26 .section}

``` {#codeblock_4cc_u4e_0rm .language-json}
"Tags": [
  {
    "Value": String,
    "Key": String
  }
]
```

## Tags properties {#section_fes_3kc_798 .section}

|Name|Type|Required|Editable|Description|Validity|
|----|----|--------|--------|-----------|--------|
|Key|String|Yes|No|None|None|
|Value|String|No|No|None|None|

## Response parameters {#section_dx4_222_lfb .section}

**Fn::GetAtt**

-   InstanceId: the ID of the instance. The instance ID is a globally unique identifier \(GUID\) generated by the system for the instance.
-   PrivateIp: the private IP address of the VPC-connected instance. This parameter is only valid when the `NetworkType` parameter is set to VPC.
-   InnerIp: the private IP address of the classic network-connected instance. This parameter is only valid when the `NetworkType` parameter is set to Classic.
-   PublicIp: the list of public IP addresses of the classic network-connected instance. This parameter is only valid when the `NetworkType` parameter is set to Classic.
-   ZoneId: the ID of the zone where the instance resides.
-   HostName: the hostname of the instance.

## Examples {#section_z3v_222_lfb .section}

``` {#codeblock_11v_7g5_g53 .language-json}
{
  "ROSTemplateFormatVersion": "2015-09-01",
  "Resources": {
    "WebServer": {
      "Type": "ALIYUN::ECS::Instance",
      "Properties": {
        "ImageId": "m-25l0rc****",
        "InstanceType": "ecs.t1.small",
        "SecurityGroupId": "sg-25zwc****",
        "ZoneId": "cn-beijing-b",
        "Tags": [{
            "Key": "tiantt",
            "Value": "ros"
        },{
            "Key": "tiantt1",
            "Value": "ros1"
        }
        ]
      }
    }
  },
  "Outputs": {
    "InstanceId": {
         "Value": {"get_attr": ["WebServer","InstanceId"]}
    },
    "PublicIp": {
         "Value": {"get_attr": ["WebServer","PublicIp"]}
    }
  }
}
```

repository: fouadyousufdar/ros

repo_name: fouadyousufdar/ros


text:
# docker-redis-ephemeral
Basic Redis image (based on Alpine) with persistence disabled.

## Description
All of the `save *` arguments in `redis.conf` have been commented-out to
disable persistence and unnecessary disk i/o when redis is only used as a
cache, message bus, and other similar scenarios.

## Relevant files
| File Name    | File Path                         |
| ------------ | --------------------------------- |
| `redis.conf` | `/usr/local/etc/redis/redis.conf` |

repository: brandonpapworth/docker-redis-ephemeral

repo_name: brandonpapworth/docker-redis-ephemeral