text:
[![Build Status](https://dev.azure.com/jasonShin91/functional-programming-jargon.rs/_apis/build/status/JasonShin.functional-programming-jargon.rs?branchName=master)](https://dev.azure.com/jasonShin91/functional-programming-jargon.rs/_build/latest?definitionId=3&branchName=master)

The project is a library for functional programming in Rust.

* [fp-core.rs](#fp-corers)
    * [installation](#installation)
* [functional programming jargon in rust](#functional-programming-jargon-in-rust)

# fp-core.rs

A library for functional programming in Rust.

It contains purely functional data structures to supplement the functional programming needs alongside
with the Rust Standard Library.

## Installation

Add below line to your Cargo.toml

```rust
fp-core = "0.1.8"
```

If you have [Cargo Edit](https://github.com/killercup/cargo-edit) you may simply

```bash
$ cargo add fp-core
```

# functional programming jargon in rust

Functional programming (FP) provides many advantages, and its popularity has been increasing as a result.
However, each programming paradigm comes with its own unique jargon and FP is no exception. By providing a glossary,
we hope to make learning FP easier.

Where applicable, this document uses terms defined in the [Fantasy Land spec](https://github.com/fantasyland/fantasy-land)
and Rust programming language to give code examples.

Also please be mindful that the project sometimes utilise FP related crates that are unfinished but contains
a specific typeclass or data type that is appropriate to give an explanation. Many of them are experimental and
are not suitable for production usage.

__Table of Contents__

* [Arity](#arity)
* [Higher-Order Functions (HOF)](#higher-order-functions-hof)
* [Closure](#closure)
* [Partial Application](#partial-application)
* [Currying](#currying)
* [Auto Currying](#auto-currying)
* [Referential Transparency](#referential-transparency)
* [Lambda](#lambda)
* [Lambda Calculus](#lambda-calculus)
* [Purity](#purity)
* [Side effects](#side-effects)
* [Idempotent](#idempotent)
* [Function Composition](#function-composition)
* [Continuation](#continuation)
* [Point-Free Style](#point-free-style)
* [Predicate](#predicate)
* [Contracts](#contracts)
* [Category](#category)
* [Value](#value)
* [Constant](#constant)
* [Variance](#variance)
* [Higher Kinded Type](#higher-kinded-type-hkt)
* [Functor](#functor)
* [Pointed Functor](#pointed-functor)
* [Lifting](#lifting)
* [Equational Reasoning](#equational-reasoning)
* [Monoid](#monoid)
* [Monad](#monad)
* [Comonad](#comonad)
* [Applicative](#applicative)
* [Morphism](#morphism)
  * [Endomorphism](#endomorphism)
  * [Isomorphism](#isomorphism)
  * [Homomorphism](#homomorphism)
  * [Catamorphism](#catamorphism)
  * [Hylomorphism](#hylomorphism)
  * [Anamorphism](#anamorphism)
* [Setoid](#setoid)
* [Ord](#ord)
* [Semigroup](#semigroup)
* [Foldable](#foldable)
* [Lens](#lens)
* [Type Signature](#type-signature)
* [Algebraic data type](#algebraic-data-type)
  * [Sum Type](#sum-type)
  * [Product Type](#product-type)
* [Option](#option)
* [Functional Programming References](#functional-programming-references)
* [Function Programming development in Rust Language](#functional-programming-development-in-rust-language)
* [My thought on this project](#my-thought-on-this-project)

## Arity

The number of arguments a function takes. From words like unary, binary, ternary, etc.
This word has the distinction of being composed of two suffixes, "-ary" and "-ity."
Addition, for example, takes two arguments, and so it is defined as a binary function or a function with an arity of two.
Such a function may sometimes be called "dyadic" by people who prefer Greek roots to Latin.
Likewise, a function that takes a variable number of arguments is called "variadic,"
whereas a binary function must be given two and only two arguments, currying and partial application notwithstanding (see below).

```rust
let sum = |a: i32, b: i32| { a + b }; // The arity of sum is 2
```

## Higher-Order Functions (HOF)

A function which takes a function as an argument and/or returns a function.

```rust
let filter = | predicate: fn(&i32) -> bool, xs: Vec<i32> | {
    xs.into_iter().filter(predicate).collect::<Vec<i32>>()
};
```

```rust
let is_even = |x: &i32| { x % 2 == 0 };
```

```rust
filter(is_even, vec![1, 2, 3, 4, 5, 6]);
```

## Closure

A closure is a scope which retains variables available to a function when it's created. This is important for
[partial application](#partial-application) to work.

```rust
let add_to = |x: i32| move |y: i32| x + y;
```

We can call `add_to` with a number and get back a function with a baked-in `x`. Notice that we also need to move the ownership of the x to the internal lambda.

```rust
let add_to_five = add_to(5);
```

In this case the `x` is retained in `add_to_five`'s closure with the value `5`. We can then call `add_to_five` with the `y`
and get back the desired number.

```rust
add_to_five(3); // => 8
```

Closures are commonly used in event handlers so that they still have access to variables defined in their parents when they
are eventually called.

__Further reading__
* [Lambda Vs Closure](http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda)
* [How do JavaScript Closures Work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)

## Partial Application

Partially applying a function means creating a new function by pre-filling some of the arguments to the original function.

To achieve this easily, we will be using a [partial application crate](https://crates.io/crates/partial_application)

```rust
#[macro_use]
extern crate partial_application;

fn foo(a: i32, b: i32, c: i32, d: i32, mul: i32, off: i32) -> i32 {
    (a + b*b + c.pow(3) + d.pow(4)) * mul - off
}

let bar = partial!( foo(_, _, 10, 42, 10, 10) );

assert_eq!(
    foo(15, 15, 10, 42, 10, 10),
    bar(15, 15)
); // passes
```

Partial application helps create simpler functions from more complex ones by baking in data when you have it.
Curried functions are automatically partially applied.

__Further reading__
* [Partial Application in Haskell](https://wiki.haskell.org/Partial_application)

## Currying

The process of converting a function that takes multiple arguments into a function that takes them one at a time.

Each time the function is called it only accepts one argument and returns a function that takes one argument until all arguments are passed.

```rust
fn add(x: i32) -> impl Fn(i32)-> i32 {
    move |y| x + y
}

let add5 = add(5);
add5(10); // 15
```

__Further reading__
* [Currying in Rust](https://hashnode.com/post/currying-in-rust-cjpfb0i2z00cm56s2aideuo4z)

## Auto Currying

Transforming a function that takes multiple arguments into one that if given less than its
correct number of arguments returns a function that takes the rest. When the function gets the correct number of
arguments it is then evaluated.

Although Auto Currying is not possible in Rust right now, there is a debate on this issue on the Rust forum:
https://internals.rust-lang.org/t/auto-currying-in-rust/149/22

## Referential Transparency

An expression that can be replaced with its value without changing the behavior of the program is said to be referentially transparent.

Say we have function greet:

```rust
let greet = || "Hello World!";
```

Any invocation of `greet()` can be replaced with `Hello World!` hence greet is referentially transparent.

## Lambda

An anonymous function that can be treated like a value.

```rust
fn  increment(i: i32) -> i32 { i + 1 }

let closure_annotated = |i: i32| { i + 1 };
let closure_inferred = |i| i + 1;
```

Lambdas are often passed as arguments to Higher-Order functions.
You can assign a lambda to a variable, as shown above.

## Lambda Calculus

A branch of mathematics that uses functions to create a [universal model of computation](https://en.wikipedia.org/wiki/Lambda_calculus).

This is in contrast to a [Turing machine](https://www.youtube.com/watch?v=dNRDvLACg5Q), an equivalent model.

Lambda calculus has three key components: variables, abstraction, and application. A variable is just some
symbol, say `x`. An abstraction is sort of a function: it binds variables into "formulae". Applications
are function calls. This is meaningless without examples.

The identity function (`|x| x` in rust) looks like `\ x. x` in most literature (`\` is a Lambda where Latex
or Unicode make it available). It is an abstraction. If `1` were a value we could use, `(\ x. x) 1` would
be an application (and evaluating it gives you `1`).

But there's more...

__Computation in Pure Lambda Calculus__

Let's invent booleans. `\ x y. x` can be true and `\ x y. y` can be false.
If so, `\ b1 b2. b1(b2,(\x y. y))` is `and`. Let's evaluate it to show how:

| `b1` | `b2` | Their `and` |
| --- | --- | --- |
| `\ x y. x` | `\x y. x` | `\x y. x` |
| `\ x y. x` | `\x y. y` | `\x y. y` |
| `\ x y. y` | `\x y. y` | `\x y. y` |
| `\ x y. y` | `\x y. x` | `\x y. y` |

I'll leave `or` as an exercise. Furthermore, `if` can now be implemented: `\c t e. c(t, e)` where `c` is the condition, `t`
the consequent (`then`) and `e` the else clause.

[SICP leaves numbers as an exercise.](https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-14.html#%_idx_1474)
They define 0 as `\f . \x. x` and adding one as `\n. \f. \x. f(n(f)(x))`.
That isn't even ASCII art, so let's add: `0 + 1`:

```
(\n. \f. \x. f(n(f)(x)))(\f. \x. x) = \f. \x. f((\x'. x')(x)) = \f. \x. f(x)
```

Basically, the number of `f`s in the expression is the number. I'll leave figuring out larger numbers as a exercise.
With patience, you can show that `\f. \x. f(f(x))` is two.  This will help with addition: `\n m. \f. \x. n(m(f)(x))`
should add two numbers. Let's make 4:

```
(\n m. \f. \x. n(f)(m(f)(x)))(\f. x. f(f(x)), \f. \x. f(f(x)))
  = \f. \x. (\f'. \x'. f'(f'(x')))(f)((\f'. \x'. f'(f'(x')))(f)(x))
  = \f. \x. (\x'. f(f(x')))(f(f(x')))
  = \f. \x. f(f(f(f(x))))
```

Multiplication is harder and there's better
[exposition on Wikipedia](https://en.wikipedia.org/wiki/Church_encoding#Calculation_with_Church_numerals).
Another good reference is [on stackoverflow](https://stackoverflow.com/questions/3077908/church-numeral-for-addition).

## Purity

A function is pure if the return value is only determined by its input values, and does not produce side effects.

```rust
let greet = |name: &str| { format!("Hi! {}", name) };

greet("Jason"); // Hi! Jason
```

As opposed to each of the following:

```rust
let name = "Jason";

let greet = || -> String {
    format!("Hi! {}", name)
};

greet(); // String = "Hi! Jason"
```

The above example's output is based on data stored outside of the function...

```rust
let mut greeting: String = "".to_string();

let mut greet = |name: &str| {
    greeting = format!("Hi! {}", name);
};

greet("Jason");

assert_eq!("Hi! Jason", greeting); // Passes
```

... and this one modifies state outside of the function.

## Side effects

A function or expression is said to have a side effect if apart from returning a value,
it interacts with (reads from or writes to) external mutable state.

```rust
use std::time::SystemTime;

let now = SystemTime::now();
```

```rust
println!("IO is a side effect!");
// IO is a side effect!
```

## Idempotent

A function is idempotent if reapplying it to its result does not produce a different result.

```rust
// Custom immutable sort method
let sort = |x: Vec<i32>| -> Vec<i32> {
    let mut x = x;
    x.sort();
    x
};
```

Then we can use the sort method like

```rust
let x = vec![2 ,1];
let sorted_x = sort(sort(x.clone()));
let expected = vec![1, 2];
assert_eq!(sorted_x, expected); // passes
```

```rust
let abs = | x: i32 | -> i32 {
    x.abs()
};

let x: i32 = 10;
let result = abs(abs(x));
assert_eq!(result, x); // passes
```

## Function Composition

The act of putting two functions together to form a third function where the output of one function is the input of the other.
Below is an example of compose function is Rust.

```rust
macro_rules! compose {
    ( $last:expr ) => { $last };
    ( $head:expr, $($tail:expr), +) => {
        compose_two($head, compose!($($tail),+))
    };
}

fn compose_two<A, B, C, G, F>(f: F, g: G) -> impl Fn(A) -> C
where
    F: Fn(A) -> B,
    G: Fn(B) -> C,
{
    move |x| g(f(x))
}
```

Then we can use it like

```rust
let add = | x: i32 | x + 2;
let multiply = | x: i32 | x * 2;
let divide = | x: i32 | x / 2;

let intermediate = compose!(add, multiply, divide);

let subtract = | x: i32 | x - 1;

let finally = compose!(intermediate, subtract);

let expected = 11;
let result = finally(10);
assert_eq!(result, expected); // passes
```

## Continuation

At any given point in a program, the part of the code that's yet to be executed is known as a continuation.

```rust
let print_as_string = |num: i32| println!("Given {}", num);

let add_one_and_continue = |num: i32, cc: fn(i32)| {
    let result = num + 1;
    cc(result)
};

add_one_and_continue(1, print_as_string); // Given 2
```

Continuations are often seen in asynchronous programming when the program needs to wait to receive data before it can continue.
 The response is often passed off to the rest of the program, which is the continuation, once it's been received.

## Point-Free style

Writing functions where the definition does not explicitly identify the arguments used.
This style usually requires currying or other Higher-Order functions. A.K.A Tacit programming.

## Predicate

A predicate is a function that returns true or false for a given value.
A common use of a predicate is as the callback for array filter.

```rust
let predicate = | a: &i32 | a.clone() > 2;

let result = (vec![1, 2, 3, 4]).into_iter().filter(predicate).collect::<Vec<i32>>();

assert_eq!(result, vec![3, 4]); // passes
```

## Contracts

A contract specifies the obligations and guarantees of the behavior from a function or expression at runtime.
This acts as a set of rules that are expected from the input and output of a function or expression,
and errors are generally reported whenever a contract is violated.

```rust
let contract = | x: &i32 | -> bool {
    x > &10
};

let add_one = | x: &i32 | -> Result<i32, String> {
    if contract(x) {
        return Ok(x + 1);
    }
    Err("Cannot add one".to_string())
};
```

Then you can use `add_one` like

```rust
let expected = 12;
match add_one(&11) {
    Ok(x) => assert_eq!(x, expected),
    _ => panic!("Failed!")
}
```

## Category

A category in category theory is a collection of objects and morphisms between them. In programming, typically types
act as the objects and functions as morphisms.

To be a valid category 3 rules must be met:

1. There must be an identity morphism that maps an object to itself.
    Where `a` is an object in some category,
    there must be a function from `a -> a`.
2. Morphisms must compose.
    Where `a`, `b`, and `c` are objects in some category,
    and `f` is a morphism from `a -> b`, and `g` is a morphism from `b -> c`;
    `g(f(x))` must be equivalent to `(g • f)(x)`.
3. Composition must be associative
    `f • (g • h)` is the same as `(f • g) • h`

Since these rules govern composition at very abstract level, category theory is great at uncovering new ways of composing things.
In particular, many see this as another foundation of mathematics (so, everything would be a category from this view of math).
Various definitions in this guide are related to category theory since this approach applies elegantly to functional programming.

__Examples of categories__

When one specifies a category, the objects and morphisms are essential. Additionally, showing that the rules are met is nice
though usually left to the reader as an exercise.

* Any type and pure functions on the type. (Note, we require purity since side-effects affect associativity (the third rule).)

These examples come up in mathematics:

* 1: the category with 1 object and its identity morphism.
* Monoidal categories: [monoids are defined later](#monoids) but any monoid is a category with 1 object and many morphisms
  from the object to itself. (Yes, there is also a category of monoids -- this is not that -- this example is that any monoid is its own
  category.)

__Further reading__

* [Category Theory for Programmers](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/)
* [Awodey's introduction](http://citeseerx.ist.psu.edu/viewdoc/download?doi=<IP_ADDRESS>.4754&rep=rep1&type=pdf) for those who like math.

## Value

Anything that can be assigned to a variable.

```rust
let a = 5;
let b = vec![1, 2, 3];
let c = "test";
```

## Constant

A variable that cannot be reassigned once defined.

```rust
let a = 5;
a = 3; // error!
```

Constants are [referentially transparent](#referential-transparency).
That is, they can be replaced with the values that they represent without affecting the result.

## Variance

Variance in functional programming refers to subtyping between more complex types related to subtyping between
their components.

Unlike other usage of variance in [Object Oriented Programming like Typescript or C#](https://medium.com/@michalskoczylas/covariance-contravariance-and-a-little-bit-of-typescript-2e61f41f6f68)
or [functional programming language like Scala or Haskell](https://medium.com/@wiemzin/variances-in-scala-9c7d17af9dc4)

Variance in Rust is used during the type checking against type and lifetime parameters. Here are examples:
- By default, all lifetimes are co-variant except for `'static` because it outlives all others
- `'static` is always contra-variant to others regardless of where it appears or used
- It is `in-variant` if you use `Cell<T>` or `UnsafeCell<T>` in `PhatomData`

**Further Reading**

- https://github.com/rust-lang/rustc-guide/blob/master/src/variance.md
- https://nearprotocol.com/blog/understanding-rust-lifetimes/

## Higher Kinded Type (HKT)

Rust does not support Higher Kinded Types [yet](https://github.com/rust-lang/rust/issues/8922). First of all, HKT is a
type with a "hole" in it, so you can declare a type signature such as `trait Functor<F<A>>`.

Although Rust lacks in a native support for HKT, we always have a walk around called [Lightweight Higher Kinded Type](https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-kinded-polymorphism.pdf)

An implementation example of above theory in Rust would look like below:

```rust
pub trait HKT<A, B> {
    type URI;
    type Target;
}

// Lifted Option
impl<A, B> HKT<A, B> for Option<A> {
    type URI = Self;
    type Target = Option<B>;
}
```

Higher Kinded Type is crucial for functional programming in general.

**Further Reading**

- https://gist.github.com/CMCDragonkai/a5638f50c87d49f815b8
- https://www.youtube.com/watch?v=ERM0mBPNLHc

## Functor

An object that implements a map function which,
while running over each value in the object to produce a new functor of the same type, adheres to two rules:

__Preserves identity__

```
object.map(x => x) ≍ object
```

__Composable__

```
object.map(compose(f, g)) ≍ object.map(g).map(f)
```

(`f`, `g` are arbitrary functions)

For example, below can be considered as a functor-like operation

```rust
let v: Vec<i32> = vec![1, 2, 3].into_iter().map(| x | x + 1).collect();

assert_eq!(v, vec![2, 3, 4]); // passes while mapping the original vector and returns a new vector
```

While leveraging the [HKT implementation](#higher-kinded-type-hkt), You can define a trait that represents Functor like below

```rust
pub trait Functor<A, B>: HKT<A, B> {
    fn fmap<F>(self, f: F) -> <Self as HKT<A, B>>::Target
        where F: FnOnce(A) -> B;
}
```

Then use it against a type such as [Option](#https://doc.rust-lang.org/std/option/index.html) like

```rust
impl<A, B> Functor<A, B> for Option<A> {
    fn fmap<F>(self, f: F) -> Self::Target
        where
            F: FnOnce(A) -> B
    {
        self.map(f)
    }
}

// This conflicts with the above, so isn't tested
// below and is commented out. TODO: add a careful
// implementation that makes sure Optional and this
// don't conflict.
impl<A, B, T> HKT<A, B> for T
where
    T: Sized + Iterator<Item = A>,
    U: Sized + Iterator<Item = B>,
{
    type URI = Self;
    type Target = U;
}

impl<A, B, T> Functor<A, B> for T
where
    T: Iterator<Item = A>,
{
    fn fmap<F>(self, f: F) -> Self::Target
    where
        F: FnOnce(A) -> B,
        A: Sized,
        B: Sized,
    {
        self.map(f)
    }
}

#[test]
fn test_functor() {
    let z = Option::fmap(Some(1), |x| x + 1).fmap(|x| x + 1); // Return Option<B>
    assert_eq!(z, Some(3)); // passes
}
```

__The Underlying Math__

The confusing fact is that functors are morphisms in the category of categories. Really, this means that
a functor from category `C` into `D` preserves properties of the category, so that the data is somewhat
preserved.

Technically, every category has a functor into the simplest (non-empty) category (1): since the category `1` just
has one object and one function, map all the objects and functions in whatever category you start from into the
thing in `1`. So, data isn't quite preserved in a "nice" sense. Such functors are called forgetful sometimes as
they drop structure.

However, less forgetful examples provide more insight and empower useful statements about types.
Unfortunately, these are rather heavy-handed in the mathematics they evoke.

## Pointed Functor

An object with an of function that puts any single value into it.

```rust
#[derive(Debug, PartialEq, Eq)]
enum Maybe<T> {
    Nothing,
    Just(T),
}

impl<T> Maybe<T> {
    fn of(x: T) -> Self {
        Maybe::Just(x)
    }
}
```

Then use it like

```rust
let pointed_functor = Maybe::of(1);

assert_eq!(pointed_functor, Maybe::Just(1));
```

## Lifting

Lifting in functional programming typically means to lift a function into a context (a Functor or Monad).
For example, give a function `a -> b` and lift it into a `List` then the signature would
look like `List[a] -> List[b]`.

**Further Reading**
- https://wiki.haskell.org/Lifting
- https://stackoverflow.com/questions/43482772/difference-between-lifting-and-higher-order-functions
- https://stackoverflow.com/questions/2395697/what-is-lifting-in-haskell/2395956

## Equational Reasoning

When an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts.

## Monoid

An set with a binary function that "combines" pairs from that set into another element of the set.

One simple monoid is the addition of numbers:

```rust
1 + 1
// i32: 2
```

In this case numbers are the set and `+` is the function.

An "identity" value must also exist that when combined with a value doesn't change it.

The identity value for addition is `0`.

```rust
1 + 0
// i32: 1
```

It's also required that the grouping of operations will not affect the result (associativity):

```rust
1 + (2 + 3) == (1 + 2) + 3
// bool: true
```

Array concatenation also forms a monoid:

```rust
[vec![1, 2, 3], vec![4, 5, 6]].concat();
// Vec<i32>: vec![1, 2, 3, 4, 5, 6]
```

The identity value is empty array `[]`

```rust
[vec![1, 2], vec![]].concat();
// Vec<i32>: vec![1, 2]
```

If identity and compose functions are provided, functions themselves form a monoid:

```rust
fn identity<A>(a: A) -> A {
    a
}
```

`foo` is any function that takes one argument.

```rust
compose(foo, identity) ≍ compose(identity, foo) ≍ foo
```

We can express Monoid as a Rust trait and the type signature would look like below

```rust
use crate::applicative_example::Applicative;

trait Empty<A> {
    fn empty() -> A;
}

trait Monoid<A, F, B>: Empty<A> + Applicative<A, F, B>
where
    F: FnOnce(A) -> B,
{
}
```

According to Fantasy Land Specification, Monoid should implement `Empty` and `Applicative`.

## Monad

A [Monad](https://github.com/fantasyland/fantasy-land#monad) is a trait that implements `Applicative` and `Chain` specifications. `chain` is
like `map` except it un-nests the resulting nested object.

First, `Chain` type can be implemented like below:

```rust
pub trait Chain<A, B>: HKT<A, B> {
    fn chain<F>(self, f: F) -> <Self as HKT<A, B>>::Target
        where F: FnOnce(A) -> <Self as HKT<A, B>>::Target;
}

impl<A, B> Chain<A, B> for Option<A> {
    fn chain<F>(self, f: F) -> Self::Target
        where F: FnOnce(A) -> <Self as HKT<A, B>>::Target {
        self.and_then(f)
    }
}
```

Then `Monad` itself can simply derive `Chain` and `Applicative`

```rust
pub trait Monad<A, F, B>: Chain<A, B> + Applicative<A, F, B>
    where F: FnOnce(A) -> B {}

impl<A, F, B> Monad<A, F, B> for Option<A>
    where F: FnOnce(A) -> B {}

#[test]
fn monad_example() {
    let x = Option::of(Some(1)).chain(|x| Some(x + 1));
    assert_eq!(x, Some(2)); // passes
}
```

`pure` is also known as `return` in other functional languages. `flat_map` is also known as `bind` in other languages.

Importantly, it is worth noting that monads are a rather advanced topic in category theory. In fact, they are called
triples by some as they involve adjoint functors and their unit -- both of which are rare to see in functional programming.
The meme is to think of a monad as a burrito with "pure" being the act of taking a tortilla (the empty burrito) and
adding ingredients using "chain".

The purely mathematical presentation of monads does not look anything like this, but there is an equivalence.

## Comonad

An object that has `extract` and `extend` functions.

```rust
trait Extend<A, B>: Functor<A, B> + Sized {
    fn extend<W>(self, f: W) -> <Self as HKT<A, B>>::Target
    where
        W: FnOnce(Self) -> B;
}

trait Extract<A> {
    fn extract(self) -> A;
}

trait Comonad<A, B>: Extend<A, B> + Extract<A> {}
```

Then we can implement these types for Option

```rust
impl<A, B> Extend<A, B> for Option<A> {
    fn extend<W>(self, f: W) -> Self::Target
    where
        W: FnOnce(Self) -> B,
    {
        self.map(|x| f(Some(x)))
    }
}

impl<A> Extract<A> for Option<A> {
    fn extract(self) -> A {
        self.unwrap() // is there a better way to achieve this?
    }
}
```

Extract takes a value out of a comonad.

```rust
Some(1).extract(); // 1
```

Extend runs a function on the Comonad.

```rust
Some(1).extend(|co| co.extract() + 1); // Some(2)
```

This can be thought of as the reverse of a monad. In fact, this is called
the "dual" in category theory. (Basically, if you know what `A` is, a `coA`
is everything in `A`'s definition with the arrows reversed.)

## Applicative

An applicative functor is an object with an `ap` function. `ap` applies a function in the object to a value in another
object of the same type. Given a pure program `g: (b: A) -> B`, we must lift it to `g: (fb: F<A>) -> F<B>`. In order to achieve
this, we will introduce another [higher kinded type](#higher-kinded-type-hkt), called `HKT3` that is capable of doing this.

For this example, we will use Option datatype.

```rust
trait HKT3<A, B, C> {
    type Target2;
}

impl<A, B, C> HKT3<A, B, C> for Option<A> {
    type Target2 = Option<B>;
}
```

Since Applicative implements Apply for `ap`  and `Pure` for `of` according to [Fantasy Land specification](https://github.com/fantasyland/fantasy-land#applicative)
we must implement the types like below:

```rust

// Apply
trait Apply<A, F, B> : Functor<A, B> + HKT3<A, F, B>
    where F: FnOnce(A) -> B,
{
    fn ap(self, f: <Self as HKT3<A, F, B>>::Target2) -> <Self as HKT<A, B>>::Target;
}

impl<A, F, B> Apply<A, F, B> for Option<A>
    where F: FnOnce(A) -> B,
{
    fn ap(self, f: Self::Target2) -> Self::Target {
        self.and_then(|v| f.map(|z| z(v)))
    }
}

// Pure
trait Pure<A>: HKT<A, A> {
    fn of(self) -> <Self as HKT<A, A>>::Target;
}

impl<A> Pure<A> for Option<A> {
    fn of(self) -> Self::Target {
        self
    }
}

// Applicative
trait Applicative<A, F, B> : Apply<A, F, B> + Pure<A>
    where F: FnOnce(A) -> B,
{
} // Simply derives Apply and Pure

impl<A, F, B> Applicative<A, F, B> for Option<A>
    where F: FnOnce(A) -> B,
{
}
```

Then we can use Option Applicative like this:

```rust
let x = Option::of(Some(1)).ap(Some(|x| x + 1));
assert_eq!(x, Some(2));
```

## Morphism

A function that preserves the structure of its domain.
See [the category definition](#category) from more.

The first few (endomorphism, homomorphism, and isomorphism) are easier to
understand than the rest. The rest require the notion of an F-algebra.
The simpler Haskell declarations are listed in [the wikipedia on paramorphisms](https://en.wikipedia.org/wiki/Paramorphism)
but the notions have yet to be extended to more general category theory.
Briefly, the view of F-algebras is to take the set-theoretic definition of algebraic
objects and redefined them on a purely category theoretic footing: to move the ideas
away from sets containing elements to collections of objects with morphisms.
However, some of the ideas here have yet to be generalised into this movement.

### Endomorphism

A function where the input type is same as the output.

```rust
// uppercase :: &str -> String
let uppercase = |x: &str| x.to_uppercase();

// decrement :: i32 -> i32
let decrement = |x: i32| x - 1;
```

### Isomorphism

A pair of transformations between 2 types of objects that is invertible.

For example, 2D coordinates could be stored as a i32 vector [2,3] or a struct {x: 2, y: 3}.

```rust
#[derive(PartialEq, Debug)]
struct Coords {
    x: i32,
    y: i32,
}

let pair_to_coords = | pair: (i32, i32) | Coords { x: pair.0, y: pair.1 };
let coords_to_pair = | coords: Coords | (coords.x, coords.y);
assert_eq!(
    pair_to_coords((1, 2)),
    Coords { x: 1, y: 2 },
); // passes
assert_eq!(
    coords_to_pair(Coords { x: 1, y: 2 }),
    (1, 2),
); // passes
```

Isomorphisms are critical in making structures identical. Since we know that the struct above is
identical to a pair, all the functions that exist on the pair can exist on the struct. If `f`
is the isomorphism and `g` and endomorphism on the codomain: `f^{-1} g f` would extend `g`
to apply on the domain.

### Homomorphism

A homomorphism is just a structure preserving map. It is the older term of morphism.
In fact, a functor is just a homomorphism between categories as it preserves the original category's structure under the mapping.

```rust
assert_eq!(A::of(f).ap(A::of(x)), A::of(f(x))); // passes
assert_eq!(
    Either::of(|x: &str| x.to_uppercase(x)).ap(Either::of("oreos")),
    Either::of("oreos".to_uppercase),
); // passes
```

### Catamorphism

A `reduceRight` function that applies a function against an accumulator and each value of the array (from right-to-left)
to reduce it to a single value.

```rust
let sum = |xs: Vec<i32>| xs.iter().fold(0, |mut sum, &val| { sum += val; sum });

assert_eq!(sum(vec![1, 2, 3, 4, 5]), 15);
```

### Anamorphism

An `unfold` function. An `unfold` is the opposite of `fold` (`reduce`). It generates a list from a single value.

```rust
let count_down = unfold((8_u32, 1_u32), |state| {
    let (ref mut x1, ref mut x2) = *state;

    if *x1 == 0 {
        return None;
    }

    let next = *x1 - *x2;
    let ret = *x1;
    *x1 = next;

    Some(ret)
});

assert_eq!(
    count_down.collect::<Vec<u32>>(),
    vec![8, 7, 6, 5, 4, 3, 2, 1],
);
```

### Hylomorphism

The combination of anamorphism and catamorphism.

### Apomorphism

It's the opposite of paramorphism, just as anamorphism is the opposite of catamorphism.
Whereas with paramorphism, you combine with access to the accumulator and what has been accumulated,
apomorphism lets you unfold with the potential to return early.

## Setoid

This is a set with an equivalence relation.

An object that has an `equals` function which can be used to compare other objects of the same type.

It must obey following rules to be `Setoid`

1. `a.equals(a) == true` (reflexivity)
2. `a.equals(b) == b.equals(a)` (symmetry)
3. `a.equals(b)` and `b.equals(c)` then `a.equals(c)` (transitivity)

Make a Vector a setoid:

Note that I am treating `Self` / `self` like `a`.

```rust
trait Setoid {
    fn equals(&self, other: &Self) -> bool;
}

impl Setoid for Vec<i32> {
    fn equals(&self, other: &Self) -> bool {
        self.len() == other.len()
    }
}

assert_eq!(vec![1, 2].equals(&vec![1, 2]), true); // passes
```

In Rust standard library, it already provides [Eq](https://doc.rust-lang.org/std/cmp/trait.Eq.html), which
resembles Setoid that was discussed in this section. Also [Eq](https://doc.rust-lang.org/std/cmp/trait.Eq.html)
has `equals` implementations that covers a range of data structures that already exist in Rust.

## Ord

An object or value that implements Ord specification, also implements [Setoid](#setoid) specification.

The Ord object or value must satisfy below rules for all `a`, `b` or `c`:

1. totality: `a <= b` or `b <= a`
2. antisymmetric: `a <= b` and `b <= a`, then `a == b`
3. transivity: `a <= b` and `b <= c`, then `a <= c`

Rust documentation for Ord can be found here [Ord](https://doc.rust-lang.org/std/cmp/trait.Ord.html)

## Semigroup

An object that has a `combine` function that combines it with another object of the same type.

It must obey following rules to be `Semigroup`

1. `a.add(b).add(c)` is equivalent to `a.add(b.add(c))` (associativity)

```rust
use std::ops::Add;

pub trait Semigroup<M>: Add<M> {
}

assert_eq!(
    vec![1, 2].add(&vec![3, 4]),
    vec![1, 2, 3, 4],
); // passes

assert_eq!(
    a.add(&b).add(&c),
    a.add(&b.add(&c)),
); // passes
```

## Foldable

An object that has a `foldr/l` function that can transform that object into some other type. We are using `rats` to give
an example but the crate only implements `fold_right`.

`fold_right` is equivalent to Fantasy Land Foldable's `reduce`, which goes like:

`fantasy-land/reduce :: Foldable f => f a ~> ((b, a) -> b, b) -> b`

```rust
use rats::foldable::Foldable;
use rats::kind::IntoKind;
use rats::kinds::VecKind;

let k = vec![1, 2, 3].into_kind();
let result = VecKind::fold_right(k, 0, | (i, acc) | i + acc);
assert_eq!(result, 6);
```

If you were to implement `Foldable` manually, the trait of it would look like below

```rust
use crate::hkt::HKT;
use crate::monoid::Monoid;

pub trait Foldable<A, B>: HKT<A, B> {
    fn reduce<F>(b: B, ba: F) -> <Self as HKT<A, B>>::Target
    where
        F: FnOnce(B, A) -> (B, B);

    fn fold_map<M, N, F>(m: M, fa: F) -> M
    where
        M: Monoid<N>,
        F: FnOnce(<Self as HKT<A, B>>::URI) -> M;

    fn reduce_right<F>(b: B, f: F) -> <Self as HKT<A, B>>::Target
    where
        F: FnOnce(A, B) -> (B, B);
}
```

## Lens

A lens is a type that pairs a getter and a non-mutating setter for some other data structure.

```rust
trait Lens<S, A> {
    fn over(s: &S, f: &Fn(Option<&A>) -> A) -> S {
        let result: A = f(Self::get(s));
        Self::set(result, &s)
    }
    fn get(s: &S) -> Option<&A>;
    fn set(a: A, s: &S) -> S;
}

#[derive(Debug, PartialEq, Clone)]
struct Person {
    name: String,
}

#[derive(Debug)]
struct PersonNameLens;

impl Lens<Person, String> for PersonNameLens {
    fn get(s: &Person) -> Option<&String> {
       Some(&s.name)
    }

    fn set(a: String, s: &Person) -> Person {
        Person {
            name: a,
        }
    }
}
```

Having the pair of get and set for a given data structure enables a few key features.

```rust
let e1 = Person {
    name: "Jason".to_string(),
};
let name = PersonNameLens::get(&e1);
let e2 = PersonNameLens::set("John".to_string(), &e1);
let expected = Person {
    name: "John".to_string()
};
let e3 = PersonNameLens::over(&e1, &|x: Option<&String>| {
    match x {
        Some(y) => y.to_uppercase(),
        None => panic!("T_T") // lol...
    }
});

assert_eq!(*name.unwrap(), e1.name); // passes
assert_eq!(e2, expected); // passes
assert_eq!(e3, Person { name: "JASON".to_string() }); // passes
```

Lenses are also composable. This allows easy immutable updates to deeply nested data.

```rust
struct FirstLens;

impl<A> Lens<Vec<A>, A> for FirstLens {
  fn get(s: &Vec<A>) -> Option<&A> {
     s.first()
  }

  fn set(a: A, s: &Vec<A>) -> Vec<A> {
      unimplemented!() // Nothing to set in FirstLens
  }
}

let people = vec![Person { name: "Jason" }, Person { name: "John" }];
Lens::over(composeL!(FirstLens, NameLens), &|x: Option<&String>| {
  match x {
      Some(y) => y.to_uppercase(),
      None => panic!("T_T")
  }
}, people); // vec![Person { name: "JASON" }, Person { name: "John" }];
```

**Further Reading**

- [A Little Lens Starter](https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/a-little-lens-starter-tutorial)
- [Monocle Scala](https://scalac.io/scala-optics-lenses-with-monocle/)

## Type Signature

Every function in Rust will indicate the types of their arguments and return values.

```rust
// add :: i32 -> i32 -> i32
fn add(x: i32) -> impl Fn(i32)-> i32 {
    move |y| x + y
}

// increment :: i32 -> i32
fn increment(x: i32) -> i32 {
    x + 1
}
```

If a function accepts another function as an argument it is wrapped in parentheses.

```rust
// call :: (a -> b) -> a -> b
fn call<A, B>(f: &Fn(A) -> B) -> impl Fn(A) -> B + '_ {
    move |x| f(x)
}
```

The letters `a`, `b`, `c`, `d` are used to signify that the argument can be of any type.
The following version of map takes `a` function that transforms `a` value of some type `a` into another type `b`,
an array of values of type `a`, and returns an array of values of type `b`.

```rust
// map :: (a -> b) -> [a] -> [b]
fn map<A, B>(f: &Fn(A) -> B) -> impl Fn(A) -> B + '_ {
    move |x| f(x)
}
```

**Further Reading**

- [Mostly Adequate Guide](https://drboolean.gitbooks.io/mostly-adequate-guide-old/content/ch7.html#tales-from-the-cryptic)
- [What is Hindley-Milner?](https://stackoverflow.com/questions/399312/what-is-hindley-milner/399392#399392)

## Algebraic data type

A composite type made from putting other types together. Two common classes of algebraic types are [sum](#sum-type) and [product](#product-type).

### Sum Type

A Sum type is the combination of two types together into another one.
It is called sum because the number of possible values in the result type is the sum of the input types.

Rust has `enum` that literally represent `sum` in ADT.

```rust
enum WeakLogicValues {
   True(bool),
   False(bool),
   HalfTrue(bool),
}
// WeakLogicValues = bool + otherbool + anotherbool
```

### Product Type

A product type combines types together in a way you're probably more familiar with:

```rust
struct Point {
    x: i32,
    y: i32,
}
// Point = i32 x i32
```

It's called a product because the total possible values of the data structure is the product of the different values.
Many languages have a tuple type which is the simplest formulation of a product type.

See also [Set Theory](https://en.wikipedia.org/wiki/Set_theory)

**Further Reading**

- [ADT in 4 different languages](https://blog.softwaremill.com/algebraic-data-types-in-four-languages-858788043d4e)
- [What are Sum Product and Pi Types](https://manishearth.github.io/blog/2017/03/04/what-are-sum-product-and-pi-types/)

## Option

Option is a [sum type](#sum-type) with two cases often called Some and None.

Option is useful for composing functions that might not return a value.

```rust
let mut cart = HashMap::new();
let mut item = HashMap::new();
item.insert(
    "price".to_string(),
    12
);
cart.insert(
    "item".to_string(),
    item,
);

fn get_item(cart: &HashMap<String, HashMap<String, i32>>) -> Option<&HashMap<String, i32>> {
    cart.get("item")
}

fn get_price(item: &HashMap<String, i32>) -> Option<&i32> {
    item.get("price")
}

```

Use [and_then](https://doc.rust-lang.org/std/option/enum.Option.html#method.and_then) or [map](https://doc.rust-lang.org/std/option/enum.Option.html#method.map) to sequence functions that return Options

```rust
fn get_nested_price(cart: &HashMap<String, HashMap<String, i32>>) -> Option<&i32> {
    return get_item(cart).and_then(get_price);
}

let price = get_nested_price(&cart);

match price {
    Some(v) => assert_eq!(v, &12),
    None => panic!("T_T"),
}
```

`Option` is also known as `Maybe`. `Some` is sometimes called `Just`. `None` is sometimes called `Nothing`.

## Functional Programming references

- [Scala with Cats](https://underscore.io/books/scala-with-cats/)
- [Haskell Programming](http://haskellbook.com/)
- [Category Theory for Programmers](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/)
- [Category Theory Notes](http://cheng.staff.shef.ac.uk/catnotes/categorynotes-cheng.pdf)

## Functional Programming development in Rust Language

- [Higher Kinded Polymorphism RFC](https://github.com/rust-lang/rfcs/issues/324)
- [Currying in Rust](https://internals.rust-lang.org/t/currying-in-rust/10326)
- [Auto-Currying in Rust](https://internals.rust-lang.org/t/auto-currying-in-rust/149)

## My thought on this project

Please be mindful that the project does not fully cover every single definitions with code examples since it does not worth
investing too much time in a glossary project. I have put extra effort in adding complementary external references that
you can check out for further study.


text:
# TTGO ST7789 Driver for MicroPython #
This driver is based on [russhughes](https://github.com/russhughes/st7789_mpy) and [devbis](https://github.com/devbis/st7789_mpy) st7789_mpy driver. I modified the original driver for one of my projects to add:

- Text processing on the screen (display left, right, center up, down ...)
- Display of figures (square, rectangle, pentagon, circle, ellipse ... - filled and empty)
- on-screen **MENU** management
- **FTP** file transfer ([robert-hh](https://github.com/robert-hh/FTP-Server-for-ESP8266-ESP32-and-PYBD))

---

## WordProcessing.py ##
#### How to use the functions ####

start by importing the file

```import WordProcessing as wp```

Centers the text in the middle of the screen:

```CentreTxt(font, txt, ColorTxt, ColorFonTxt, ajust_x=0, ajust_y=0, rotation=3)```

Displays the text at the top left of the screen:

```LeftTopTxt(font, txt, ColorTxt, ColorFonTxt, ajust_x=0, ajust_y=0, rotation=3)```

Displays the text at the bottom left of the screen

```LeftBottomTxt(font, txt, ColorTxt, ColorFonTxt, ajust_x=0, ajust_y=0, rotation=3)```

Display the text at the top right of the screen:

```RightTopTxt(font, txt, ColorTxt, ColorFonTxt, ajust_x=0, ajust_y=0, rotation=3)```

Display the message at the bottom right of the screen:

```RightBottomTxt(font, txt, ColorTxt, ColorFonTxt, ajust_x=0, ajust_y=0, rotation=3)```

Displays the message with a carriage return:

```message(txt, ColorTxt, ColorFonTxt, rotation=3)```

**font** your font

**txt:** your text

**ColorTxt:** your text color

**ColorFonTxt:** your backgroud text color

**ajust_x (optional):** X-axis adjustment of x pixel

**ajust_y (optional):** Y-axis adjustment of y pixel

**rotation (optional):** screen position

license: MIT

branch_name: refs/heads/main

extension: md

license_type: permissive


text:
# Offline Invoicing
 Desktop invoicing app built with electron

**To Customize/Create your own installer**

- Clone this project.
- Open terminal and navigate into the cloned folder.
- Run "npm install" to install dependencies.
- Run "npm run electron".

branch_name: refs/heads/master


text:
# Advance Usage

## Introduction
I'd like to explain how to extend function of ``figpptx`` and
make it adopt to the user's preference.

Intrinsically, conversion from ``matplotlib`` to ``PowerPoint Object`` is
almost impossible to pursue perfect.
In addition, even if it is possible, I think the cost of them
does not match the benefit.

Instead, I believe that mechanism where users can modify the library
to their tastes are more practical and useful.

In Advance Usage,  I'd like to provide some examples as simple tutorials.
I'm happy you are interested in the library and extend it to make it your tool.

### Overview of ``figpptx``.

* When you want to modify **how** an Artists is converted to ``PowerPoint Object``,  you change ``converter function``.
* When you want to modify **what** Artist are converted as ``PowerPoint Object``, you change  ``Separator``.

That is the basic strategy of modification.

I hope the following tutorials help you to get the gist of strategies for modification.

* [Extension of transcribe ](./converter.md)
    - Explains how to extend ``converter functions``.
* [Tutorial for Separator]
    - Not yet,.

repository: Sillte/figpptx

gha_language: Python

gha_license_id: MIT

repo_name: Sillte/figpptx


text:
# Introduction

This guide covers tools that will help managing of your localization process. You may come across abbreviations TMS (translation management system) or CAT (computer-aided translation) that are sometimes used to describe these tools.

## Why use Sync & Collaboration Tools?

The easiest way to translate your application is to translate the `.po` files directly in a text editor, or with a tool like [Poedit](https://poedit.net).

This solution may be good enough when your application is still small and doesn't evolve much, but it quickly becomes hard work when the number of sentences to translate and the target languages to manage increase with time.

It then becomes more and more difficult and time-consuming to manage the back and forth with the translators, while keeping your application `.po` files up-to-date with the current state of a codebase that doesn't stop evolving.

That's why sync and collaboration tools are directly integrated into Lingui to help structure your work with your translators team, to ensure the consistency of the translations, and to make your life easier.

### Regular Workflow

![Translation workflow *without* sync and collaboration tool](/img/docs/without-collaboration-tool.png)

This is the most basic workflow which involves sending the `.po` files to your translators (usually by email) and syncing them back manually into your application.

This workflow is manageable when your application is still quite small, doesn't contain a lot of text, and doesn't evolve much.

### Sync & Collaboration Tool Workflow

![Translation workflow *with* sync and collaboration tool](/img/docs/with-collaboration-tool.png)

When the amount of text to translate increases, and the number of target languages grows, it becomes more efficient to use a sync and collaboration tool to assist you with the management of your team of translators, and co-evolution between your code and the translated files.

Instead of manually sending and receiving many emails and fixing the inconsistencies with your code, a `sync` method is called and your `.po` and `.js` files are directly updated with the latest translations. Your translators will also be notified when there are new text to translate.

## Benefits of these tools

- **Synchronization**: unique `yarn sync` or `npm run sync` command to synchronize your project with all your translators and update your local `.po` and `.js` files with the latest translations.
- **Translation Interface**: provide a professional and flexible interface to translators.
- **Translation Memory**: assist translators by suggesting previously translated sentences that are similar.
- **Machine Translation**: auto-translate with Google Translate, DeepL, etc. and human-proofread later.
- **Smart Plural Management**: allows to translate `Message` and `Messages` instead of `{count, plural, one {Message} other {Messages}}`.
- **Consistency**: assist translators with `{variable}` interpolation and HTML formatting.

## List of available tools

### [Crowdin](https://crowdin.com/?utm_source=lingui.dev&utm_medium=referral&utm_campaign=lingui.dev)

- Documentation: [Crowdin](/docs/tools/crowdin.md)
- GitHub: <https://github.com/crowdin>

### [Translation.io](https://translation.io/lingui)

- Documentation: [translation-io](/docs/tools/translation-io.md)
- GitHub: <https://github.com/translation/lingui>

repository: lingui/js-lingui

gha_language: TypeScript

repo_name: lingui/js-lingui


text:
# FTStackingPanels

FTStackingPanels is a [Unity 3D](https://unity3d.com) framework. It is created to design and manage game UI as the collection of presentable panels. Feedback events allow you to track presentation state and setup panel's content and animations accordingly.

![ftstackingpanels](https://cloud.githubusercontent.com/assets/25864772/26696204/3cd6d9a4-4716-11e7-80db-765f617bf7f9.gif)

## How To Get Started
- [Download FTStackingPanels](https://github.com/monofire/FTStackingPanels/archive/master.zip) project and try it out.
- Follow instructions below.

## Architecture:
![screen shot 2017-06-06 at 21 15 24](https://user-images.githubusercontent.com/25864772/26844830-60f4a114-4afd-11e7-8464-45c73f626619.png)

### UIPanel

`UIPanel` is designed to host all UI elements and has 4 stages of presentation flow.

**UIPanel event callbacks**
Each stage is represented with corresponding callback as described below.
Transition to the new stage is managed by `UIPanelsStack`. Every callback has a handler which allows moving to the next stage only when it is relevant (useful while dealing with asynchronous operations).

* * *
```c#
void onWillDisappear (Action onWillDisappearFinished)
```
Called when the panel is about to disappear from the visible area.
*Use this callback to provide your response to event and prepare to the next panel stage* *e.g save UI state to model*

`onWillDisappearFinished()` handler should be called to continue with next presentation stage.

* * *

```c#
void onDidDisappear (Action onDidDisappearFinished)
```
Called when the panel has already disappeared from the visible area.
*Use this callback to reconfigure UI objects on panel, release resources, start of stop game process, etc*

`onDidDisappearFinished ()` handler should be called to continue with next presentation stage.

* * *
```c#
void onWillAppear (UIPanel sender, Action onWillAppearFinished)
```
Called when the panel is not visible but is about to be shown.
*Use this callback to prepare UI objects to be presented, recover UI state from model*

`sender` provides name of game object which initiated this panel transition.
`onWillAppearFinished ()` handler should be called to continue with next presentation stage.

* * *
```c#
void onDidAppear (UIPanel sender, Action onDidAppearFinished)
```
Called when the panel has already appeared on the screen.

`sender` provides name of game object which initiated this panel transition.
`onDidAppearFinished ()` handler should be called to continue with next presentation stage.
* * *

**UIPanel animation objects**
Presentation flow of UI panel is managed by two animation objects.
The first object animates how panel appears on screen while the second object
animates how panel disappears from visible area.
It is up to you what animations to use. However, you must declare explicitly
start triggers of your animations in the following methods:

```c#
   void startAppearAnimation ()
   {
      /* set trigger that starts present animation */
      _animator.SetTrigger ("presentPanel");
   }

   void startDisappearAnimation ()
   {
      /* set trigger that starts hide animation */
      _animator.SetTrigger ("hidePanel");
   }
```

### UIPanelsStack

`UIPanelsStack` manages UIPanels transitions and routes events between different UIPanels.
***
***Constants***

```c#
 const string _UIPanelTag
```
Used to recognize `UIPanel` among other objects in the hierarchy.

```c#
  const string _initiallyPresentedPanelName
```
Used to recognize first `UIPanel` presented to a player.

```c#
  const string _alwaysActivePanelName
```
Used to recognize `UIPanel` that should be always active
 (pls. see UI Panels and performance).
***
***Attributes***
```c#
  UIPanel previousPanel
```
Points on previously presented `UIPanel`.

```c#
  UIPanel currentPanel
```
Points on currently presented `UIPanel`.

```c#
  Dictionary <string, UIPanel> panels
```
Contains pointers on all panels and panels names.

***
***Methods***

```c#
void presentTarget (string targetName,
                    Action onTransitionToTargetFinishedNullable)
```
Presents target panel without transition to other panel.
`onTransitionToTargetFinishedNullable ()` handler is called when transition is finished (optional)
 * * *
```c#
    void hideTarget (string targetName,
                     Action onHideTargetTransitionFinishedNullable)
```
Hides target panel.
`onTransitionToTargetFinishedNullable ()` handler is called when transition is finished (optional)
 * * *
```c#
    void present (string senderName,
                  string targetName,
                  Action onTransitionToTargetFinishedNullable)
```
Hides sender panel and presents target panel.
`onTransitionToTargetFinishedNullable ()` handler is called when transition is finished (optional)
* * *

***UI Panels and performance***
It is suggested to notify UIPanelsStack when you are using / not using your UI panels on Scene,  to free up resources and decrease number of draw-calls.

 * * *

```c#
    void activateUIPanels()
```
Activates all panels.

* * *

```c#
    void activateUIPanels()
```
Deactivates all panels except the one stated in `_alwaysActivePanelName` const.
* * *

## Usage

1. Scene setup
1.1 Set Main Camera's "Projection" attribute  to "Orthographic".
1.2 Create and add Canvas game object as a child of the Main Camera.
1.3 Add UIPanelStack.cs script to the Canvas object.
1.4 Create and add Panel object as a child of Canvas.
1.5 Subclass `UIPanel` and add this subclassed script to your panel.

2. UIPanelsStack.cs script setup
2.1 Set `_UIPanelTag` const with your panel tag e.g "UIPanel".
Set this tag for all your Panels, to allow UIPanelStack.cs script recognize and manage all Panel objects.
2.2. Set `_initiallyPresentedPanelTag` const with the name of the panel that will be presented to the player in the first order e.g. "MainMenuPanel".
2.3 Set `_alwaysActivePanelName` const with the name of the panel that should be always active e.g. "GameScenePanel".
(Please see ***UI Panels and performance*** for the detailed explanation).

3. Panel animations setup
3.1 Add Animator to the Panel in order to manage panel's "hide" and "present" animations.
3.2 Create animation controller and your "hide" and "present" animations.
3.3 Add corresponding triggers e.g. "presentPanel" and "hidePanel" to your animations.
This triggers will be called from your UIPanel subclass.
3.4 Add an event in the end of your "present" animation and link it to the onAppearAnimationFinished() method of UIPanel.
3.5 Add an event in the end of your "hide" animation and link it to the onDisappearAnimationFinished() method of `UIPanel`.
![screen shot 2017-06-05 at 19 54 38](https://user-images.githubusercontent.com/25864772/26844747-23538cd0-4afd-11e7-821f-bcc55dfbc591.png)

4. UIPanel.cs script setup
4.1 override `startAppearAnimation ()`method in your `UIPanel` subclass: "presentPanel" animation trigger should be called from this method.
e.g `_animator.SetTrigger ("presentPanel");`
4.2 override `startDisappearAnimation ()` method in your `UIPanel` subclass:
"hidePanel" animation trigger should be called from this method.
e.g `_animator.SetTrigger ("hidePanel");`
4.3 Override UIPanels's methods described in ***UIPanel event callbacks*** section and use them according to your tasks.

Repeat steps 1.3 - 3.2 for all the number of panels you plan to use.

## License
This project is licensed under the MIT License - see the LICENSE.md file for detail


text:
463\. Island Perimeter

Easy

You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water.

Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).

The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.

**Example 1:**

![](https://assets.leetcode.com/uploads/2018/10/12/island.png)

**Input:** grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]

**Output:** 16

**Explanation:** The perimeter is the 16 yellow stripes in the image above.

**Example 2:**

**Input:** grid = [[1]]

**Output:** 4

**Example 3:**

**Input:** grid = [[1,0]]

**Output:** 4

**Constraints:**

*   `row == grid.length`
*   `col == grid[i].length`
*   `1 <= row, col <= 100`
*   `grid[i][j]` is `0` or `1`.
*   There is exactly one island in `grid`.

repository: javadev/LeetCode-in-Java

gha_language: Java

repo_name: javadev/LeetCode-in-Java


text:
# VBA Control Array

Add the power of control arrays to VBA and simplify event handling.

Here is a list of the controls that can be added to the control array collection.
```
Checkbox
Combobox
CommandButton
Frame
Image
Label
ListBox
MultiPage
OptionButton
ScrollBar
SpinButton
TabStrip
TextBox
ToggleButton
```
### Prerequisites

Any VBA product that uses Microsoft Forms 2.0 library by default.  Tested to work with Excel and Word, 2010-2016.  Microsoft Access will not work with this code, use [vba-msaccess-controlarray](https://github.com/bohicajr/vba-msaccess-controlarray) for code compatible with Access.

### Quick Start
Download one of the blank templates from the quickstart folder, there is an [Excel](https://github.com/bohicajr/vba-controlarray/blob/master/quickstart/VBA-ControlArray_Blank.xlsm) and [Word](https://github.com/bohicajr/vba-controlarray/blob/master/quickstart/VBA-ControlArray_Blank.docm) version available. Ensure that you have macros enabled.

### Manual Install

Download all the .cls files from github and import the files into your VBA project.
**Copy and paste will not work!**

Here is a list of the class files you must import into the VBA IDE.

```
CACheckbox.cls
CACombobox.cls
CACommandButton.cls
CAFrame.cls
CAImage.cls
CALabel.cls
CAListBox.cls
CAMultiPage.cls
CAOptionButton.cls
CAScrollBar.cls
CASpinButton.cls
CATabStrip.cls
CATextBox.cls
CAToggleButton.cls
ControlArray.cls
IControl.cls
```

### Basic Example
Add a user form to your VBA project and add as many command buttons as you want, then add the following code behind the form.

```VBA
Option Explicit

Private WithEvents Buttons as ControlArray

Private Sub UserForm_Initialize()

    Set Buttons = ControlArray.Create(Me.Controls)

End Sub

Private Sub Buttons_onClick(ctl As IControl)

    MsgBox "You clicked the button " & ctl.Name

End Sub
```

note that after you add the line that has WithEvents, that in the editor you now can choose the Buttons object, and select from it's many events to handle.  Every event also sends back a reference to the object that raised it!

### Known Issues

- AfterUpdate, BeforeUpdate, Enter and Exit events are not available. this is a limitation of MSForms and VBA.  If you want to use those events you'll have to work with them in the traditional manor.

- Frames, MultiPage and TabStrip have several events that are slightly unique in its parameters, you have to listen for their distinctive events.

### Inspiration
[Rubberduck VBA: Factories](https://rubberduckvba.wordpress.com/2016/07/05/oop-vba-pt-2-factories-and-cheap-hotels/) influenced the style that I used in writing this code.  Strongly recommend reading this article.

repository: bohicajr/vba-controlarray

repo_name: bohicajr/vba-controlarray


text:
# gethostbyname

If you do a gethostbyname() and there is no trailing dot after a domainname that does not resolve, this domainname will ultimately be appended to the server-FQDN by nslookup.

So if you do a lookup for nonexistentdomainname.be your server may return the ip for nonexistentdomainname.be.yourhostname.com, which is the server-ip.

To avoid this behaviour, just add a trailing dot to the domainname; i.e. gethostbyname('nonexistentdomainname.be.')

---

Options for the underlying resolver functions can be supplied by using the RES_OPTIONS environmental variable. (at least under Linux, see man resolv.conf)

Set timeout and retries to 1 to have a maximum execution time of 1 second for the DNS lookup:

```
<?php
  putenv('RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1');
  gethostbyname($something);
?>
```

You should also use fully qualified domain names ending in a dot. This prevents the resolver from walking though all search domains and retrying the domain with the search domain appended.

---

This function says "Returns the IPv4 address or a string containing the unmodified hostname on failure.

This isn't entirely true, any hostname with a null byte in it will only return the characters BEFORE the null byte.

```
<?php
$hostname = "foo\0bar";
var_dump($hostname );
var_dump(gethostbyname($hostname ));
?>
```

Results:
string 'foo�bar' (length=7)
string 'foo' (length=3)

---

Important note: You should avoid its use in production.

DNS Resolution may take from 0.5 to 4 seconds, and during this time your script is NOT being executed.

Your customers may think that the server is slow, but actually it is just waiting for the DNS resolution response.

You can use it, but if you want performance, you should avoid it, or schedule it to some CRON script...

---

[Official documentation page](https://www.php.net/manual/en/function.gethostbyname.php)

**[To root](/README.md)**


text:
# Raymarcher-rs

A Rust implementation of the raymarching algorithm.

Comes with a few primitives and implementors.

# Features
1. Basic primitives (cube, sphere, half plane)
1. Union, intersect, difference
1. Translation, uniform scaling
1. Phong shading
1. Reflections
1. Point lights
1. Rotations

# TODO
1. Materials with the current point as input
1. Refraction
1. Figure out where the color banding/reflection waves come from
1. More light types

# Sources/inspiration
* https://raytracing.github.io/books/RayTracingInOneWeekend.html (correct camera code)
* http://jamie-wong.com/2016/07/15/ray-marching-signed-distance-functions/ (basic principles)
* https://iquilezles.org/ (primitives, combinators, soft shadows)
* https://en.wikipedia.org/ (Phong shading, vector laws)
* Random forum/Reddit posts I forgot about.

repository: TVerse/raymarcher-rs

repo_name: TVerse/raymarcher-rs


text:
For an integer k rearrange all the elements of the given array in such way, that:

all elements that are less than k are placed before elements that are not less than k; all elements that are less than k remain in the same order with respect to each other; all elements that are not less than k remain in the same order with respect to each other. Example

For k = 5 and array [1, 3, 5, 7, 6, 4, 2] the answer will be [1, 3, 4, 2, 5, 7, 6].

[input] integer k

[input] array.integer elements

[output] array.integer


text:
Notes for message tracing for Proton based applications
=======================================================

- Assumption - we are going to use Jaeger as our tracing backend
  - As far as clients are concerned they use the OpenTracing API

- Consideration - where do tracing "ids" (spans) come from?
  - Really generating spans is an application level concern
  - Passing the tracing context around between elements of the distributed app is function of both tracing library and amqp implementation
  - Implement Inject/Extract capability for specific message transports.
  - Don't want to continually alter messages as they pass through routers and intermediaries as this may be expensive.
  - So do we record a span for messages passing through router/broker?
    - It's not obvious that we should as how would you choose the span name in other words this is perhaps not a real application level event.
    - Although you do want visibility of the time spent queuing/transitioning the interconnect
      - How would it work with istio?

  - So really want to generate when message is originally generated or piggyback on another
   identifier
  - Is there any AMQP TC consensus on how the tracing context gets attached to AMQP messages?

- What is the deliverable?
  - Demo?
  - Some sort of proton integration with Jaeger so that apps can pass around the tracing context?
  - New code in router/broker to record spans?
  - Some AMQP TC agreement/proposal for tracing context interoperation?

- C implementation og OpenTracing API
  - https://github.com/opentracing/opentracing-c

- Google Dapper
  - Google comment in their paper that they can use the tracing without explicit extra programming in the applications. They also talk about instrumenting low level libraries (used for amongst other things threading).

  - This is only possible because they already have an RPC abstraction/abstractions that they can instrument to form the spans and the relationships between them implicitly because of the flow of RPC events into various asynchronous executions (local and remote)

  - This is not currently possible for us as we have no such RPC abstraction (At least in proton-c or anything using it).

  - Maybe Some things in Java land have such an abstraction - Vrtx? In which case we could build some infrastructure like google to automatically put together RPC traces without application programmer overhead.

  - Even for the Google case (in 2010 at least) they comment that some number of their own systems use direct TCP or custom communication schemes and so can't transparently use the Dapper framework. These applications need some glue to connect to the Dapper tracing - we are currently in this situation.

  - *We should very definitely consider producing an RPC framework that can do OpenTracing transparently*
    - This would obviously require us to implement hooks into proton that can inject and extract tracing ids which is prerequisite for users to do the application work.
    - But we could also introduce our own RPC implementation using AMQP (or actually whatever) that transparently introduces the trace ids and transfers them over the network so that tracing can be performed.

- Possible steps
  1. Prototype code that can inject/extract tracing ids from AMQP messages
     - Seems like this might be an addition to proton-c reusable by any of its users/
  2. New code in router/broker (elsewhere too? - EnMaas?) which uses the trace ids of incoming/outgoing messages to record trace spans for them as they are read from the network/queued and dequeued and written to the network.
     - Obviously the precise spans recorded here will depend on the exact function of the network element.
     - Any extra operations occuring to support the spans from incoming messages (for example messages sent for authentication or message routing purposes) should be recorded as related spans (hopefully in some way that can be automatic)
  3. Produce some sort of RPC mechanism that renders span generation automatic.

- Some light dawns!
  We actually need *two* separate inter-related pieces
  - The tracing part which supports the OpenTracing API interfaces - inject/extract to the underlying protocol to pass the SpanContexts around.
  - And the Jaeger specific part which passes the actual tracing info to the Jaeger agent (and is configured by it).

- Useful/Interesting External Sources
  - Events or Spans? The Opentracing API uses spans, but events maybe more natural and useful: https://medium.com/opentracing/open-for-event-based-tracing-a326c295f2a2
  - Dapper paper: https://ai.google/research/pubs/pub36356
  - Opentracing Project: https://opentracing.io/
  - Opentracing Project Specification: https://opentracing.io/specification/
  - W3C Distributed Tracing Spec: https://www.w3.org/2018/distributed-tracing/
  - W3C AMQP Trace Context Spec: https://github.com/w3c/trace-context-amqp

repository: astitcher/qpid-proton-tracing

repo_name: astitcher/qpid-proton-tracing


text:
---
currentMenu: current-limitation
---

## Current limitations

This package uses [voodoo magic](http://ocramius.github.io/voodoo-php/) to
operate, specifically [go-aop-php](https://github.com/lisachenko/go-aop-php).

Go AOP PHP has some limitations when it comes to intercepting access to
private class members, so please be aware that it has limited scope (for now).

This package only works against autoloaded classes; classes that aren't handled by
an autoloader cannot be rectified by StrictPhp.

repository: jaapio/StrictPhp

repo_name: jaapio/StrictPhp


text:
I have an ASP.Net Core project that I build with VSTS. It is deployed to Azure through a CI / CD setup in VSTS. That part I'm happy with. Proud of even. Now to the sordid hiddenness: try as I might, I've never found a nice way to deploy Entity Framework database migrations as part of the deployment flow. So I have [blushes with embarrassment] been using the `Startup` of my ASP.Net core app to run the migrations on my database. There. I said it. You all know. Absolutely filthy. Don't judge me.

 If you care to google, you'll find various discussions around this, and various ways to tackle it. Most of which felt like too much hard work and so I never attempted.

It's also worth saying that being on VSTS made me less likely to give these approaches a go. Why? Well, the feedback loop for debugging a CI / CD setup is truly sucky. Make a change. Wait for it to trickle through the CI / CD flow (10 mins at least). Spot a problem, try and fix. Start waiting again. Repeat until you succeed. Or, if you're using the free tier of VSTS, repeat until you run out of build minutes. You have a limited number of build minutes per month with VSTS. Last time I fiddled with the build, I bled my way through a full month's minutes in 2 days. I have now adopted the approach of only playing with the setup in the last week of the month. That way if I end up running out of minutes, at least I'll roll over to the new allowance in a matter of days.

Digression over. I could take the guilt of my EF migrations secret no longer, I decided to try and tackle it another way. I used the approach suggested by [Andre Broers](https://github.com/broersa)[here](https://github.com/aspnet/EntityFrameworkCore/issues/9841#issuecomment-395712061):

> I worked around by adding a dotnetcore consoleapp project where I run the migration via the Context. In the Build I build this consoleapp in the release I execute it.

## Console Yourself

First things first, we need a console app added to our solution. Fire up PowerShell in the root of your project and:

```console
md MyAwesomeProject.MigrateDatabase
cd .\MyAwesomeProject.MigrateDatabase\
dotnet new console
```

Next we need that project to know about Entity Framework and also our DbContext (which I store in a dedicated project):

```console
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add reference ..\MyAwesomeProject.Database\MyAwesomeProject.Database.csproj
```

Add our new project to our solution: (I always forget to do this)

```console
cd ../
dotnet sln add .\MyAwesomeProject.MigrateDatabase\MyAwesomeProject.MigrateDatabase.csproj
```

You should now be the proud possessor of a `.csproj` file that looks like this:

```xml
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.1" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\MyAwesomeProject.Database\MyAwesomeProject.Database.csproj" />
  </ItemGroup>

</Project>
```

Replace the contents of the `Program.cs` file with this:

```cs
using System;
using System.IO;
using MyAwesomeProject.Database;
using Microsoft.EntityFrameworkCore;

namespace MyAwesomeProject.MigrateDatabase {
    class Program {
        // Example usage:
        // dotnet MyAwesomeProject.MigrateDatabase.dll "Server=(localdb)\\mssqllocaldb;Database=MyAwesomeProject;Trusted_Connection=True;"
        static void Main(string[] args) {
            if (args.Length == 0)
                throw new Exception("No connection string supplied!");

            var myAwesomeProjectConnectionString = args[0];

            // Totally optional debug information
            Console.WriteLine("About to migrate this database:");
            var connectionBits = myAwesomeProjectConnectionString.Split(";");
            foreach (var connectionBit in connectionBits) {
                if (!connectionBit.StartsWith("Password", StringComparison.CurrentCultureIgnoreCase))
                    Console.WriteLine(connectionBit);
            }

            try {
                var optionsBuilder = new DbContextOptionsBuilder<MyAwesomeProjectContext>();
                optionsBuilder.UseSqlServer(myAwesomeProjectConnectionString);

                using(var context = new MyAwesomeProjectContext(optionsBuilder.Options)) {
                    context.Database.Migrate();
                }
                Console.WriteLine("This database is migrated like it's the Serengeti!");
            } catch (Exception exc) {
                var failedToMigrateException = new Exception("Failed to apply migrations!", exc);
                Console.WriteLine($"Didn't succeed in applying migrations: {exc.Message}");
                throw failedToMigrateException;
            }
        }
    }
}
```

This code takes the database connection string passed as an argument, spins up a db context with that, and migrates like it's the Serengeti.

## Build It!

The next thing we need is to ensure that this is included as part of the build process in VSTS. The following commands need to be run during the build to include the MigrateDatabase project in the build output in a `MigrateDatabase` folder:

```cs
cd MyAwesomeProject.MigrateDatabase
dotnet build
dotnet publish --configuration Release --output $(build.artifactstagingdirectory)/MigrateDatabase
```

There's various ways to accomplish this which I wont reiterate now. [I recommend YAML](./2018-06-16-vsts-yaml-up.md).

## Deploy It!

Now to execute our console app as part of the deployment process we need to add a CommandLine task to our VSTS build definition. It should execute the following command:

```cs
dotnet MyAwesomeProject.MigrateDatabase.dll "$(ConnectionStrings.MyAwesomeProjectDatabaseConnection)"
```

In the following folder:

```cs
$(System.DefaultWorkingDirectory)/my-awesome-project-YAML/drop/MigrateDatabase
```

Do note that the command uses the `ConnectionStrings.MyAwesomeProjectDatabaseConnection` variable which you need to create and set to the value of your connection string.

![](../static/blog/2018-06-24-vsts-and-ef-core-migrations/Screenshot%2B2018-06-24%2B10.55.27.png)

## Give It A Whirl

Let's find out what happens when the rubber hits the road. I'll add a new entity to my database project:

```cs
using System;

namespace MyAwesomeProject.Database.Entities {
    public class NewHotness {
        public Guid NewHotnessId { get; set; }
    }
}
```

And reference it in my DbContext:

```cs
using MyAwesomeProject.Database.Entities;
using Microsoft.EntityFrameworkCore;

namespace MyAwesomeProject.Database {
    public class MyAwesomeProjectContext : DbContext {
        public MyAwesomeProjectContext(DbContextOptions<MyAwesomeProjectContext> options) : base(options) { }

        // ...

        public DbSet<NewHotness> NewHotnesses { get; set; }

        // ...
    }
}
```

Let's let EF know by adding a migration to my project:

```cs
dotnet ef migrations add TestOurMigrationsApproach
```

Commit my change, push it to VSTS, wait for the build to run and a deployment to take place.... Okay. It's done. Looks good.

![](../static/blog/2018-06-24-vsts-and-ef-core-migrations/Screenshot%2B2018-06-24%2B09.02.22.png)

Let's take a look in the database:

```console
select * from NewHotnesses
go
```

![](../static/blog/2018-06-24-vsts-and-ef-core-migrations/Screenshot%2B2018-06-24%2B08.59.00.png)

It's there! We are migrating our database upon deployment; and not in our ASP.Net Core app itself. I feel a burden lifted.

## Wrapping Up

The EF Core team are aware of the lack of guidance around deploying migrations and have recently announced plans to fix that in the docs. You can track the progress of this issue [here](https://github.com/aspnet/EntityFramework.Docs/issues/691). There's good odds that once they come out with this I'll find there's a better way than the approach I've outlined in this post. Until that glorious day!


text:
---
date: 2020-01-29
title: Tool Window Management
technologies: [.net]
products: [rider]
topics: [ide]
author: matkoch
subtitle: Little helpers always at the right size!
thumbnail: ./thumbnail.png
cardThumbnail: ./card.png
animatedGif:
  file: './guide.gif'
  width: 500
leadin: |
    **Too little space to work with?** 🤨

    If you find yourself frequently resizing tool windows like for VCS or the terminal, then you should try one of the following:

    - With the **Undock** view mode a tool window will automatically hide as soon as it loses focus.
    - Using the **Maximize/restore tool window** action will put the active tool window at maximum available space, and will restore to the previous size on the second call.

    Try it now! 🤓

    ### See Also
    - [Rider - Working with Tool Windows](https://www.jetbrains.com/help/rider/Tool_Windows.html)
    - [Rider - Window Layout Manager plugin](https://plugins.jetbrains.com/plugin/13005-window-layout-manager)
---


text:
---
name: Feature Request
about: New Feature Request
title: 'Add/Implement :functionality: in :section: '
labels: Feature
assignees: smurtazakazmi

---

**Overview**
Add any other context or screenshots about the feature request here.

**Is your feature request related to a problem? Please describe.**
Yes/No,  if yes, provide a clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Screenshot/Mock-up**
Provide screenshot or mock-up if available.

**Container**
- Name: Container Name
- Endpoint:  API Endpoint
- Authentication: Required / Not Required

**Feature Breakdown**
- [ ] Add field
- [ ] Update Service
- [ ] Update store etc

**Side effects**
Provide any details, if this feature can effect any existing functionality, also describe possible solutions to these side effects.


text:
---
title: GitHub Pages Deployment
layout: en
permalink: /user/deployment/pages/
---

> Deploying to GitHub Pages uses `git push --force` to overwrite the history on the *target* branch, so make sure you only deploy to a branch used for that specific purpose, such as `gh-pages`.

Travis CI can deploy your static files to [GitHub
Pages](https://pages.github.com/) after a successful build.

You will need to provide a [personal access
token](https://help.github.com/articles/creating-an-access-token-for-command-line-use/)
and set the deployment provider details in `.travis.yml`.

For a minimal configuration, add the following to your `.travis.yml`:

```yaml
deploy:
  provider: pages
  skip_cleanup: true
  github_token: $GITHUB_TOKEN # Set in travis-ci.org dashboard
  on:
    branch: master
```

> Make sure you have `skip_cleanup` set to true, otherwise Travis CI will delete
> all the files created during the build, which will probably delete what you are
> trying to upload.

## Setting the GitHub token

You'll need to generate a [personal access
token](https://help.github.com/articles/creating-an-access-token-for-command-line-use/)
with the `public_repo` or `repo` scope (`repo` is required for private
repositories). Since the token should be private,
you'll want to pass it to Travis securely in your [repository
settings](https://docs.travis-ci.com/user/environment-variables#Defining-Variables-in-Repository-Settings)
or via [encrypted variables in
`.travis.yml`](https://docs.travis-ci.com/user/environment-variables#Defining-encrypted-variables-in-.travis.yml).

## Further configuration

* `local_dir`: Directory to push to GitHub Pages, defaults to the current
    directory
* `repo`: Repo slug, defaults to current repo
* `target_branch`: Branch to push force to, defaults to `gh-pages`
* `fqdn`: Optional, sets a custom domain for your website, defaults to no custom domain support.
* `project_name`: Defaults to value of `fqdn` or repo slug, used for metadata
* `email`: Optional, committer info, defaults to<EMAIL_ADDRESS>* `name`: Optional, committer, defaults to `Deployment Bot`

gha_language: HTML


text:
title: Venue
---

## The venue

The conference will be held at [Cardiff City Hall](http://www.cardiffcityhall.com/find-us), Cathays Park, Cardiff CF10 3ND

### Accessibility

The venue is accessible for people of limited mobility. If you need to park near the venue because of mobility issues, please [contact us](/contact/) and we'll do our best to help.

## Accommodation in Cardiff

See [Accommodation](/accommodation/) for recommended hotels and other places to stay.

## Getting to Cardiff

### Trains

Trains to Cardiff arrive right in the city centre, at Cardiff Central railway station.

Rail travel in the UK can be very expensive, especially if you don’t buy your tickets until you travel. For much cheaper fares:

* buy your tickets about twelve weeks in advance, when the cheapest Advance Single tickets are released
* note that travel at off-peak times will be cheaper
* ... and that buying two singles can sometimes be cheaper than buying a return ticket

### Buses

Cardiff Central Bus Station is closed until late 2017, but most if not all services will stop near the city centre, on Castle Street so you shouldn't be inconvenienced (in fact, the Castle Street stop is closer to the venue). Just be aware of where your bus will be arriving and leaving from!

[National Express](http://nationalexpress.com) has some good services to Cardiff, but check for services provided by other lines.

### Planes

Cardiff's pocket-sized airport has daily flights from several European cities.  It's extremely convenient if you can find a flight that lands there. A bus into town (~35 minutes) from the airport is about £5; a taxi (~20 minutes) will be about £25.

Bristol Airport is a larger and served by more flights. A [National Express](http://nationalexpress.com) bus will take you to the centre of Cardiff in about 1 hour 40 minutes, for about £20.

Birmingham Airport is about two hours away by train. The trip requires a change at Birmingham New Street station.

Flights from London Heathrow have reasonable connections by bus. Other London airports are further away. Avoid flying to London Stansted or Luton airports unless you have to. Getting from there to Cardiff will be an unrewarding experience.

### Cars

There's limited parking in the city centre, and you'll pay for the privilege.  However, if you need to use a car because of mobility issues, please contact us.


text:
dansguardian [![CircleCI](https://circleci.com/gh/double16/dansguardian.svg?style=svg&circle-token=9482bcf116b2564ced24bda33b0876acbbbb5621)](https://circleci.com/gh/double16/dansguardian)
============

[![](https://images.microbadger.com/badges/image/pdouble16/dansguardian.svg)](http://microbadger.com/images/pdouble16/dansguardian "Get your own image badge on microbadger.com") [![](https://images.microbadger.com/badges/version/pdouble16/dansguardian.svg)](http://microbadger.com/images/pdouble16/dansguardian "Get your own version badge on microbadger.com") [![](https://images.microbadger.com/badges/commit/pdouble16/dansguardian.svg)](http://microbadger.com/images/pdouble16/dansguardian "Get your own version badge on microbadger.com") [![](https://images.microbadger.com/badges/license/pdouble16/dansguardian.svg)](http://microbadger.com/images/pdouble16/dansguardian "Get your own version badge on microbadger.com")

Container for DansGuardian, a web content filter.

This container is intended to be used as a base image. The configuration is stock from the Ubuntu packages. `/etc/dansguardian/*` needs to be configured for your use case. This container configuration uses all of the blacklists from shallalist.de, which makes it very restrictive. You might try http://www.myip.com for a site that is not blocked.

A sample blacklist config for shallalist is in `/blacklists/bannedsitelist`, `/blacklists/bannedurllist`. These files are not referenced by the dansguardian config. They are provided to show the total available blacklists provided by shallalist.de and are updated each time the blacklist is downloaded via cron.

Features:
 - dansguardian + squid + blacklist update from shallalist.de
 - See Copyright at http://www.shallalist.de for use of this container
 - Port 3128 is the content filtered proxy port
 - Port 8123 is the caching only proxy port
 - Port 8124 is the transparent caching only proxy port
 - `http://*:8125/reports` holds web usage reports stored at `/log/sarg`
 - Volume `/log` for holding log files
 - Volume `/cache` for holding the squid cache
 - Volume `/blacklists` for persisting black list updates across re-creating of the container
 - Enviroment `SERVERNAME` for the name or IP of the proxy server, by default uses the value of `hostname` in the container

gha_language: Shell


text:
# *HDHR-DVRUI+*
PHP Server Application for managing your home networks HDHomeRun DVR(s) from SiliconDust including post-processing and enhanced scheduling

![Advanced Rule](HDHomeRun_DVR_UI_EditRule.png)

This fork was done to make changes specific to the fine app by [demonrik](https://github.com/demonrik) and [avandeputte](https://github.com/avandeputte) that fell outside of the scope of the original project.
My setup uses a powerful Ubuntu server (8 core Xeon 2 GB VM) to record, post-process, archive to a NAS and notify Plex of the new video.
The UI has been modified to allow for post processing of the video content including commercial removal, archiving, transcoding and cleanup of the incoming video content.

### After a base installation of Ubuntu Server I ran the following:

### install file monotoring [iWatch](http://iwatch.sourceforge.net/index.html) (not Apple)
    wget http://ftp.debian.org/debian/pool/main/i/iwatch/iwatch_0.2.2-5_all.deb
    sudo dpkg -i iwatch_0.2.2-5_all.deb
    sudo apt-get install -f

### install commercial removal: [comskip](http://www.kaashoek.com/comskip/)
    git clone git://github.com/erikkaashoek/Comskip
    cd Comskip
    ./autogen.sh
    ./configure
    make

### install transcoding: [FFmpeg](https://www.ffmpeg.org/)
    sudo add-apt-repository ppa:mc3man/trusty-media
    sudo apt-get install ffmpeg

### install file renaming for Plex to get episode title: [Python/PyQuery](https://pythonhosted.org/pyquery/)
    sudo apt-get install libxml2-dev libxslt1-dev python-dev
    sudo pip install pyquery

### install apache
    sudo apt-get install apache2

### install HDHR-DVRUI to the Apache directory
    git clone git://github.com/phillipssc/HDHR-DVRUI.git
    sudo cp HDHR-DVRUI/app/bin/postprocess.sh /usr/bin/
    sudo cp HDHR-DVRUI/app/bin/postprocessclean.sh /usr/bin/
    sudo cp HDHR-DVRUI/app/bin/postprocessvars.sh /usr/bin/
    sudo cp HDHR-DVRUI/app/bin/postprocesswatch.sh /usr/bin/
    sudo cp HDHR-DVRUI/app/bin/postprocessname.py /usr/bin/
    sudo cp HDHR-DVRUI/app/cfg/postprocess.conf /etc/
    sudo cp HDHR-DVRUI/app/index.html /var/www/html/
    sudo mv HDHR-DVRUI /var/www/html/

### grant permissions to the web client
    sudo visudo
    #add the following to the bottom and save:
    www-data        LOCAL=NOPASSWD:/usr/sbin/service
    www-data        LOCAL=NOPASSWD:/bin/mkdir
    www-data        LOCAL=NOPASSWD:/usr/bin/nohup
    www-data        LOCAL=NOPASSWD:/usr/bin/setsid
    www-data        LOCAL=NOPASSWD:/bin/bash
    www-data        LOCAL=NOPASSWD:/bin/df
    www-data        LOCAL=NOPASSWD:/usr/bin/uptime
    www-data        LOCAL=NOPASSWD:/usr/bin/postprocessvars.sh
    www-data        LOCAL=NOPASSWD:/usr/bin/postprocess.sh

### set up the background tasks
    sudo crontab -e
    #add the following to the bottom and save:
    0,30 * * * * /usr/bin/postprocessclean.sh
    */5 * * * * /usr/bin/postprocesswatch.sh

### update the settings
    sudo nano /etc/postprocess.conf
    #You will need to update the Plex values with those from your own server.   The best way that I have found to get the token value is to use your browser to inspect the "scan" icon on any of the plex screens

I rotate my local recordings using the postprocessclean.sh routine run every half hour by cron.   The script deletes videos older than a week, if I want to keep them longer I archive them.
The postprocesswatch.sh script watches for and kills hung ffmpeg processes.   It is configurable through /etc/postprocess.conf
The postprocessvars.sh script is used by the web application to read variables from /etc/postprocess.conf.
The postprocess.sh script is the workhorse that does the post-processing.

The web application, for the most part, sets the iWatch configuration file /etc/iwatch/iwatch.xml to watch over the various directories and act on files after they are done being written.  This invokes the postprocess.sh script using the desired parameters to do the task.   The web app also will invoke the postprocess.sh script directly on the existing recordings.
The web application also shows the server stats: disk space usage on the temp, recording and plex mounts as well as the server load.

Finally, scheduling was enhanced.   Dropdowns replace the guesswork of date time and channel selection for any show.   You can now edit an existing rule easily and, of course, add post-processing options to it.

Original README:

**Release binaries are [here](https://github.com/demonrik/HDHR-DVRUI/releases)**

This project is a spin off of the contributions made to the QNAP installer package for Silicondust DVR located at [dvr_install](https://github.com/Silicondust/dvr_install)
These contributions were from both [demonrik](https://github.com/demonrik) and [avandeputte](https://github.com/avandeputte)

After a few additions to the UI for that project we concluded that we were starting to exceed the initial goal of creating a UI to manage the installed record engine.
Thus we decided to reduce the QNAP install package UI down to those features required for management of the local Record Engine and create this project to allow us to innovate on more fatures as a stand alone web server application.

Most of the features for interaction are documented by Silicondust at their documention's repo [wiki](https://github.com/Silicondust/documentation/wiki)
Others have been gleaned from looking at the Kodi plugin, and also some helpful tips from others on the Silicondust [forum](https://www.silicondust.com/forum).
Documentation is still in flux, and the DVR record engine has yet to see a full release. Thus features are subject to change.

repository: phillipssc/HDHR-DVRUI

repo_name: phillipssc/HDHR-DVRUI


text:
# astro

Common astronomical utilities, with a focus on galaxy cluster analyses

(c) Cristóbal Sifón, 2013-2018

---

*This package has been developed following my own interests and requirements and is made public here as-is. Some portions of it may be incomplete or (partially) untested, and I cannot guarantee that it will work in other operating systems or python versions*

---

repository: arosbunster-cami/astro

repo_name: arosbunster-cami/astro


text:
# Go Emoji Sanitizer
![tests](https://github.com/DaRealFreak/emoji-sanitizer/workflows/tests/badge.svg?branch=master) [![Coverage Status](https://coveralls.io/repos/github/DaRealFreak/emoji-sanitizer/badge.svg?branch=master)](https://coveralls.io/github/DaRealFreak/emoji-sanitizer?branch=master) ![GitHub](https://img.shields.io/github/license/DaRealFreak/emoji-sanitizer) [![Go Report Card](https://goreportcard.com/badge/github.com/DaRealFreak/emoji-sanitizer)](https://goreportcard.com/report/github.com/DaRealFreak/emoji-sanitizer)

go library to detect unicode emoji runes and to sanitize them.

## Usage
The usage is fairly simple. You generate a sanitizer and can sanitize passed strings.
A minimalistic usage:
```go
sanitizer, err := NewSanitizer()
// this will return "Test string [e][e][e] [e]"
sanitizer.ReplaceUnicodeEmojis("Test string 😆😆😆 😛", "[e]")
// this will return: "Test string  "
sanitizer.StripUnicodeEmojis("Test string 😆😆😆 😛")
```

You can also set multiple options to further configure the sanitization.

## Options
### Set custom unicode version
You can simply set the unicode version with the UnicodeVersion option:
```go
sanitizer, err := NewSanitizer(
    options.UnicodeVersion(VersionLatest),
)
```

currently offline available are following versions:
1.0, 2.0, 3.0, 4.0, 5.0, 11.0, 12.0, 12.1, 13.0, 13.1
All of those are taken from https://unicode.org/Public/emoji/

If you are using the online option you can also instantly use other versions when they get released.

By default the version is set to the currently newest version: 13.1

### Emoji Data from custom path
You can load the emoji data from whatever path you want with the option:
```go
sanitizer, err := NewSanitizer(
    options.LoadFromCustomPath("https://unicode.org/Public/13.0.0/ucd/emoji/emoji-data.txt"),
)
```

If no `http` or `https` is in the scheme of the parsed URL it'll try to load a local file.

### Retrieve Emoji Data from offline/online
In case you always want to run the latest emoji data or possibly any updates you can use the option:
```go
// offline, this is already the default option
sanitizer, err := NewSanitizer(
    options.LoadFromOnline(false),
)

// online, you'll need this option if you want to load the emoji data from online
sanitizer, err := NewSanitizer(
    options.LoadFromOnline(true),
)
```

To reduce the error proneness you can further set the option to fallback to the offline approach should an error occur while loading the emoji data.
```go
sanitizer, err := NewSanitizer(
    options.LoadFromOnline(true),
    options.FallbackToOffline(true),
)
```

### Allow specific unicode emoji runes
In case you want to allow specific unicode emoji runes you can allow specific runes/ranges.
Best shown in the example of basic runes which are categorized as emoji:

```go
sanitizer, err := NewSanitizer(
    // general emoji codes which are normally allowed in most contexts
    // "#", "*", "[0-9]", "©", "®", "‼", "™"
    options.AllowEmojiCodes([]string{"0023", "002A", "0030..0039", "00A9", "00AE", "203C", "2122"}),
)
```

## Development
Want to contribute? Great!
I'm always glad hearing about bugs or pull requests.

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

repository: DaRealFreak/emoji-sanitizer

repo_name: DaRealFreak/emoji-sanitizer


text:
# Contributing

First off, **thank you** for considering to contribute to this project. You should know that there
are many ways to contribute. You can write tutorials or blog posts, improve the documentation,
submit bug reports or feature requests and write actual source code. All of these are very
worthwhile contributions.

Following these guidelines helps to communicate that you respect the time of the developers managing
this open source project. In return, they will reciprocate that respect in addressing your issue,
assessing changes, and helping you finalize your pull requests.

## Submitting a Feature Requests

If you find yourself wishing for a feature, you are probably not alone. There are bound to be others
out there with similar needs. Before submitting a feature request, first check if the
[wiki](https://github.com/djipco/webmidi/wiki)'s enhancements section already lists that feature.

If not, open an [issue](https://github.com/djipco/webmidi/issues) which describes the feature you
would like to see, why you need it, and how it should work.

## Understanding How to Contribute

Contribution to this project is done via pull requests. This allows the owner and contributors to
properly review what gets merged into the project.

**If this is your first pull request**, you can learn how to get started from a free series of
tutorials called
[How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github).

## Submitting a Pull Request

**WebMidi.js** is a relatively small library supported by an even smaller team. Therefore, the
process for contributing is intended to be simple and friendly.

However, to insure good quality, there are steps that you should go through when submitting a PR.
Here are the usual steps:

1. Discuss the change(s) you wish to make by means of an
[issue](https://github.com/djipco/webmidi/issues).
2. Unless the PR is for a minor improvement (typo, documentation, etc.), you should write and/or
update unit tests and check your code against the tests (see below).
3. If appropriate, update the [jsdoc](http://usejsdoc.org/) comments. Keeping the documentation and
the API consistant is very important.
4. If appropriate, update the `README.md` file.

Please note that your code should adhere to the styles defined in `.eslintrc.js`. You can use
`npm run lint` to make sure it does.

Finally, **do not** update the library's version number. Version numbering and releases will be
handled by the owner. If the PR breaks backwards-compatibility, it must be communicated explicitely
to the owner. The versioning scheme follows the [SemVer](http://semver.org/) standard.

## Testing

WebMidi.js now has a proper test suite. The tests can be run on the command line without a need for
a browser (thanks to Tim Susa).

You can execute all tests, including code coverage, by running the following command in the
terminal or on the command line:

```
npm run test-all
```

You can develop in *watch mode* with hot file reloading like so:
```
npm run test -- -w
```

You can start a single test in this way:
```
npx mocha ./test/virtual-midi-test.js
```

You can develop a single test in *watch mode* like this:
```
npx mocha ./test/virtual-midi-test.js -- -w
```

If you simply want to view code coverage, you can do:
```
npm run test-coverage
```

repository: djipco/webmidi

gha_language: JavaScript

repo_name: djipco/webmidi