text:
# Phones recognition and articulatory features detection using LAS

## Overview
This repository is an official implementation for Interspeech 2019 "Attention model for articulatory features detection" [paper][paper_arxiv].
Base code is a fork of [WindQAQ implementation][original_implementation] of [*Listen, Attend and Spell*][las] (LAS) model in Tensorflow.

Our contributions:
* Recipes for some common datasets: Librispeech, Common Voice, TIMIT, L2 artctic, SLR32 and VCTK.
* Phones/words/characters/binary features data collection switch. Usefull if you intend to train on IPA targets.
* Support of MFE, MFCC and Lyon's model features.
* Decoder for phonological features.
* Support for multitask training: phones recognition and indicators estimation.
* Option for joint training with text auto-encoder.

## Usage

### Requirements
Run `pip install -r requirements.txt` to get the necessary version.
To do training on phone targets, you'll need `espeak-ng` installed.

### Data Preparing
Before running the training script, you should convert your data into TFRecord format, collect normalization data and prepare vocabulary.
To do that, collect your train and test data in separate CSV files like this:
```csv
filename1.wav,en,big brown fox
filename2.wav,en,another fox
```
Recipes for some datasets are available in `recipes` folder.
After that call data collection script: `process_all.py`.
```text
usage: preprocess_all.py [-h] --input_file INPUT_FILE --output_file
                         OUTPUT_FILE [--norm_file NORM_FILE]
                         [--vocab_file VOCAB_FILE] [--top_k TOP_K]
                         [--n_mfcc N_MFCC] [--n_mels N_MELS] [--window WINDOW]
                         [--step STEP] [--n_jobs N_JOBS]

optional arguments:
  -h, --help            show this help message and exit
  --input_file INPUT_FILE
                        File with audio paths and texts.
  --output_file OUTPUT_FILE
                        Target TFRecord file name.
  --norm_file NORM_FILE
                        File name for normalization data.
  --vocab_file VOCAB_FILE
                        Vocabulary file name.
  --top_k TOP_K         Max size of vocabulary.
  --n_mfcc N_MFCC       Number of MFCC coeffs.
  --n_mels N_MELS       Number of mel-filters.
  --window WINDOW       Analysis window length in ms.
  --step STEP           Analysis window step in ms.
  --n_jobs N_JOBS       Number of parallel jobs.
  --targets {words,phones}
                        Determines targets type.
```

### Training and Evaluation
Simply run `python3 train.py --train TRAIN_TFRECORD --vocab VOCAB_TABLE --model_dir MODEL_DIR --norm NORM_FILE`.
You can also specify the validation data and some hyperparameters.
To find out more, please run `python3 train.py -h`.
```text
usage: train.py [-h] --train TRAIN [--valid VALID] --vocab VOCAB [--norm NORM]
                [--mapping MAPPING] --model_dir MODEL_DIR
                [--eval_secs EVAL_SECS] [--encoder_units ENCODER_UNITS]
                [--encoder_layers ENCODER_LAYERS] [--use_pyramidal]
                [--decoder_units DECODER_UNITS]
                [--decoder_layers DECODER_LAYERS]
                [--embedding_size EMBEDDING_SIZE]
                [--sampling_probability SAMPLING_PROBABILITY]
                [--attention_type {luong,bahdanau,custom}]
                [--attention_layer_size ATTENTION_LAYER_SIZE] [--bottom_only]
                [--pass_hidden_state] [--batch_size BATCH_SIZE]
                [--num_channels NUM_CHANNELS] [--num_epochs NUM_EPOCHS]
                [--learning_rate LEARNING_RATE] [--dropout DROPOUT]

Listen, Attend and Spell(LAS) implementation based on Tensorflow. The model
utilizes input pipeline and estimator API of Tensorflow, which makes the
training procedure truly end-to-end.

optional arguments:
  -h, --help            show this help message and exit
  --train TRAIN         training data in TFRecord format
  --valid VALID         validation data in TFRecord format
  --vocab VOCAB         vocabulary table, listing vocabulary line by line
  --norm NORM           normalization params
  --mapping MAPPING     additional mapping when evaluation
  --model_dir MODEL_DIR
                        path of saving model
  --eval_secs EVAL_SECS
                        evaluation every N seconds, only happening when
                        `valid` is specified
  --encoder_units ENCODER_UNITS
                        rnn hidden units of encoder
  --encoder_layers ENCODER_LAYERS
                        rnn layers of encoder
  --use_pyramidal       whether to use pyramidal rnn
  --decoder_units DECODER_UNITS
                        rnn hidden units of decoder
  --decoder_layers DECODER_LAYERS
                        rnn layers of decoder
  --embedding_size EMBEDDING_SIZE
                        embedding size of target vocabulary, if 0, one hot
                        encoding is applied
  --sampling_probability SAMPLING_PROBABILITY
                        sampling probabilty of decoder during training
  --attention_type {luong,bahdanau,custom}
                        type of attention mechanism
  --attention_layer_size ATTENTION_LAYER_SIZE
                        size of attention layer, see
                        tensorflow.contrib.seq2seq.AttentionWrapperfor more
                        details
  --bottom_only         apply attention mechanism only at the bottommost rnn
                        cell
  --pass_hidden_state   whether to pass encoder state to decoder
  --batch_size BATCH_SIZE
                        batch size
  --num_channels NUM_CHANNELS
                        number of input channels
  --num_epochs NUM_EPOCHS
                        number of training epochs
  --learning_rate LEARNING_RATE
                        learning rate
  --dropout DROPOUT     dropout rate of rnn cell
```

### Tensorboard
With the help of tensorflow estimator API, you can launch tensorboard by `tensorboard --logdir=MODEL_DIR`  to see the training procedure.

### Notes

If you intend to use LAS architecture and not vanilla seq2seq model,
use `--use_pyramidal --pass_hidden_state --bottom_only` flags combination.

Rerun of `train.py` would result in most of parameters restored from original run.
Thus, if you wish to override this behaviour, delete `hparams.json` file.

This codebased has been used to train models referenced in our paper. It also can be used to replicate results on sequence level accuracies and word error rates.
For frame level accuracies computations we used a Jupyter Notebook that is not included in this repository.

## References

- [Paper e-print][paper_arxiv]
- [WindQAQ implementation][original_implementation]
- [Listen, Attend and spell][las]
- [How to create TFRecord][sequence_example]
- [nabu's implementation][nabu]
- [Tensorflow official seq2seq code][nmt]
- [ASR model evaluation toolkit][asr_eval]

[paper_arxiv]: https://arxiv.org/pdf/1907.01914.pdf
[original_implementation]: https://github.com/WindQAQ/listen-attend-and-spell
[nabu]: https://github.com/vrenkens/nabu
[nmt]: https://github.com/tensorflow/nmt
[las]: https://arxiv.org/pdf/1508.01211.pdf
[sequence_example]: https://github.com/tensorflow/magenta/blob/master/magenta/common/sequence_example_lib.py
[asr_eval]: https://github.com/belambert/asr-evaluation

repository: madved/phones-las

repo_name: madved/phones-las


text:
#  Parse Json File
A console application that reads in a json file using the an external module and prints a single known property value.

[Source](https://github.com/mwasplund/Soup/tree/master/Samples/ParseJsonFile)

## Recipe.toml
The Recipe file that sets the standard name, type, version, as well as the single external dependency of the [json11](https://github.com/dropbox/json11) project.
```
Name = "ParseJsonFile"
Version = "1.0.0"
Type = "Executable"
Dependencies = [
<EMAIL_ADDRESS>]
RuntimeDependencies = [
    "Message.json"
]
Source = [
    "Main.cpp",
]

```

## Message.json
A json file containing a single property containing a message for the application to print.
```
{
  "message": "Hello!"
}
```

## Main.cpp
A simple main method that reads the contents of a single json file, parses the json content and prints a single message from a known property.
```
#include <fstream>
#include <iostream>
#include <streambuf>
#include <string>

import json11;

int main()
{
    // Read in the contents of the json file
    auto jsonFile = std::ifstream("Message.json");
    auto jsonContent = std::string(
        std::istreambuf_iterator<char>(jsonFile),
        std::istreambuf_iterator<char>());

    // Parse the json
    std::string errorMessage;
    auto json = json11::Json::parse(jsonContent, errorMessage);

    // Print the single property value
    std::cout << "Message: " << json["message"].string_value() << std::endl;

    return 0;
}
```

## .gitignore
A simple git ignore file to exclude all Soup build output.
```
out/
```

license: MIT

repository: Tembocs/Soup

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: Tembocs/Soup


text:
Lightcurve Feature Extractor
========
Recommended prerequisite: Filelist with lightcurve filenames.

Recommendation (example given for long cadence lightcurves from a Kepler quarter):
1. Collect lightcurves into a single directory.
2. Generate a filelist of the contents of that directory (the lightcurves)

    for f in \*llc.fits; do echo $f >> filelist; done

NOTE: For unknown reasons the code is having issues processing a whole quarter at once. Recommend splitting
the files into at least 2 groups. An easy option is the splitting the files starting in 00 and 01

2. (alternate)

    for f in kplr00\*llc.fits; do echo $f >> Q??\_00filelist; done

    for f in kplr01\*llc.fits; do echo $f >> Q??\_01filelist; done

Where ?? is replaced by the quarter number.

Ways to use:
1. Run keplerml.py to calculate the lightcurve features, this will output a numpy array with the calculated features for each lightcurve.

        python keplerml.py path/to/filelist path/to/fitsfiles path/to/outputfile
2. Open Feature Calculation Example.ipynb in jupyter notebook to see examples of how to run feature calculation in a notebook.

Note: Using a 48-2.70GHz core linux computer (using 47 of the cores), processing 114,948 files took 54m:48s, which translates to 1.344 seconds to process a single file on one core. If you have less cores (most computers have 1-8 cores), multiply the number of files by the time to process a single file, and divide by the number of cores in the computer for an estimate on how long it will take to process.

repository: d-giles/lcfeatures

gha_language: Jupyter Notebook

repo_name: d-giles/lcfeatures


text:
#Titanium Validation Module

##Description
This module is designed to help you with validating input fields & switches. It is based on Rick Harrisons [validate.js](http://rickharrison.github.com/validate.js).

##Please note:
I am not actively maintaining Titanium plugins at the moment. Titanium has evolved a lot since my initial versions and best practices have changed a lot, to the better, I have to say. So, although these plugins should do the job, feel free to send me pull requests! I would be more than happy to see these plugins as modules :)

##Installation
Just add `de.mwfire.validate.js` to your current projects `lib` folder. Create the folder as a child of Resources if it does not exist yet on classic Titanium projects. If you are using Alloy `lib` should be in the `app` directory.

##Methods
**`validate( inputFields, options )`**

Inits validation and returns **true** if all validation rules have passed, otherwise **false**

* **inputFields** [Array] required
The input fields you want to validate
* **options** [Dictionary] optional
Options, by now only **showAlert: bool** is supported. Set true if you want to display an alert containing the validation errors

##Rules
Applying rules is easily done by adding a `rule` and `name` property to your Ti.UI.TextField or Ti.UI.Switch. You set all rules in your .tss file as well, only the `matches` rule and Sitches need special treatment. The following rules are available and should be pretty self explanatory:

    required
    matches
    valid_email
    valid_emails
    min_length[int]
    max_length[int]
    exact_length[int]
    greater_than[float]
    less_than[float]
    is_checked
    agree_on
    age_at_least[int(years)]
    alpha
    alpha_numeric
    alpha_dash
    numeric
    integer
    decimal
    is_natural
    is_natural_no_zero
    valid_ip
    valid_base64
    valid_credit_card
    valid_url

Some rules require a parameter, passed in square brackets.

` rules: 'min_length[5]'`

Multiple rules can be combined, separated by **|**.

` rules: 'required|min_length[5]|integer'`

Have a look at the examples for more info.

##Accessing the module
To access this module, you would do the following:

    var validation = require('/lib/de.mwfire.validate');

If you are on Alloy, you can omit the lib folder:

    var validation = require('de.mwfire.validate');

##Example

```javascript
// Assuming you have a window called win
// Require the module
var validation = require('/lib/de.mwfire.validate');

// Email is required and has to be valid
var emailField = Ti.UI.createTextField({
    hintText     : 'Email',
    name         : 'Email',
    rules        : 'required|valid_email'
});
win.add(emailField);

// Password is required, min of 5 chars and max of 30
var passwordField = Ti.UI.createTextField({
    hintText     : 'Password',
    name         : 'Password',
    passwordMask : true,
    rules        : 'required|min_length[5]|max_lenght[30]'
});
win.add(passwordField);

// Special case "matches". Add property "matchField"
// and pass the field you want to validate
var repeatPasswordField = Ti.UI.createTextField({
    hintText     : 'Repeat Password',
    name         : 'Repeat Password',
    passwordMask : true,
    rules        : 'matches',
    matchField   : passwordField
});
win.add(repeatPasswordField);

// Special case "switch".
// Add property "isSwitch" and pass true
var termsCheckbox = Ti.UI.createSwitch({
    rules        : 'is_checked',
    isSwitch     : true
});
win.add(termsCheckbox);

// Our send button
var sendButton = Ti.UI.createButton({
   title         : 'Send'
});

// Validate the "form"
sendButton.addEventListener('click', function() {
   if(validation.validate([ emailField, passwordField, repeatPasswordField, termsCheckbox], { showAlert: true})) {
      alert('Passed!');
   } else {
      alert('Failed!');
   }
});
```

##Note
I did not have the chance to test all rules, so if you find anything that does not work, feel free to notify me!

##Platform
This should work on all platforms, though it is only tested on iOS and Android.

## Author

© 2013 Martin Wildfeuer

mwfire web development

[www.mwfire.de](http://www.mwfire.de)

## License

Licensed under the Apache License, Version 2.0 (the "License")

repository: mwfire/titanium-module-validation

gha_language: JavaScript

repo_name: mwfire/titanium-module-validation


text:
1. Introduction to Digital Imaging
- Image Sensing and Acquisition
   - **Describe the operational principles of CCD and CMOS sensors.**
   - **List the major differences between CCD and CMOS image sensors.**
- CCD: Charged Coupled Device
   - Charge accumulates during exposure
   - Collected charges shifted out by horizontal and then vertical shift registers
   - Each pixel is converted to the voltage
   - Voltage is amplified by an amplifier
   - Blooming: The charge collected by a pixel leaks to other pixels. Electrons move more easily in the vertical direction, resulting in a vertical streak.
- CMOS: Complementary Metal Oxide Semiconductor
   - In a CMOS sensor, each pixel has its own charge-to-voltage conversion, amplifiers and digitization circuits -> No blooming, faster operation.
   - Digital values are read in a line-by-line fashion -> Rolling shutter artifact
   - CMOS circuitry dissipates less power.
| CCD                                                | CMOS                                      |
|----------------------------------------------------|-------------------------------------------|
| Broadcast cameras (still industry standard for TV) | Phone, Web, and digital SLR cameras       |
| Better image quality                               | Cheaper and faster (data transfer)        |
| Susceptible to the blooming effect                 | Susceptible to the rolling shutter effect |
   - Know how colour images are captured by CCD and CMOS image sensors.
     - 3 CCDs capturing red, green and blue, A prism
     - CMOS: Arranging colour filters on a square grid of photosensors, 50% green, 25% red and blue
        - Separated channel -> interpolated channel -> summing three channels

-  Digital Imaging Fundamentals (P30)
   - Know the definitions of the digital image (pixel, gray level) and the colour map.
   - Know the amount of storage required for an image.
     - i, j -> B = 8 -> L = 2^8 = 256 -> 0-255
     - 3 * M * N * B/8
   - Know the following terms relating to digitalization: continuous-tone image -> digital
     - Sampling: its brightness is measured and sampled at discrete locations to form an element in a rectangular matrix.
     - Quantization: Each element in the sampled image is quantized
     - Dynamic range: The range of grey levels
     - Spatial resolution: Physical size of a pixel.
       - Pixelation
     - Brightness resolution: how accurate the greyscale value can represent
       - Brightness contouring: less bits -> single grey level
   - Know how nearest neighbor and bilinear interpolation work.
       - Gray level of (i,j) is assigned to be that of its nearest neighbour.
       - Weighted average of 4 closest neighbours.
       - p(s, t) = (1-s)(1-t)p(00) + (1-s)tp(01) + (1-t)sp(10) + stp(11)
-  Colour Fundamentals
   - Know different colour models introduced and what they are good for.
       - 65, 33, 2
       - Grayscale along the diagonal
       - Quantize each component into 6 levels (6^3)
       - [C, M, Y] = [1-R, 1-G, 1-B] - P73
       - HSV space we can process only brightness without altering the color - P79

2. Point Operations
-  Define point operations.
-  Common Point Operations
   - Describe the following point operations:
     - Linear point operation
        - b affects brightness of image by shifting grey levels.
        - a affects contrast and brightness.
     - Logarithmic
        - reveal more detail, extremely large range of values
     - Power law
        - (<1) Map narrow range of dark input to wider range of output
        - (>1) Map wide range of dark input to narrow range of output
     - Window and level
   - Know when these point operations are used.
-  Histogram Processing
   - Know how to derive the expression for output histogram given input histogram and point operation in continuous gray-level domain.
   - Know how to apply the expression.
   - H[i] & D[i]
   - P30 H(D) = HA(f-1(D))/f'(f-1(D))
-  Histogram Equalization
   - Histogram equalization for images with continuous or discrete gray levels. Expected to know formula. - P42
-  Histogram Specification (Matching) [**P69**]
   - Obtain point operations achieving histogram specification in continuous and discrete domains.

3.  Spatial Filtering
-  Need to know how to perform convolution and correlation for 2D discrete images. Know the difference between convolution kernel and computational molecule.
   - filter/convolution kernel.
   - Flip the kernel g in horizontal and vertical directions -> computational molecule.
   - Weighted filter
-  Know how borders are handled in the correlation operation.
-  Smoothing spatial filters (Remove noise)
   - Boxcar filter (avg), Gaussian filter (involves convolution)
     - P18
   - Order-statistic filters (do not involve convolution)
     - Median filter.
     - remove salt-and-pepper noise
-  Sharpening spatial filters (Feature enhancement)
   - First derivative filters (e.g., Prewitt filter, Sobel filter – need to know how they are defined). Need to know how to apply these filters in x and y directions and calculate gradient magnitude.
   - Second derivative filters (Laplacian).
-  Use Laplacian for image enhancement. Need to know how one correlation operation can be used to compute I - \delta^2*I. Which property of linear filtering is used? - P39

4. **Transform Domain Filtering** [4.1]
-  Fourier Transform in 1D and 2D
   - Know Fourier transform for continuous signals and discrete signal.
   - Describe sampling theorem in terms of the Fourier transforms of pulse samples and discrete samples.
   - Know discrete Fourier transform
     - Know how to perform circular convolution
     - Describe why wraparound error occurs. - Need zero padding
     - Know how to perform linear convolution via circular convolution.
-  Frequency Domain Filtering [4.2]
   - Why do we filter in frequency domain instead of spatial domain?
   - Know the effect of circular convolution in 2D filtering and how to mitigate the effect.
   - Know ideal, Gaussian and Butterworth lowpass filters.
   - Design lowpass filter using ideal, Gaussian and Butterworth filters.
   - Know ideal, Gaussian, Butterworth bandpass and bandreject filters.
   - Know how to construct a notch filters based on ideal, Gaussian and Butterworth filters.

5. Image Restoration and Reconstruction
-  Know noise removal filters:
   - Arithmetic mean filter - mean(sum)
   - geometric mean filter - (mul)^(1/n)
   - median filter - median
   - alpha-trimmed mean filter - region(mean(sum))
   - adaptive median filter -
-  Know three ways for estimating impulse response:
   - observation
   - experimentation
   - modelling.
-  Know inverse filtering
   - What issue does it have? enhance the noise, prominent at regions where is close to 0
   - How to mitigate this issue? Apply the inverse filter only at the low frequencies
-  Know Wiener filtering - Mean Squared Error (MSE) Filtering
   - What does it optimize?
   - What issue does it have? - We do not know noise and the spectrum of the undegraded image
   - How to mitigate this issue? - Approximate an average signal-to-noise ratio, denoted by SNR, used across all (u,v)
-  Image Reconstruction from Projections
   - Know Radon Transform
   - Define “sinogram”. Why is this representation called sinogram? - The Radon transform data is often called a sinogram because the Radon transform of an off-center point source is a sinusoid.
   - Describe backprojection. Describe mathematically why backprojection results in a blurred image.
   - Know the Fourier-slice theorem
   - Define “filtered backprojection”. Describe the filter that should be used mathematically. List the steps involved in filtered backprojection. P92

6. Geometric operations
-  Linear transformation: expected to know formulae to relate coordinates in the input image with those in the output image
   - Translation
   - Scaling about origin or an arbitrary point
   - Rotation about origin or an arbitrary point
     - [cos, -sin] [sin, cos]:
   - Composite transformation. Order of operation does matter.
-  For all transformation described in (a), know how to define the affine matrix to implement the transformation using Python built-in tool [i.e., need to be able to determine T passed to cv2.warpAffine(im, T, (width, height)) for the transformation described in (a).] P 39
-  Define forward mapping and backward mappings. Why are the advantages of using backward mapping? Need to be able to perform the backward mapping given the forward mapping [i.e., need to be able to express (i,j) in terms of (i’,j’).]
-  Grey level interpolation
   - Nearest neighbour
   - Bilinear
-  Landmark registration: expected to know how the four transformation parameters, a, b, ti and tj, are derived.

7. Morphological Image Processing
-  Binary morphological operations
   - Know how to perform erosion and dilation.
   - Know the applications of erosion and dilation.
      - FIT - erosion -> ALL of the ‘1’s of SE are covered
        - Shrinking objects
        - Removing small objects or noise
        - Removing bridges and branches
        - Removing protrusions
        - Enlarge holes
      - HIT - dilation -> any ONE of the ‘1’s of SE is covered
        - Growing objects
        - Repairing intrustions
        - Filling gaps
        - Filling holes
   - Know how to perform opening and closing.
        - (A-B)+B
        - (A+B)-B
   - Know the geometric interpretations of opening and closing.
-  Connected components and labelling
   - Identify connected components based on the 4-connectedness and 8-connectedness definitions.
   - Understand the two-pass labelling algorithm.
-  Morphological algorithms
   - Hit-Or-Miss transform
   - Boundary extraction
   - Region filling
   - Skeletonization (no need to know detailed algorithm)
-  Grayscale Morphology
   - Know how to perform erosion and dilation.
   - Know how to perform opening and closing.
   - Know the geometric interpretations of opening and closing.
   - Know the following grayscale morphology algorithms: morphological smoothing, morphological gradient, top-hat and bottom-hat transformations

8. Image segmentation
-  Edge detection
   - Know how to get 1st and 2nd derivatives of an image using convolution/correlation.
     - backward f(x) - f(x-1)
     - forward f(x+1) - f(x)
     - center f(x+1) - f(x-1)
     - f(x+1)+f(x-1)-2f(x)
   - Know how to compute gradient vector, its magnitude and angle at each pixel.
     - P11
   - Know how to use the Laplacian of Gaussian (LoG) filter
     - P24
   - Know how to generate an edge map of an image by finding the zero-crossing in an LoG filtered image.
   - Know the three criteria for an optimal edge detected as defined by Canny.
     - Good detection
     - Good localization
     - Single response
   - Know how to generate an edge map of an image using the Canny edge detector.
-  Discrete dynamic contour (DDC)
   - Know what is a deformable model for segmentation.
   - Expected to be able to calculate the following items: di, ti, ri, ci, and len(ci).
     - P50/P62/P63/P65
   - Expected to know how internal force is computed to avoid collapsing of a closed contour to a point.
   - Given an external force, expected to calculate the actual external force applied to DDC to avoid clustering of vertices.

gha_language: CSS

gha_license_id: MIT


text:
---
layout: post
title: Kickstart your home practice!
date: 2022-08-17 08:43:00
author: Lucy Tennyson
image: "/uploads/yogaclockface.jpg"
categories:
  - Blog
---
Doing yoga at home in between classes will help you keep mobile for the rest of your life - but it's often hard to know what to do, or get started. You have to first, establish a routine, by deciding what time of day, and how long.  Say 10 minutes every morning, for example, or 20 minutes three times a week.

The clockface chart below is my attempt to help you get started and into a routine. The idea is to go round the clock from 1 pm. You can chose just to go as far as 2 pm (two warm up sequences) and then jump to 12 pm (a short relaxation). That'll give you a 10 minute sequence. If you add say 3, 5 and 7 pm, then you build up to 20 minutes.

![](/uploads/yogaclockface.jpg){: width="2182" height="2112"}

You can vary the numbers, but always add the first two and the last, and go in the order of the clock. The whole 12 will take about an hour. Once you get used to this sequence, you can vary the postures within each number, (for example, trying  different backbends, standing postures or warm up sequences).

We'll be using this clockface this term to help get you started.

repository: eye-division/lucytennyson-yoga

repo_name: eye-division/lucytennyson-yoga


text:
# Top Down Arcade Game

Here we will explore the concept and utilization of prefabs in Unity.

## What Are Prefabs?

["Prefabs"](https://docs.unity3d.com/Manual/Prefabs.html) are a blueprint or default of an object that we can copy and paste around our game.\
Let's explain it with an example.\
You are adding enemies to your game. This enemy is made of a few parts :

* Enemies have a sprite renderer.
* They have scripts that deal with movement, attacking, and health.
* They have a collider.
* They have a rigidbody.
* And the list goes on.

Now if you were to start adding these enemies you can see how long it will take you. For each enemy you add you will have to add all of these things and also set the values of each component.\
Now enters the prefab.\
You make a single enemy with all the bells and whistles, turn it into a prefab, and then you can place down as many enemy prefabs as you want and all these defaults are already set.

That should illustrate how great prefabs are and also how essential they are.\
So how do we make a prefab?

## How To Make Prefabs

First we need to create an object that we will make into a prefab. At this point you just need to make one, it does not need a purpose in your project here.\
You can put whatever you want onto this object. Perhaps make a "Ball" object that has a sprite (look up a ball sprite online or use the circle from the [Rube Goldberg](../1%20Rube%20GoldBerg%20Machine/Assets/WhiteCircle.png)), a circle collider, and rigidbody 2D.

![BallObject](Images/BallObject.JPG)

For best practice, first create a new folder in your project window and name it "Prefabs". Then drag the object into that folder.
Once we have that all set up to our liking all we have to do is drag the object from our hierarchy into our project window, and more specifically with into our prefabs folder.\
It's that easy. You'll now see our object was turned into a prefab inside the folder. Now we can use that in our scene instead of making new objects.

![BallPrefab](Images/BallPrefab.JPG)

## Using Prefabs

Having prefabs are great but now we need to actually use them. This is very simple. Just drag the prefab from the folder into the scene.\
Go ahead and drag a few onto the scene. When you press play you will notice that they fall because they all have the components we added to the prefab which included a Rigidbody.\
You can also individually edit these objects. Try changing some colors or size on the objects (from the hierarchy), not the prefab (in the folder).

![PlacingPrefabs](Images/PlacingPrefabs.JPG)

This is great so far but now to show you the real power of prefabs.\
Say we had a thousand of these balls around our scene and all of a sudden we decide that we need to change something on them. Now we need to go through all of them and update them. We'd likely have to go through different levels of our game and try to find them all. If we miss even one it might seriously mess up our game.\
Now if we used Prefabs we can update any number of these balls with a single click.\
Go into the Prefabs folder and double-click on the Ball prefab we made. This will open up a window where we can edit just our prefab.

![EditingPrefabs](Images/EditingPrefabs.JPG)

Within here we can edit the prefab itself. So whatever this looks like is what our prefabs will look like when we drag it onto the scene.\
Let's start by setting the color to green. Now we should see the ball as green. Let's go back to the game view we had.\
To do this click on "Scenes" in the top left of the scene view window. It should be beside the name of our prefab. Like this :

![SwitchingPrefabViews](Images/SwitchingPrefabViews.JPG)

Now in our scene it should look something like this :

![EditedPrefabs](Images/EditedPrefabs.JPG)

Not all of our circles are green. What's with that?\
Well if you [look back](#using-prefabs) at the prefabs before we edited the color you'll notice that one of them was blue and two were white. So why did only the white ones change?\
Well that's because those balls had the "default" color of the prefab. If a change is made to a prefab every instance of that prefab that has the default of value will update.\
Since we made the one ball blue by hand it's color value was not **not** default and therefore not changed. The color was [overriden](https://docs.unity3d.com/Manual/PrefabInstanceOverrides.html).\
 Take note of which ones update their color.

***Note***\
If you'd like to see whether an object has default values or custom values compared to the prefab you can just look at the Inspector. Any value that is not the default will have a bold name like this :

![OverridenValues](Images/OverridenValues.JPG)

You'll notice the color is in bold and has a blue line on the left of it.\
If you want to reset these values to the default you can click the "Overrides" dropdown just below the name of the object and revert them as you wish.

![RevertOverrides](Images/RevertOverrides.JPG)

Go right ahead and play around with these prefabs. There isn't much you can break when there's a reset button!\
It is important to understand how to use prefabs in order to make a quality game so spend some time with them.

## Player Prefab

We are going to create a Player Prefab to use in our game. We won't be able to add everything we need to right now but will build it up throughout this unit.\
Let's start by putting the [white square](../1%20Rube%20GoldBerg%20Machine/Assets/WhiteBox.png) we used in the [Rube GoldBerg](../1%20Rube%20GoldBerg%20Machine) unit into our game.\
Right click on your Hierarchy, scroll down to "2D Object", and create a new "Sprite". Name it "Player".\
Go into the Inspector and set it's sprite to the white box we just added. Just for fun make it blue (or whatever color you want!) using the Color option.\
Next we should add a [Box Collider 2D](https://docs.unity3d.com/Manual/class-BoxCollider2D.html) to our object. Make sure to use the 2D option. If you used the box sprite provided from this course the default size of the collider should be good.\
Next add a [Rigidbody 2D](https://docs.unity3d.com/Manual/class-Rigidbody2D.html). Again, make sure it's 2D. There are some other things to do here to ensure our player works with the movement code we will be writing soon.

* First set ["Gravity Scale"](https://docs.unity3d.com/ScriptReference/Rigidbody2D-gravityScale.html) to `0` to prevent the gravity from affecting our player.
* Set ["Collision Detection"](https://docs.unity3d.com/ScriptReference/Rigidbody2D-collisionDetectionMode.html) to ["Continuous"](https://docs.unity3d.com/ScriptReference/CollisionDetectionMode2D.html).
* And then tick off the ["Freeze Rotation"](https://docs.unity3d.com/ScriptReference/Rigidbody2D-freezeRotation.html) box under ["Constraints"](https://docs.unity3d.com/ScriptReference/Rigidbody2D-constraints.html).

With that we should be good to make this player into a prefab. Just [drag](#how-to-make-prefabs) it into the prefab folder.

![BasicPlayerPrefab](Images/BasicPlayerPrefab.JPG)

Now we can move on to making some scripts to manipulate that prefab and use input from the player to do so!

url: https://raw.githubusercontent.com/vishnu-rgb/GameDesign11/e68cec9a5554110cea95fffdf35754c6de75a359/3 Top Down Arcade/1 Prefabs.md

path: /3 Top Down Arcade/1 Prefabs.md

filename: 1 Prefabs.md


text:
---
slug: biology-major-earns-coveted-internship-with-public-media
title: "Biology major earns coveted internship with public media"
date: January 01 2020
---

  As a child, Grace Singer explored tide pools on the Monterey Peninsula. She
  was hooked.

  That led to degrees in biology and chemistry at a local community college, an
  internship at Hopkins Marine Station and volunteer work at the Monterey Bay
  Aquarium. Her goal is to pursue a career in science communication.

  With the help of generous donors, Singer is getting a head start on that
  career with a summer internship at KQED in San Francisco.

  The junior biology major is the winner of the Professor and Mrs. Allen Fuhs
  science communication scholarship and internship, each worth $10,000.

  This summer, Singer is working for KQED Science, which provides science and
  environment coverage from the Bay Area and beyond by the flagship Northern
  California PBS and NPR affiliates.

  “I’ll get a chance to participate in as many projects as I can handle,” she
  said. She’s primarily working for the video web series, Deep Look. “My
  responsibilities include researching new ideas, consulting with research
  specialists, editing, writing and co-producing.” And she’s writing a blog
  for the KQED Science website.

  Her first
  story
  explains how researchers from the California Academy of Sciences discovered
  more than 100 new species of marine animals off the coast of the Philippines.

  Singer applied for the scholarship to help with expenses for the international
  study program in Costa Rica she’ll attend in the fall.

  “I’ve always loved writing, editing and filmmaking, so it seemed like the
  perfect scholarship for my skill set,” she said. “I love working with others
  to spread awareness where it matters, and being privy to the latest scientific
  breakthroughs excites and motivates me.”

  She plans to apply to the science writing certificate program at UC Santa Cruz
  after she graduates.

  About the donor: Allen Fuhs, Ph.D., is a distinguished professor emeritus
    at the Naval Postgraduate School in Monterey, where he chaired the
    mechanical engineering and aeronautics departments. Among his achievements,
    Dr. Fuhs was an Honorary Fellow of the American Institute of Aeronautics and
    Astronautics, one of the most prestigious honors in aerospace.

Published June 11, 2015

repository: csumb-archives/news-gatsby

repo_name: csumb-archives/news-gatsby


text:
---
layout: post
title:      "Data Structures and Nesting"
date:       2017-10-31 11:11:49 +0000
permalink:  data_structures_and_nesting
---

Understanding and becoming familiar with Ruby Data Structures can be daunting. It can seem especially difficult if you have never encountered the syntax and its length. When initially looking at deeply nested Data Structures, I had tough time distinguishing where the data began or ended and how to traverse them. However, just like with anything in coding and in life, the more you use it the better you understand it and become more efficient at it.

In Ruby:

> "Arrays are ordered, integer-indexed collections of any object." -
[https://ruby-doc.org/core-2.2.0/Array.html](http://)

For our purposes the keyword we should focus on in the array definition is *collections of any **object***. Object is key here because it represents a broad terminology allowing us to not only store primitive types such as integers or strings but also our custom types, such as class instances and even other arrays and *hashes*.

Examples of Arrays:
```
array = [1, 2, 3]
array_1 = ["Hello", 1, 3]
```
We can see that in Ruby arrays do not need to be type specific. We can put together a collection of different objects.

> "A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are like Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type." - [https://ruby-doc.org/core-2.4.2/Hash.html](http://)

Hashes can be thought of as dictionaries. Structure of a dictionary consists of a key and then following is the value. Key in a dictionary, being a unique word, and value its definition. In the same sense hashes allow us to create our own dictionary structures where we specify what the unique key and the corresponding value will be. This is referred to as *key value pairs*.

Examples of Hashes:
```
hash = {name: "Tim", hobby: "fishing", age: 23}
```

In the below example, is where I think Ruby Data Structures can become a little bit tricky to understand. We can have an array of hashes likewise we are allowed to have a hash that points to an array.
Example of a hash with an array as its value

```
people = { teachers: => ["Manny", "Marty" , "Moe"], students: => ["Tim", "Jon", "Grant"] }
```

If we needed to retrieve "Jon" from this hash we would need to specify the name of the hash and then the key and then the index of the value we want to retrieve:
```
people[:students][0]
#Tim
```

Here we have a key of the hash called *teachers* that points to a value pair that is an array consisting of string objects. There is nothing stopping us from creating an array of other arrays. Likewise, we can create a hash where its key is pointing to another hash:

Example of a hash nested inside another hash
```
schools = { :Greenbriar => {address:  "123 Main St", email<EMAIL_ADDRESS>students: ["Jerry", "Gary" ,"Randy"] }
```

":Greenbriar" is the key and its value is another hash. There is no limit as to how deeply nested our Data Structures can go.

If we needed to retrieve student "Gary" we would do:
```
schools[:Greenbriar][:students][1]
#"Gary"
```

In the above example we have a hash called "schools" which has a key called "Greenbriar". The key "Greenbriar" points to a value of yet another hash. We can also see that this inner hash has keys for "address", "email" but it also has a key for "students" which points to an array as its value.

When working with Ruby deeply nested Data Structures, we can see it can easily get confusing and complicated. What makes it easier for me is "bubbling up". Basically moving up the chain from destination to the beginning. In the last example of the "schools" hash we could do following and find our nested piece of information.

Target is to retrieve "Gary". "Gary" is inside of an array. it is at index 1. The name of the array is students. *Noting students[1]*, then as we move up the chain, we see that students is a key inside the ":Greenbriar" hash. *Noting [:Greenbriar][:students][1].* Then in the last layer we see that ":Greenbriar" is the first key in the hash called schools thus our final statement would be schools[:Greenbriar][:students][1]. This is my personal flavor of tackling deeply Data Structures and what has helped expedite my understanding.

extension: markdown


text:
---
layout: portfolio
title:  "Series Addict"
date:   2014-10-10 14:16:03
categories: android app
thumb: images/series-addict-thumb.png
description: Manage and track your favorite TV shows.
link: https://play.google.com/store/apps/details?id=com.alamkanak.seriesaddict
link-title: Get it from Google Play
project_date: October 2014
client: Unsolicited
skills: Android, UI Design, Java, XML
category_slugs: android
---

![Series Addict]({{ site.baseurl }}/images/series-addict.png)

Series Addict keeps you up to date about new and upcoming episodes. Mark the episodes as watched when you watch them, get notified when episodes air, view TV schedules of your favorite shows, add home screen widgets to remain up to date about new episodes all the time and do a lot more with Series Addict. Never miss a show from now on.

Features
---
* Mark episodes as watched
* View TV schedules of your favorite shows in calendar
* Share what you’re watching with your friends
* Add widgets to your home screen
* Get notified when new episodes air


text:
---
title: "Create a promotion application blueprint for load testing"
date: 2020-10-15T18:47:14+03:00
weight: 36
draft: false
---

* Your next task will be to provide application environments for the load testing QA certification.
* In this case, you will increase the number of VMs for the application UI tier from 1 to 3. The ELB load balancer will be automatically configured

![46_page](/images/module1/46_page.png)

Edit promotions-manager-all-aws-loadtest.yaml (in the /blueprint directory in your Git repo) and uncomment the "#instances: 3 for the UI tier" line

![46_page](/images/module1/48_page.png)

 Commit your changes

 ![46_page](/images/module1/49_page.png)

repository: Shnitselon/aws-modernization-with-quali

branch_name: refs/heads/main

gha_license_id: NOASSERTION

repo_name: Shnitselon/aws-modernization-with-quali


text:
DAFGU Migration Status
======================

This is a small menu bar application that can change its icon into one of four states:

* kDMStatusUnknown (0) - Translucent gray
* kDMStatusOK (1)      - Happy green
* kDMStatusError (2)   - Angry red
* kDMStatusActive (3)  - Pulsating orange

If you click on it it'll also show a status message. We use it to display the status of the last backup.

Compiling
---------

The project is configured to build a universal app for 10.5+ with Xcode 3.2. If you change to a newer SDK you can also build it on Xcode 4, but then you'll lose support for 10.5 and PPC.

Usage
-----

The app opens a socket under /tmp and waits for messages in the form of a plist encoded NSDictionary, with the following keys:

* DAFGUMigrationStatus (NSInteger, 0-3)
* DAFGUMigrationMessage (NSString, max 100 chars)

Sample code to set the status can be found in test/socketclient.py:

    # ./test/socketclient.py 3 'Look at me go!'
    Sending message to /tmp/se.gu.it.dafgu_migration_status.4079eab9040e62e4

Version History
---------------

* 1.2
    * Changed IPC to unix domain sockets, as shared objects don't work across different bootstrap contexts.
    * Added smooth image scaling for 10.5.
* 1.1
    * Changed IPC to shared objects, as watching plists uses too much CPU.
    * Added animation for active status.
* 1.0
    * Initial release.

License
-------

    Copyright 2012 Per Olofsson, University of Gothenburg

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

repository: MagerValp/DAFGU-Migration-Status

repo_name: MagerValp/DAFGU-Migration-Status


text:
# Facebook-Likes-Model
Why is your Facebook Data so valuable? A method to predict humans traits through Facebook Likes.
As the election time is approaching we will see how and why our Facebook Data is so valuable to advertisers, politicians. Facebook is the world's largest social network platform with over 2.5 billion active users. It processes data at a scale never seen before, the highly sophisticated Facebook A.I algorithms curate, categorize, and predict associations between data in an almost human way.

Live Demo: https://fblikesmodel.herokuapp.com/

# Paper
This repo is the reproduction of the paper: https://www.pnas.org/content/pnas/110/15/5802.full.pdf

# Colab
https://colab.research.google.com/drive/1k75ODwkhEnXirVDKzyyBImPqNGISqjs6?usp=sharing

# Medium
https://towardsdatascience.com/why-is-your-facebook-data-so-valuable-a-method-to-predict-humans-traits-through-facebook-likes-e1ae036e80fb

repository: aaditkapoor/Facebook-Likes-Model

repo_name: aaditkapoor/Facebook-Likes-Model


text:
# `?` in `main` and tests

![Minimum Rust version: 1.26](https://img.shields.io/badge/Minimum%20Rust%20Version-1.26-brightgreen.svg)

Rust's error handling revolves around returning `Result<T, E>` and using `?`
to propagate errors. For those who write many small programs and, hopefully,
many tests, one common paper cut has been mixing entry points such as `main`
and `#[test]`s with error handling.

As an example, you might have tried to write:

```rust,ignore
use std::fs::File;

fn main() {
    let f = File::open("bar.txt")?;
}
```

Since `?` works by propagating the `Result` with an early return to the
enclosing function, the snippet above does not work, and results today
in the following error:

```rust,ignore
error[E0277]: the `?` operator can only be used in a function that returns `Result`
              or `Option` (or another type that implements `std::ops::Try`)
 --> src/main.rs:5:13
  |
5 |     let f = File::open("bar.txt")?;
  |             ^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
  |
  = help: the trait `std::ops::Try` is not implemented for `()`
  = note: required by `std::ops::Try::from_error`
```

To solve this problem in Rust 2015, you might have written something like:

```rust
// Rust 2015

# use std::process;
# use std::error::Error;

fn run() -> Result<(), Box<Error>> {
    // real logic..
    Ok(())
}

fn main() {
    if let Err(e) = run() {
        println!("Application error: {}", e);
        process::exit(1);
    }
}
```

However, in this case, the `run` function has all the interesting logic and
`main` is just boilerplate. The problem is even worse for `#[test]`s, since
there tend to be a lot more of them.

In Rust 2018 you can instead let your `#[test]`s and `main` functions return
a `Result`:

```rust,no_run
// Rust 2018

use std::fs::File;

fn main() -> Result<(), std::io::Error> {
    let f = File::open("bar.txt")?;

    Ok(())
}
```

In this case, if say the file doesn't exist and there is an `Err(err)` somewhere,
then `main` will exit with an error code (not `0`) and print out a `Debug`
representation of `err`. Note that this will always print out the `Debug` representation.
If you would like to, for example, print out the `Display` representation of `err`,
you will still have to do what you would in Rust 2015.

## More details

Getting `-> Result<..>` to work in the context of `main` and `#[test]`s is not
magic. It is all backed up by a `Termination` trait which all valid return
types of `main` and testing functions must implement. The trait is defined as:

```rust
pub trait Termination {
    fn report(self) -> i32;
}
```

When setting up the entry point for your application, the compiler will use this
trait and call `.report()` on the `Result` of the `main` function you have written.

Two simplified example implementations of this trait for `Result` and `()` are:

```rust
# #![feature(process_exitcode_placeholder, termination_trait_lib)]
# use std::process::ExitCode;
# use std::fmt;
#
# pub trait Termination { fn report(self) -> i32; }

impl Termination for () {
    fn report(self) -> i32 {
        # use std::process::Termination;
        ExitCode::SUCCESS.report()
    }
}

impl<E: fmt::Debug> Termination for Result<(), E> {
    fn report(self) -> i32 {
        match self {
            Ok(()) => ().report(),
            Err(err) => {
                eprintln!("Error: {:?}", err);
                # use std::process::Termination;
                ExitCode::FAILURE.report()
            }
        }
    }
}
```

As you can see in the case of `()`, a success code is simply returned.
In the case of `Result`, the success case delegates to the implementation for
`()` but prints out an error message and a failure exit code on `Err(..)`.

To learn more about the finer details, consult either [the tracking issue](https://github.com/rust-lang/rust/issues/43301) or [the RFC](https://github.com/rust-lang/rfcs/blob/master/text/1937-ques-in-main.md).


text:
---
layout: post
title: "Algorithm: Tree structure"
date: 2021-02-25
categories:
  - Algo
tags:
  - tree
author_profile: true
read_time: true
comments: true
share: true
related: true
popular: true
toc: true
toc_sticky: true
toc_label: 목차
article_tag1: tree traversing
article_tag2: data structure
article_section: Algo
meta_keywords: algo, tree traversing, data structure
published: true
---

# Tree structure

- Basic keywords

Name| Exp|
-|-|
Root node| Node w/o parent|
Leaf node| Node w/o child|
Size| # of every node in tree|
Depth| Distance from root|
Height| Max depth|
Degree| # of edges from parent to child|

In this post, I will refer Left leaf(child) as __L__ , Root as __Root__, Right leaf as __R__.

- Tree traversal
  - Pre-order: __Root__ -> __L__ -> __R__
  - In-order: __L__ -> __Root__ -> __R__
  - Post-order: __R__ -> __Root__ -> __L__

  ex)

<img src="/assets/images/algo/algo001.PNG" width="30%" height="60%">

- Binary Search Tree
  - Tree data structure for efficient binary search
  - Value: __L__  < __Root__ < __R__


text:
# LatexGU

This is a repository to share the script of the lecture "Applied functional analysis", written by Tim Keil.

Just click here: [Script](https://github.com/TiKeil/LatexGU/raw/master/AF.pdf)

For questions and mistakes<EMAIL_ADDRESS>

repository: TiKeil/LatexGU

repo_name: TiKeil/LatexGU


text:
# Syntax
Below is an exhaustive list of SugarScript's syntax.

# Variables and Types

```
# integers
let a: integer        # use `let` to define a variable
let a: integer = 1    # you can also give it a value
let a = 1             # if you do, then the type can be guessed
a = 2                 # you can then re-assign it's value
b = 3                 # ERROR, you need to define before you assign

# floats
let PI = 3.14
let number: float
number = PI / 2

# booleans - aliases for 1 and 0
let a = true    # same as `let a = 1`
a = yes         # same as above
a = on          # same as above
a = false       # same as `a = 0`
a = no          # same as above
a = off         # same as above

# strings
let name = 'Mike'                # single-quoted
let foo = "Bar"                  # double-quoted
let greeting = "Hello, #{name}!" # interpolation, only works with double-quoted strings
```

# Binary Operations

```
# booleans
result = true and true
result = true or false

# comparison
result = some_variable is "hello"     # equality comparison
result = some_variable == "hello"     # same as above
result = some_variable isnt "hello"   # not equal comparison
result = some_variable != "hello"     # same as above
result = other_variable > 1           # you can use `>`, `>=`, `<` and `<=` as usual

# arithmetics
result = 2 + 2
result = 2 - 2
result = 2 * 2
result = 2 / 2
result = 2 % 2  # modulo
result = 2 ** 2 # exponentiation, TODO
```

# If Statement

```
if some_flag is on
  do_something()
elif a == 1
  do_something_else()
else
  another_function()

# one-liner
if true then foo()
unless is_jumping() then do_something()
```

# While Statement

```
while true
  if foo() then break # exit loop
  if bar() then continue # skip this iteration
  do_something()
```

# For Statement

```
for i = 1 to 100 step 2
  print("#{i}")

# without step
for i = 1 to 100
  do_something_with(i)

# one-liner
for i = i 1o 100 do something_with(i)
```

# For..In Statement

```
for num in [1, 2, 3]
  print("#{num}")

# one-liner
for num in [1, 2, 3] do print("#{num}")
```

# Functions

```
def greet(name: string, age: integer = 18): string
  return "Hello #{name}, you are #{age} years old"

greet("Mike")
```

# Types

```
type Person(name: string, age: integer)

# or multiline
type Person
  name: string
  age: integer

let p: Person
p.name = "Mike"
p.age = 123

# short-syntax
let p = { name: "Mike", age: 123 }: Person
```

# Arrays

```
let empty = []: integer # empty array of integers
let a = [1, 2, 3]       # non-empty array of integers
let b = [1, "foo"]      # ERROR, all elements must be of the same type
foo([1, 2, 3])          # it can be passed to a function too, it's just an expression

# nested arrays work too, they must be consistent with the types though
let a = [[1], [2, 3], [4]]      # OK
let a = [[1], []: integer, [4]] # OK
let a = [[1], ["hi"], [4]]      # ERROR
let a = [[1], 4]                # ERROR

# manipulation
array_insert(a, 2)
array_insert_at(a, 3, 0) # array, value, index
array_delete(a, 0)

# IMPORTANT: On array length
# For the array `[1, 2, 3]`, Tier 1 returns `2` for length. SugarScript will
# return `3` instead, normalizing the language with the rest of the world:
let len = array_length([1, 2, 3]) # len will now equal `3`
```

# Lambdas
Lambdas are also known as "Anonymous Functions", that is, functions without a
name. They work mostly like regular functions.

```
let greeter = (name: string): string ->
  return "Hello, #{name}!"

call(greeter): string
```

Note that the syntax for calling lambdas is different than regular function
calls. Lambdas are called using `call` and need an additional _type hint_. This
is because `greeter` is just an integer, so to type-check it, the compiler needs
a little help.

An alternative syntax for `call` is `->`:

```
call(greeter)
# same as
->(greeter)
```

You can use `call` and `->` the same way you'd use regular function calls.
Lambdas can also take default values:

```
let greeter = (name: string = 'Federico'): string ->
  return "Hello, #{name}!"

let greeting = call(greeter): string
```

Because lambdas are just integers, you can treat it just like any other integer.
You can re-assign it:

```
let get_name = (): string -> 'Federico'
let demo = 22
# ... some more code here ...
# because `get_name` is an integer, we can assign it to demo
demo = name
# we can even call demo now
let name = call(demo): string # name is now 'Federico'
```

Pass it to a function:

```
let get_name = (): string -> 'Federico'

def example(get_name: integer)
  print("Hello #{call(get_name): string}")

example(get_name)
```

And return it from a function:

```
let get_name = (): string -> 'Federico'

def identity(lambda: integer): integer
  return lambda

let itself = identity(get_name)
let name = ->(itself): string
```

It can also be defined inside a function, if needed:

```
def get_name_getter(): integer
  return (): string -> 'Federico'

let name_getter = get_name_getter()
let name = call(name_getter): string
```

## Inline-Lambdas
You can also define lambdas in a single line. These lambdas always return a
value, which is the result of the expression:

```
let greeter = (name: string): string -> "Hello, #{name}!"
```

These lambdas can only take a single expression. For more lines, you need to
swap to a regular lambda, and use a `return` statement.

These lambdas are particularly useful for passing them to other functions:

```
def greet_manager(greeter: integer, name: string): string
  return call(greeter, "Mike"): string

let result = greet_manager((name: string): string -> "Hello #{name}!", "Mike")
```

In the example above, inside `greet_manager`, `greeter` is defined simply as
integer. It is then called using the special syntax.

Note that the type checker doesn't know what parameters `greeter` expects, so
it cannot check those for you.

## Limitations of Lambdas

* Because of array limitations in Tier 1, they can only receive arguments _by value_
* The type-checker can't validate arguments are valid when calling a lambda
* They are slower than regular functions, so when possible, prefer using a regular function

# Unions
Unions represent a value that can be of one of many possible types:

```
type Rectangle(x: float, y: float, width: float, height: float)
type Circle(x: float, y: float, radius: float)
type Shape(Rectangle | Circle)

# a shape can hold either a Rectangle, or a Circle
let shape: Shape
shape = { x: 100, y: 100, width: 200, height: 200 }: Rectangle
shape = { x: 100, y: 100, radius: 100 }: Circle

# to access unions, you must use the `with` statement
# it's mandatory to provide an `else` branch, as unions
# can be initialized without a type
def area(shape: Shape): float
  with shape
    when rect: Rectangle
      return rect.width * rect.height
    when circle: Circle
      return 3.14 * circle.radius * circle.radius
    else
      return 0

# a rectangle's area
shape = { x: 100, y: 100, width: 200, height: 200 }: Rectangle
let result = area(shape)

# a circle's area
shape = { x: 100, y: 100, radius: 100 }: Circle
let result = area(shape)

# trying to access a property directly will raise an error
shape.x # ERROR

# when types share common properties, you can group them as such:
type Car(wheels: integer)
type Bike(wheels: integer)
type Vehicle(Car | Bike)

let vehicle: Vehicle
vehicle = { wheels: 2 }: Bike

with vehicle
  when v: (Bike | Car)
    print("I have #{v.wheels} wheels")
  else
    print("I haven't been initialized yet")
```

# Require
Require is simple, it requires one file, relative to the current file:

```
# ./foo.ss
require 'bar' # this will require the file `./bar.ss`
```

## Remote Require
Require can work with URLs, too:

```
require 'https://github.com/.../my-file.ss'
```

The code above will download the `my-file.ss` file, and if that file has other
requires, it will recursively download them, and cache them for future use.

# Numerical Bases
You can use binary, octal and hexadecimal bases as such:

```
let binary = 0b1001
let octal = 0c1732
let hex = 0xFF1A9
```

# Primitive Functions
Because SugarScript is purely functional, it needs to add new functions to replace
existing oop-like calls in Tier 1. Those functions are:

 * `array_length(arr): integer`
 * `array_insert(arr, value)`
 * `array_insert_at(arr, value, index)`
 * `array_insert_sorted(arr, value)`
 * `array_remove(arr)`
 * `array_remove_at(arr, index)`
 * `array_sort(arr)`
 * `array_find(arr, value): integer`
 * `array_save(arr, filename)`
 * `array_load(arr, filename)`
 * `to_json(arr_or_udt): string`
 * `from_json(arr_or_udt, json_string)`

__IMPORTANT__ `array_length` will behave like it does in most programming
languages. That is, it will report the actual numbers of elements inside the
array. So for `array_lengt([1, 2, 3])`, it will return 3, unlike Tier 1, that
would return `2`.

# List Comprehensions

```
let pairs = [i for i in [0, 1, 2, 3, 4] when i % 2 is 0]
let doubles = [i * 2 for i in [0, 1, 2, 3, 4]]
```

# Plugins

```
import_plugin SomePlugin as p
p::someMethod(): integer
```

# Halt

```
halt "Something went extremely wrong, program execution stopped"
```

repository: Qugurun/sugarscript

repo_name: Qugurun/sugarscript


text:
---
description: Manage your full node
---

## Commands

### Accounts

List node accounts

```
USAGE
  $ celocli node:accounts
```

_See code: [packages/cli/src/commands/node/accounts.ts](https://github.com/celo-org/celo-monorepo/tree/master/packages/cli/src/commands/node/accounts.ts)_

repository: ashishb/celo-monorepo

gha_language: TypeScript

repo_name: ashishb/celo-monorepo


text:
# Confluent Kafka Mixin

This Mixin was designed to work with the Confluent Cloud metrics API. It contains a dashboard that monitors all metrics available on the API at the time of creation, giving the user a fine grained control on which metrics are seen, selecting the cluster, topic, partition and principalID wanted. This dashboard was based on [this community dashboard](https://github.com/Dabz/ccloudexporter/blob/master/grafana/ccloud-exporter.json).

To use it, you need to have `mixtool` and `jsonnetfmt` installed. If you have a working Go development environment, it's easiest to run the following:

```bash
$ go get github.com/monitoring-mixins/mixtool/cmd/mixtool
$ go get github.com/google/go-jsonnet/cmd/jsonnetfmt
```

You can then build a directory `dashboard_out` with the JSON dashboard files for Grafana:

```bash
$ make build
```

For more advanced uses of mixins, see [Prometheus Monitoring Mixins docs](https://github.com/monitoring-mixins/docs).

repository: grafana/jsonnet-libs

gha_language: Jsonnet

repo_name: grafana/jsonnet-libs


text:
# Hydrocotyle burmanica subsp. craibii (H.Eichler) C.Y.Wu & F.T.Pu SUBSPECIES

#### Status
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
null

### Remarks
null

repository: mdoering/backbone

path: /life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Hydrocotyle/Hydrocotyle hookeri/ Syn. Hydrocotyle burmanica craibii/README.md

repo_name: mdoering/backbone


text:
[![Build Status](https://travis-ci.org/jbguillois/nagios-teams-notify.svg?branch=master)](https://travis-ci.org/jbguillois/nagios-teams-notify)

# nagios-teams-notify
Send Nagios/Shinken alerts to a Microsoft O365 Teams channel.

## Overview

This script can send Nagios/Shinken alerts to a Microsoft O365 Teams channel.

By sending alerts to Teams, we can simplify addition and removal alert recipients, allow for self-service subscription and push preferences, and have conversations based around the alerts as they occur.

## Installation

You can should install python dependencies listed in `requirements.txt` (you might use `pip` to do so) and copy `notifyTeams.py` where it can be executed by the Nagios/Shinken user (`/usr/lib` could be a good option). Make sure the script is  executable with `chmod +x notifyTeams.py`.
You can test this script by running the included unit tests (`python -m unittest -v testNotifyTeams.py`)

## Configuration

### Create the Webhook

From [Using Office 365 Connectors: Teams](https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/connectors/connectors-using#setting-up-a-custom-incoming-webhook):

1. In Microsoft Teams, choose More options (⋯) next to the channel name and then choose Connectors.
2. Scroll through the list of Connectors to Incoming Webhook, and choose Add.
3. Enter a name for the webhook, upload an image to associate with data from the webhook, and choose Create.
4. Copy the webhook to the clipboard and save it. You'll need the webhook URL for sending information to Microsoft Teams.
5. Choose Done.

### Configure Nagios/Shinken

Create a command object in the Nagios/Shinken configuration and replace <yourshinkenurl> with your Shinken URL (http://shinkenhost/).

```
define command {
    command_name notify_teams
    command_line /path/to/script/notifyTeams.py $_CONTACTWEBHOOKURL$ <youshinkenurl> $NOTIFICATIONTYPE$ $HOSTALIAS$ $HOSTSTATE$ "$HOSTDURATION$" "$SERVICEDESC$" "$SERVICESTATE$" "$SERVICEDURATION$" --msg "$SERVICEOUTPUT$ - $LONGSERVICEOUTPUT$"
}
```
Create a contact object with the custom variable macro _WEBHOOK set to the URL from the Teams channel connector. This variable is used when running the command above.

```
define contact {
    contact_name    example-team
    alias           Example Team
    host_notifications_enabled  1
    service_notifications_enabled   1
    host_notification_period    24x7
    service_notification_period 24x7
    host_notification_options   d,u,r,f,s
    service_notification_options    w,u,c,r,f
    host_notification_commands  notify_teams
    service_notification_commands   notify_teams
    _WEBHOOKURL <yourwebhookURL>
}
```

Then add the contact to an existing object or contact group and reload your configuration.

Create additional contacts with their own `_WEBHOOKURL` custom variable macro for each Teams channel needing notifications.

repository: jbguillois/nagios-teams-notify

repo_name: jbguillois/nagios-teams-notify


text:
# anti-sybil-token-drop
This repo uses 🏗 scaffold-eth - 🔏 sign in with web3 example

## Concept
Airdrops of tokens and nft are common. However, these airdrops are often conducted by individuals with multiple addresses, and are often bought up or minted by a small number of participants. As a countermeasure, there is a launch pad that distributes tokens according to the amount of tokens locked in advance, but this also favors a small number of whales. The method I propose here is to use Proofof humanity so that only accounts registered as individuals can be minted or claimed only once. We also transfer tokens from the backend for participants with small amounts who are hesitant to pay for gas.

## How it works
> Ask users to sign a message with their web3 wallet and recover it in a backend service

> If the user has not claimed yet, we will send the token to them.

## Setup
---

```bash
git clone https://github.com/austintgriffith/scaffold-eth.git anti-sybil-token-drop

cd anti-sybil-token-drop

git checkout anti-sybil-token-drop
```

```bash

yarn install

```

```bash
yarn chain
```

```bash
yarn deploy
```

```bash

yarn start

```

> start the backend service that listens for and verifies signatures:
get a private key which is provided `yarn chain` and set `PK`
```bash

PK=<Private Key> yarn backend

```

📝 Edit your frontend `App.jsx` in `packages/react-app/src`

📱 Open http://localhost:3000 to see the app

---

> Connect a web3 wallet:

![image](https://user-images.githubusercontent.com/2653167/116907182-794c0480-abfe-11eb-9b63-935d8848b613.png)

---

> Sign a message to prove you own the address:

![image](https://user-images.githubusercontent.com/2653167/116907431-c6c87180-abfe-11eb-9382-e885a39c0579.png)

![image](https://user-images.githubusercontent.com/2653167/116907476-dc3d9b80-abfe-11eb-9fb6-f0c2af0f40a1.png)

---

> A backend server verifies sigatures:

![image](https://user-images.githubusercontent.com/2653167/116907561-fb3c2d80-abfe-11eb-9b09-f1c81265040b.png)

---

> The frontend can then react to the correct signature:

![image](https://user-images.githubusercontent.com/2653167/116907586-02633b80-abff-11eb-9ab4-3c5a9a16d64d.png)

---

## 💬 Support Chat

Join the telegram [support chat 💬](https://t.me/joinchat/KByvmRe5wkR-8F_zz6AjpA)  to ask questions and find others building with 🏗 scaffold-eth!

---

===================================================== [⏫ back to the top ⏫](https://github.com/austintgriffith/scaffold-eth#-scaffold-eth)

---


text:
---
title: "Bitcoin Seed FAQ"
---

## Index

1) [**The Basics**](#1-The-Basics)
	- [Introduction](#Introduction)
	- [Terminology](#Terminology)
	- [What is a HD Wallet?](#What-is-a-HD-Wallet)
2) [**Creating your seed**](#2-Creating-your-seed)
	- [Where should I physically be when I backup my seed?](#Where-should-I-physically-be-when-I-backup-my-seed)
	- [All seeds are not created equal](#All-seeds-are-not-created-equal)
	- [Does the order of the words matter?](#Does-the-order-of-the-words-matter)
	- [How do I get my seed?](#How-do-I-get-my-seed)
	- [Should I check my seed?](#Should-I-check-my-seed)
3) [**Storing your Seed**](#3-Storing-your-Seed)
	- [Why should I bother storing my seed, I only have a small amount of bitcoin?](#Why-should-I-bother-storing-my-seed-I-only-have-a-small-amount-of-bitcoin)
	- [Should I have multiple (redundant) backups?](#should-i-have-multiple-redundant-backups-of-my-seed)
	- [Paper Backups](#paper-backups)
	- [Metal Backups](#metal-backups)
	- [How can I store my seed](#How-can-I-store-my-seed)
	- [Can I 'encrypt' my seed so that all is not lost if someone finds my mnemonic?](#Can-I-encrypt-my-seed-so-that-all-is-not-lost-if-someone-finds-my-mnemonic)
	- [Passphrases](#1-use-a-passphrase-alongside-your-mnemonic-seed-following-bip39)
	- [Encrypt Seed Words](#encrypt-the-plaintext-seed-words)
	- [Should I split my mnemonic in two (short version)?](#should-i-split-my-mnemonic-in-two-short-version)
	- [Should I split my mnemonic in two (long version)?](#should-i-split-my-mnemonic-in-two-long-version)
	- [Should I split my seed ABC into AB|BC|CA?](#should-i-split-my-seed-abc-into-abbcca)

4) [**Using your Seed**](#4-Using-your-Seed)
	- [Can I recover my bitcoin without my seed?](#Can-I-recover-my-bitcoin-without-my-seed)
	- [Can I recover my bitcoin without my passphrase?](#Can-I-recover-my-bitcoin-without-my-passphrase)
	- [I have forgotten my passphrase, what now?](#I-have-forgotten-my-passphrase-what-now)
	- [How should I recover bitcoin using my seed?](#How-should-I-recover-bitcoin-using-my-seed)
	- [What is the Derivation Path?](#What-is-the-Derivation-Path)
	- [How often should I check backups?](#how-often-should-i-check-backups)

# 1) The Basics

### Introduction

Great - you have decided to control your bitcoin directly instead of using a custodial service like an exchange. This is a very wise move - exchanges fall into only two categories; those which have been hacked and those which will be hacked.

 You should take time to read this FAQ in order to understand the common errors & mistakes, and to learn the best practice in seed management. Be aware that this a general guideline. Every solution for storing your bitcoin seed will be a tradeoff between security and usability, and the level of security needed or wanted will vary from person to person, as will the threats you are trying to secure yourself against.

### Terminology

When it comes to bitcoin seed descriptions, words are often confused and used interchangeably. It is important that we speak a common language, so let me define what I mean by each of these words.

| Word | Definition | Other Names |
| ---- | ---- | ---- |
| [**Private Key**](https://en.bitcoin.it/wiki/Private_key) | A secret 256 bit number that you use to spend bitcoin | Secret Key |
| [**Seed**](https://en.bitcoin.it/wiki/Seed_phrase) | A 256 bit number which can be used to generate a bitcoin private key. |  |
| **Mnemonic Seed** | The seed encoded in the form of a list of words in a specific order.  | Mnemonic / Seed Phrase / Seed Words |
| **Non-Extended Mnemonic** | 12/24 Words (Just the Mnemonic) | Mnemonic  |
| **Extended Mnemonic** | Mnemonic (12/24 words) + Passphrase | Extended Seed |
| **Backup** | A complete set of information from which your bitcoin can be recovered  | |
| **Encrypted Backup** | Backup encrypted with a password (not to be confused with a passphrase) | |

### What is a HD Wallet?

In practice, most bitcoin wallets are 'HD' (Hierarchical Deterministic) wallets - This means that a single bitcoin private key is used to generate as many key pairs as is required. This makes it easy for the user to use a new address each time they receive bitcoin, which is how bitcoin is designed to be used.

With a HD wallet the bitcoin private key (which is derived from the seed) is combined with a 'chain code' to generate what is referred  to as a 'master extended key'. For more details see [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki).

Typically when backing up a wallet you are presented with the mnemonic seed - a series of either 12 or 24 words from [this list](https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt) - it is an encoded version of your seed made to be easy to read and transcribe. The encoding method is detailed in [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki#), but effectively each word on the wordlist corresponds with a number, and thus your 12 or 24 word mnemonic seed is simply an easy to write representation of a large number (your seed).

Many wallets carelessly label the mnemonic seed as just the 'seed' - take care, the mnemonic seed can be extended with an additional word or sentence (a passphrase), without which you cannot decode the actual seed (a 256 bit number) and thus, you cannot recover your bitcoin.

##### Important Note:

Anyone with access to your seed can spend your coins. As such it is imperative that you store copies of your seed securely. The next section explains how to do just that.

# 2) Creating your Seed

### Where should I physically be when I backup my seed?

Remember that if anyone sees your seed it is potentially compromised, and should be treated as such.
For this reason make sure that you backup your seed somewhere that is private and that has no cameras/CCTV.
- Don't read your seed aloud as someone could hear it.
- Don't type it into a computer
- Don't take a picture / screenshot

### All seeds are not created equal

Suppose you have a computer riddled with malware and viruses and you download some bitcoin wallet software and view the seed (or more likely the mnemonic seed). This seed is likely insecure. The viruses/malware may be taking screenshots of your computer at regular intervals and sending this data to the creator of the virus/malware.
If you can see your seed on screen, then potentially so can the hacker.

For this reason, with non-trivial amounts of bitcoin it is crucial that you carefully control the environment in which the seed is generated. The easiest way for non-technical people to do this is to buy a 'Hardware Wallet'. These devices store all the 'secret information' required to access your bitcoin on the dedicated hardware device so that it doesn't matter if your computer has viruses/malware.

That said, some hardware wallets are better than others so make sure that you never enter your seed into your computer - only enter it into the device itself.

Another option is to generate a seed using a clean computer which is not connected to the Internet.

### Does the order of the words matter?
Yes! The order of the words in a mnemonic seed does matter. You must store your mnemonic seed in such a way that the order of the words is clear and unambiguous. Remember - the mnemonic seed is simply an encoding of the seed which is a large number, if you get the order wrong then you will decode a different number.

### How do I get my seed?

This will depend on the bitcoin wallet that you are using. Most have a 'backup seed' option visible in the settings menu which can be used at any time, though some only allow seed backups when the wallet is initialised. Again, what you are backing up is typically the mnemonic seed. If you use an extended mnemonic (i.e. A 12/24 word mnemonic seed + a passphrase) you MUST have access to the passphrase to recover your bitcoin. For this reason it is very important to backup your passphrase in addition to your seed - though you should not store them in the same place.

It is important to note that it is generally insecure to create your own seed as humans are not good at creating truly random information.

### Should I check my seed?

You should definitely check your backup as part of your process for backing up. Failure to do so could lead to you losing your bitcoin - don't risk it. Part of checking the backup is checking that you have correctly recorded your seed, though this is not the whole process. You should additionally check that you know the derivation path and the passphrase (if you used one).

The value of bitcoin could increase substantially and you may one day regret not backing up your seed. You should **always** back up your seed. It is good practice to regularly review your seed management and consider how effective your chosen solution is.

### Should I have multiple (redundant) backups of my seed?

Yes. For the reasons explained below you should have multiple redundant backups of your seed.

### Paper Backups

If you do decide to use a paper backup:
- Use waterproof ink & paper
- Write on a hard surface so you don't indent the paper below
- You can increase the durability of your paper backup by laminating it
- Consider labelling your seed discreetly. Something labelled 'BITCOIN SEED' is more likely to be swept (stolen) than if you label it 'COOKIE RECIPE', though it may be easy to forget that you did this.
- Laminate the paper

Learn More: [Here](https://www.quora.com/How-do-I-maintain-a-paper-notebook-that-can-remain-for-years) and [Here](https://www.quora.com/If-I-write-with-a-pencil-on-my-notebook-will-the-writing-last-for-a-long-time-say-50-years-or-will-it-just-fade-away-gradually)

### Metal Backups

There are lots of options available. See Lopp's [initial comparison](https://medium.com/@lopp/metal-bitcoin-seed-storage-stress-test-21f47cf8e6f5) & [more recent comparison](https://youtu.be/zFN__b6ARH4?t=20593).
The [Blockplate 1.0](https://www.blockplate.com/) appears to hold up well to fire / crushing while being easy to use.

### How can I store my seed?
Initially let us consider the case where you store a single unencrypted mnemonic seed (12 or 24 words).

| Method  						   	|Location          				| Digital Theft Resistance 	| Physical Theft Resistance 		| Durability 						|
| ------    					    | ---- 				    		| -------------------------	| ------------------------------|	---------------				|
| Screenshot              | On Phone 					  | Weak							        | Weak													|	Fragile (Deletion) 		|
| Notes App               | On Phone					  | Weak							        | Weak													|	Fragile (Deletion)		|
| Printed Paper Note  		| In Home 					  | Weak							        | Weak													|	Fragile (Fire)	  		|
| Printed Paper Note 			| Bank Deposit Box 		| Weak							        | **Strong** \[3]								|	**Durable**        		|
| Handwritten Paper Note  | In Home 					  | **Strong**				        | Weak													|	Fragile (Fire)	  		|
| Handwritten Paper Note  | Bank Deposit Box 		| **Strong**				        | **Strong** \[3]								|	**Durable**        		|
| Handwritten Paper Note  | Buried Somewhere 		| **Strong**				        | **Strong**										|	Fragile (Water)				|
| Stamped Metal Sheet [1]	| In Home 					  | **Strong**				        | Weak													|	**Durable**        		|
| Stamped Metal Sheet	    | Bank Deposit Box 		| **Strong**				        | **Strong** \[3]								|	**Durable**        		|
| Stamped Metal Sheet	    | Buried Somewhere 		| **Strong**				        | **Strong**										|	**Durable**        		|
| USB (Plaintext)					| In Home 						| **Strong**				        | Weak													|	Fragile (Water/Time)	|
| Memorised	[2]						| Brain								| **Strong**				        | **Strong**										|	Fragile (Time/Injury)	|

*\[1] There are many ways to do this, some are better than others - see Lopp's [initial comparison](https://medium.com/@lopp/metal-bitcoin-seed-storage-stress-test-21f47cf8e6f5) & more recent comparison: [Medium](https://medium.com/@lopp/metal-bitcoin-seed-storage-stress-test-part-ii-d309e04aefeb) / [Youtube](https://youtu.be/zFN__b6ARH4?t=20593)*

*\[2] Often referred  to as a [Brain Wallet](https://en.bitcoin.it/wiki/Brainwallet) - Not to be confused with a wallet where you generate the mnemonic using your brain (i.e. sentence from a book) a Brain Wallet is a wallet with a memorised mnemonic which was generated securely using a source of entropy.*

*\[3] Though likely far safer than your home there have been [reports](https://www.nbclosangeles.com/investigations/Safe-Deposit-Box-Theft-Missing-Items-Wells-Fargo-Bank-564733791.html) of theft of valuables from bank deposit boxes. That said, it is possible to store your seed in a nondescript manner, for example if on paper it could be written on the pages of a book. Provided there is some level of subtlety (don't write BITCOIN SEED at the top of the backup) I imagine a safety deposit box is quite safe from physical theft.*

There are three methods that are both Resistant to Theft and Durable;
- Handwritten Paper Note in a Bank Deposit Box
- Stamped Metal Sheet in a Bank Deposit Box
- Stamped Metal Sheet Buried Somewhere

A Bank Deposit Box is fine, but as discussed in the footnote above it requires some degree of trust in the bank.
Burying is fine, but it requires some degree of luck that someone won't find it / that you will be able to find it.

In either case, theft of the mnemonic seed can occur. Theft of an unencrypted seed is bad for two reasons;
A) The thief can spend your coins at any time. If they replace the seed there is no way for you to know that the seed is compromised.
B) You have lost your backup. You are unable to restore your seed, thus your bitcoin is lost whether or not the thief sweeps the funds.

You can use a watch only wallet to monitor the balance of your addresses, though if you see your funds move it is too late to do anything about it. Furthermore, if someone finds your watch only wallet they know how much bitcoin you have.

If you notice that your seed has been stolen you want to be able to quickly move your funds in-case the thief hasn't figured out what they stole, or they simply haven't swept the funds yet. For this reason is obvious that you should have MULTIPLE seed backups.

But with an **unencrypted seed**, each additional backup is an additional risk, because theft of any one of your backups is enough for a thief to steal your bitcoin. It would be better if you encrypted your seed, so that the thief wouldn't be able to steal your funds if they only have your 12/24 word mnemonic.

### Can I 'encrypt' my seed so that all is not lost if someone finds my mnemonic?

Yes, you can encrypt your seed by one of two methods:

#### 1) Use a passphrase alongside your mnemonic seed following [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki#from-mnemonic-to-seed)

Behind the scenes, many wallets use BIP39 encoding. All seeds encoded using BIP39 actually consist of the mnemonic + a passphrase.

If you didn't set a passphrase when making the wallet then is is empty / null / 1 /  ```""```.

Some wallets (e.g Samourai Wallet / ColdCard) will give you the option to set a custom passphrase (not to be confused with a password). The passphrase is sometimes referred to as a "seed extension", "extension word" or "the 13th/25th word".

##### Why use a passphrase?

Passphrases add flexibility and deniability at little cost provided you are aware that you are using a passphrase and the understand the implications of losing / forgetting it.

###### 1) Using a passphrase helps manage multiple isolated wallets.

You can use any passphrase in combination with your mnemonic seed to generate a 'valid' bitcoin wallet. This means that you can easily have a number of bitcoin wallets which all use the same mnemonic seed words but which have unique passphrases. Importantly each wallet will be completely independent.

You may want to have two wallets; One for bitcoin transactions relating to your public identity and the second relating to your online identity.

To do this you could have one wallet with passphrase ```"public-identity"``` and another with passphrase ```"online-identity"```. Both would use the same seed words so you only need to worry about (and go through the process of securely backing up) one mnemonic seed.

Now *if* someone finds your mnemonic seed they could attempt to "brute force" your passphrases (essentially trying to guess your passphrase by an automated process of trial and error), and this could lead them to discover the link between your identities (or they could accidentally reveal the link on-chain by making a transaction which spends from coins controlled by both wallets) so if its paramount that these identities never collide you should use completely independent seeds **which are stored in separate locations**.

###### 2) Using a passphrase can enable a duress wallet.
You could store some of your bitcoin using a null passphrase and most of your bitcoin in a wallet which uses a passphrase. A thief / attacker who obtains your seed words will take your bitcoin and be unaware that you have access to additional funds using your passphrase.

You can even make a wallet using a passphrase which you intend to give out to attackers in the case of duress (i.e. kidnapping). You could pre-fund this with some bitcoin so that if the attacker demands you give a passphrase you can do so.

###### 3) Light defence against a non-technical thief

If you **don't** use a passphrase and someone finds your bitcoin mnemonic seed then you will lose your bitcoin if this person enters your seed into a wallet and sends the bitcoin to an address that they control.

The thief need not be technically savvy or even understand bitcoin - they just need to realise that they have found a seed, perform an internet search and find a wallet that will let them import the seed words.

If you **do** use a passphrase and someone comes upon your bitcoin mnemonic seed they may give up after attempting to sweep the funds and finding no bitcoin (the seed without the passphrase will generate valid bitcoin addresses which will all be empty).

##### Other things to consider about passphrases

###### Backing Up:
Forget a weak passphrase and you will have to brute force it. Forget a strong passphrase (to protect against a thief brute forcing it) and you will lose your bitcoin forever.

There are many options with regard to backing up seeds, and adding passphrases into the mix complicates things further. The key is to consider the benefits of each option;

- **One location:** You can backup all your passphrases in the same location(s) as your mnemonic seed backup (s). No more risky than using a null passphrase but lets you manage multiple isolated wallets.

- **Twos separate locations:** You can backup all your passphrases in one location different to your mnemonic seed backup(s). Strictly more secure against physical theft than using a null passphrase (thief has to compromise multiple locations) and can mislead a thief into thinking that they have stolen your main bitcoin stash. Increases risk of losing access to your own bitcoin (if you lose all backups of passphrase you lose your bitcoin - risk not present when using a null passphrase).

- **X Separate Locations:** You can backup each passphrase in a separate location to your mnemonic seed. Some of the benefits from the above with some of the downsides. Requires more locations for backups for the same per wallet redundancy (though could plausibly hide multiple different passphrase backups in one location).

- **Combo:** You can store one or more passphrases with your mnemonic seed and one or more in separate locations. Again, some benefits of above options with some of the downsides. Probably quite good for deniability / duress situations where attacker is familiar with passphrases.

###### Long term viability:
Assuming you are using a bip39 encoded wallet using a passphrase introduces no more technical complexity than not using one because all bip39 wallets are encoded to use a null passphrase.

The spec (bip39) is widespread and well documented - In my opinion it's unlikely it will be lost to the relics of time. You can always store a copy of the bip39 readme and a software implementation if you are worried about this.

###### Risk of bitcoin loss:

If you use a passphrase and then forget it you will lose your bitcoin.

#### 2) Encrypt the plaintext seed words

You can take your mnemonic seed and use any encryption method to ensure that you need to use a password to decrypt the file.
You use either Physical or Digital Encryption Tools;

- **Physical Encryption Tool** ([e.g. Enigma](https://en.wikipedia.org/wiki/Enigma_machine) / [One Time Pad](https://en.wikipedia.org/wiki/One-time_pad)): Clearly if you are using a physical encryption tool you will need to ensure that the tool is commonly available so that you can decode when required. Enigma Machines are hard to come by - so they are not a practical solution. The One Time Pad provides perfect encryption, but remember - anyone with physical access to the pad can decode the mnemonic.
- **Digital Encryption Tool** ([e.g. VeraCrypt](https://www.veracrypt.fr/en/Home.html)): If you are using a digital encryption tool you will need to ensure that the computer on which you are encrypting/decrypting data is secure. The easiest way to do this is to use a temporary OS like [tails](https://tails.boum.org) on an old computer which is not connected to the Internet.

### Should I split my mnemonic in two (short version)?

This reduces the cryptographic security of your backup (it is far easier to brute force the private key with half the mnemonic words already known than with none known).

That said, the thief would have to know what the words are and either spend time cracking the seed themselves or sell the words to someone who would have no way to know the bitcoin they could steal before cracking the seed (so may be unwilling to pay for the first/last words).

If you are going to do this be sure to use a 24 word mnemonic seed (not a 12 word mnemonic seed).

It is better to use [Shamir's secret sharing](https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing) to split the seed into 2 secrets, this way each piece of information is useless in isolation, and it is impossible to brute force the private key. The secrets can be recombined to recover the seed. You can also add redundancy, requiring say 2 of 3 of the secrets, or 3 of 5 (or any N of M). TailsOS comes with a pre-installed commandline tool called [ssss](http://point-at-infinity.org/ssss/) for this purpose.

[SLIP-0039](https://github.com/satoshilabs/slips/blob/master/slip-0039.md) will greatly increase the usage of sss.

Please let me know ([@6102bitcoin](https://keybase.io/6102)) if you can recommend any others.

### Should I split my mnemonic in two (long version)?

If an attacker knows the first/last 12 words of a 24 word seed the security against a brute force attack is greatly reduced (compared to brute forcing with none of the words known). Importantly it is more than twice as easy to brute force the half known seed (to understand without going into too much detail consider that 2^24 is 4096 times greater than 2^12).

All else being equal you should make it impossible for an attacker to access to any of your seed words.

In reality, all else is often not equal. It is important to consider the relative security of the options available to an individual when discussing bitcoin seed security.

Take Alice & Bob;
- Alice stores a full copy of her seed (24 words) in location A and a second full copy of her seed (24 words) in location B.
- Bob stores half his seed (12 words) in location A and the other half (12 words) in location B.

If an attacker (Charlie) goes to location A he can easily steal Alice's bitcoin with minimal effort or technical expertise - he simply has to identify that what he has found is a bitcoin seed and use a tool to try different derivation paths for the seed until he finds bitcoin to steal.

For Charlie to steal bob's bitcoin he will have to identify that he has found half a bitcoin wallet and then brute force the remaining 12 words. It is likely that this is computationally infeasible (more detailed analysis needed to verify this). It is also possible that the attacked would not be technically competent enough to brute force the seed, or that he wouldn't even realise that he has 12 words of a 24 word seed (perhaps he would assume that it's an invalid 12 word seed).

It would be natural to conclude that Bob's bitcoin seed is more secure than Alice's.

But now consider what would happen if Charlie is an arsonist (not a thief) and he sets location A on fire.

Regardless of how Alice stored her seed (on paper, stamped on metal etc.) she has a full backup in location B - she does not lose her bitcoin.
For Bob, how he stored his seed is now essential. He has no full backups, no redundancy. If the seed in location A is lost then so are all his bitcoin. Even if he stamped his seed into a metal plate it is possible that location A is an old building which collapsed in the fire, and his metal plate is buried under tonnes of brick and iron.

It would be natural to conclude that Alice's bitcoin are more secure then Bob's.

This example was simply meant to highlight that it is easy to forget that there are often trade-offs when it comes to securing your bitcoin seed. Though you should take care to minimize the risks posed by a sophisticated attacker capable of brute forcing half a 24 word seed you should first limit your exposure to risks which are more likely to pose a realistic threat (such as fire / malware / social attacks).

### Should I split my seed ABC into AB|BC|CA?

People will suggest using 3 partial seeds to a 24 word mnemonic seed, each with 16 words i.e. [1-16] , [9-24] , [17-24 & 1-8]. This does give some redundancy, but as discussed previously the relationship between number of revealed seed words and security against brute force attack is not linear.

As a simple exercise to compare of relative strength of 24, 12 and 8 unknown bits (0/1) compare the number of combinations possible. 2^24 = 16777216, 2^12 = 4096, 2^8 = 256.

There are ~ 4000 times fewer combinations of 12 bits than there are 24 bits, and ~65000 times fewer combinations of 8 bits than 24 bits. Other people will be able to crunch the actual numbers for BIP38 seeds, and it may be that the security of this method is still sufficiently high that it is a reasonable approach for almost everyone (excluding those which huge bitcoin holdings).

This method (splitting seed into three 2/3 pieces) is simple, and does not require evaluation of any additional code (as is required for Shamir's Secret Sharing) but it does significantly lower the security against brute force attacks.

# 4) Using your seed

### Can I recover my bitcoin without my seed?
No. It is not possible to recover your bitcoin unless you have your seed. **Lose your seed, Lose your bitcoin**.

### Can I recover my bitcoin without my passphrase?
If you used a strong passphrase is not possible to recover your bitcoin (you need BOTH your mnemonic seed AND your passphrase). If you used a weak passphrase (or can't remember whether your passphrase was strong) you will have to try and brute force it. If anyone has opensource tools to do this please [get in touch](https://keybase.io/6102).

### I have forgotten my passphrase, what now?
If you still have access to your wallet (say you are using Samourai Wallet on your mobile and you can get into an existing wallet with your PIN code) you should consider IMMEDIATELY sending your bitcoin to a new wallet for which you have backups of both the Mnemonic Seed AND the passphrase.
Be aware that you damage your privacy by consolidating UTXO's. It may be prudent to;
- Mark all UTXO's as 'do not spend' excluding one UTXO
- Send your max balance to a new address generated using your new wallet (with a new, backed up Mnemonic seed & Passphrase).
- Once sent, unmark another UTXO
- Send that to a second, new address generated using your new wallet
- Repeat

### How should I recover bitcoin using my seed?

You should follow the same rules when recovering bitcoin using your seed as when you are generating your seed;
- Carefully control the environment in which the seed is exposed. The easiest way for non-technical people to do this is to buy a 'Hardware Wallet'. These devices store all the 'secret information' required to access your bitcoin on the dedicated hardware device so that it doesn't matter if your computer has viruses/malware. That said, some hardware wallets are better than others so make sure that you never enter your seed into your computer - only enter it into the device itself.

Remember that if anyone sees your seed it is potentially compromised, and should be treated as such.
For this reason make sure that you recover bitcoin from your seed somewhere that is private and that has no cameras/CCTV.
- Don't read your seed aloud as someone could hear it.
- Don't type it into a computer

### What is the Derivation Path?

See [walletsrecovery.org](https://walletsrecovery.org/) for detailed information about the derivation path for each wallet.

Also see [StackExchange](https://bitcoin.stackexchange.com/questions/78993/default-derivation-paths) for some more info.

### How often should I check backups?

You should definitely check your backup as part of your process for backing up. Provided that you have done this correctly there should be no need to actually sweep bitcoin from the backup unless you need the bitcoin. It is worth checking that the backup remains accessible at irregular intervals (say every 1-3 years). It is worth checking because if a single backup disappears you can recover using a secondary backup (if there is a chance that the backup was stolen) or make a replacement backup (if you are completely confident that the backup was just damaged, e.g. house fire). Don't regularly check backups (e.g. the 1st Jan each year) as this could be obvious and lead to people discovering your backup.

More reading on this subject: [SmartCustodyWhitePapers](https://github.com/BlockchainCommons/SmartCustodyWhitePapers/blob/master/%23SmartCustody-_Simple_Self-Custody_Cold_Storage_Scenario.md)

gha_language: HTML