text:
# ArgBind

**Build CLIs via docstrings and type annotations, with YAML support.**

![Build](https://github.com/pseeth/argbind/workflows/Build/badge.svg)
[![PyPI version](https://badge.fury.io/py/argbind.svg)](https://badge.fury.io/py/argbind)
[![codecov](https://codecov.io/gh/pseeth/argbind/branch/main/graph/badge.svg?token=BWI0FHZI5H)](undefined)
![Lines of code](https://img.shields.io/tokei/lines/github/pseeth/argbind)
[![Downloads](https://pepy.tech/badge/argbind)](https://pepy.tech/project/argbind)

*ArgBind is a simple way to bind arguments to functions to the command line or to .yml files!* It supports scoping of arguments, similar to other frameworks like
[Hydra](https://github.com/facebookresearch/hydra) and
[gin-config](https://github.com/google/gin-config).
ArgBind is *very* small (only ~400 lines of code, in one file), can be used to make complex and well-documented command line programs, and allows
you to configure program execution from .yml files.

If you're migrating from an ArgParse script to an ArgBind script, check out the
[migration guide](./examples/migration). Scroll down to see some [examples](#examples). Please also look at the
current known [limitations](#limitations-and-known-issues) of ArgBind.

## Why ArgBind?

I built ArgBind mostly to help me configure my machine learning experiments. ML experiment
configuration is often highly nested, and can get out of hand quick. I didn't want to switch
my workflow around too much to accommodate a new framework. Instead, I wanted the scripts
that I've written to be easily adapted so that I could achieve a few goals:

1. Configure scripts using `.yml` files. Be able to save `.yml` files that can be used to rerun scripts the exact same way twice.
2. Spend time writing actual functions needed to run experiments, not argument parsers.
3. Be able to run my experiment code from other Python scripts, notebooks, or the command line.
4. Be able to specify arguments from the command line directly to various functions.
5. Be able to use scoping patterns, so I can run a function inside of a `train` scope and `test` scope, with different results (e.g. for getting a train dataset and a test dataset).

Nothing out there really fit the bill, so I wrote ArgBind. If you have
an `argparse` based script, converting it to ArgBind should be very quick! ArgBind is simple,
small, and easy to use. To get a feel for how it works, check out [usage](#usage), [design](#design), and [examples](#examples)!

## Installation

Install via `pip`:

```
python -m pip install argbind
```

Or from source:

```
git clone https://github.com/pseeth/argbind.git
cd argbind
python -m pip install -e .
```

## Examples

- [Example 1: Hello World](./examples/hello_world/)
- [Example 2: Scope patterns](./examples/scoping/)
- [Example 3: Typing](./examples/typing/)
- [Example 4: MNIST Script](./examples/mnist/)
- [Example 5: Loading, saving, and using .yml files](./examples/yaml)
- [Example 6: Multi-stage programs](./examples/multistage)
- [Example 7: Mimic more traditional CLI, without `func.arg` notation](./examples/without_prefix)
- [Example 8: Debug mode](./examples/debug)
- [Example 8: Migrating from ArgParse](./examples/migration)

## Usage

There are six main functions.

- `bind`: Binds a functions typed keyword arguments (and positional arguments if `positional=True`) to ArgBind.
- `parse_args`: Actually parses the arguments into a dictionary.
- `scope`: Context manager that scopes a dictionary containing function arguments to be used by the functions.
- `dump_args`: Dumps the args dictionary to a `.yml` file. Used internally when program is called with `--args.save path/to/save.yml`.
- `load_args`: Loads args from a `.yml` file. Used internally when program is called with `--args.load path/to/load.yml`.
- `get_used_args`: Gets arguments that have actually been used by call functions up to this point.

Your code with ArgBind generally follows this pattern:

1. Write a function with a good docstring, and typed arguments.
2. Bind it via `bind`.
3. When program is called, parse the arguments via `parse_args`.
4. Scope the arguments, and call the bound function within the context block.
5. Optionally call program with `--args.save` to save the current execution configuration to a `.yml` file or `--args.load` to load arguments from a prior saved execution configuration to run it the same way twice.
6. Optionally, run your script with `--args.debug=1` to see exactly how every bound function is called.

In your program, you can call `get_used_args` to inspect the state of the argument dictionary. Here's a minimal example:

```python
import argbind

@argbind.bind()
def hello(
    name : str = 'world'
):
    """Say hello to someone.

    Parameters
    ----------
    name : str, optional
        Who you're saying hello to, by default 'world'
    """
    print("Hello " + name)

if __name__ == "__main__":
    # Arguments for CLI automatically generated from bound functions under the pattern
    # function_name.function_arg.
    args = argbind.parse_args()
    # When called within a scope, the keyword arguments map to those from CLI or
    # from defaults.
    with argbind.scope(args):
        hello()
```

Help text is automatically generated from the docstring:

```
❯ python examples/hello_world/with_argbind.py -h
usage: with_argbind.py [-h] [--args.save ARGS.SAVE] [--args.load ARGS.LOAD] [--args.debug ARGS.DEBUG] [--hello.name HELLO.NAME]

optional arguments:
  -h, --help            show this help message and exit
  --args.save ARGS.SAVE
                        Path to save all arguments used to run script to.
  --args.load ARGS.LOAD
                        Path to load arguments from, stored as a .yml file.
  --args.debug ARGS.DEBUG
                        Print arguments as they are passed to each function.

Generated arguments for function hello:
  Say hello to someone.

  --hello.name HELLO.NAME
                        Who you're saying hello to, by default 'world'
```

Execution of this could look like:

```
# Default arguments
❯ python examples/hello_world/with_argbind.py
Hello world
# Binding name from the command line and saving the args.
❯ python examples/hello_world/with_argbind.py --hello.name=you --args.save=/tmp/args.yml
Hello you
# Loading saved arguments.
❯ python examples/hello_world/with_argbind.py --args.load=/tmp/args.yml
Hello you
# Loading saved arguments, and overriding via command line.
❯ python examples/hello_world/with_argbind.py --args.load=/tmp/args.yml --hello.name=me
Hello me
# See how each function is called with args.debug=1.
❯ python examples/hello_world/with_argbind.py --args.load=/tmp/args.yml --args.debug=1
hello(
  name : str = you
)
Hello you
```

You can also run the `hello` function from another Python script or a Jupyter notebook:

```python
import argbind
# Import the bound function
from .hello_world import hello
# Load the args
args = argbind.load_args('/tmp/args.yml')
# Scope the args
with argbind.scope(args):
    # Run the bound function
    hello() # Prints 'Hello you'.
hello() # Prints 'Hello world', as it's outside scope.
# Can edit the args before scoping again.
args['hello.name'] = 'me'
with argbind.scope(args):
    hello() # Prints 'Hello me'.
```

You'll notice that ArgBind forces you to document and type your
function arguments, which is always a good idea!
Please check out the [examples](#examples) for more details!

## Design

ArgBind is designed around a decorator that can be used on
functions the user wants to expose to command line or to a .yml file.
The typed arguments to that function are
then bound to a dictionary. When the function is called,
each argument is looked up in the dictionary and its
value is replaced with the corresponding value in the dictionary. The
dictionary that the function looks for values in is controlled by
`scope`:

```python
import argbind

@argbind.bind()
def func(arg : str = 'default'):
    print(arg)

dict1 = {
    'func.arg': 1,
}
dict2 = {
    'func.arg': 2
}

with argbind.scope(dict1):
    func() # prints 1
with argbind.scope(dict2):
    func() # prints 2
func(arg=3) # prints 3.
```

The function arguments are bound to the command line. Continuing the
simple program from above:

```python
if __name__ == "__main__":
    args = argbind.parse_args()
    with argbind.scope(args):
        func()
    with argbind.scope(args):
        func(arg=3)
```

You can call this function like so:

```bash
❯ python examples/readme_example.py --func.arg 5
1 # Looks up `arg` in dict1
2 # Looks up `arg` in dict2
3 # arg is passed in on python call `func(arg=3)`
5 # Looks up `arg` from command line call `--func.arg 5`
3 # arg is passed in from two places: `func(arg=3)` and `--func.arg 5`. Former overrides the latter.
```

The logic here is that arguments that are bound that are closer to the actual function call get priority. From highest priority, to lowest, it goes:

1. Bound explicitly in Python code
2. Bound via command line
3. Bound via .yml file
4. Bound via default for kwarg

### Note!

The catch is that the function's argument MUST be typed.
This is required so that ArgBind knows how to parse it from the
command line.

# Limitations and known issues

There are some limitations to ArgBind, some due to how Python function decorator works,
and others out of a desire to keep ArgBind's code simple and straightforward.

## Boolean keyword arguments

If a boolean is flipped to True in a `.yml` file, there's no
way to override it from the command line. If you want a flag to
be flippable, make the argument an int instead of a bool and use
0 and 1 for True and False. Then you can override from command
line like `--func.arg 0` or `--func.arg 1`.

## Only typed arguments are bound

Only keyword arguments that have types associated with them are bound
in functions. Positional arguments are bound only if `positional=True`.
Untyped arguments cannot be bound, because ArgBind won't know what type to
parse for.

## Bound function names should be unique

Functions that are bound must be unique, even if they are in different files. The
function name is resolved in the argument parser only using the immediate name, not
a path to the function etc.

## Supported docstring formats

ArgBind uses [docstring-parser](https://github.com/rr-/docstring_parser), and so
the only supported styles are: ReST, Google, and Numpydoc-style docstrings.

## Not all types are supported

ArgBind supports most types that might pop up in your script, but not all. The supported types can be seen in the [typing example](./examples/typing/).

## Positional arguments should not be saved into .yml files

If the a positional argument is saved into a .yml file, and loaded
via `--args.load`, then any positional argument passed in the
command line will be overridden. Take care not to pass in
positional arguments via `.yml` files.

# Releasing

Do the following steps:

```
python setup.py sdist
```

Upload it to test PyPI:

```
pip install twine
twine upload --repository testpypi dist/*
pip install -U --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple -U argbind
```

Make sure you can install it and it works (e.g. run the examples). Now upload
to actual PyPI:

```
twine upload dist/*
```

# Issues? Questions?

If you've run into some issues with ArgBind, or have some questions, please ask
via Github Issues. Projects like ArgBind are pretty tricky to get right, so there
may be some edge cases that have been missed.

repository: janvainer/argbind

repo_name: janvainer/argbind


text:
# stockwell_transform
1-D  S_transform matlab code transfered to Python

Included:

1. origin S_transform  (/my_stran.py)
2. fast discrete orthonormal S_transform  (/my_fdost.py)

![stockwell](https://github.com/Gsonggit/stockwell_transform/blob/master/origin_s_transform.png)

**the result is as same as [claudiodsf](https://github.com/claudiodsf/stockwell)  and **[st.m](https://github.com/Gsonggit/stockwell_transform/blob/master/origin_matlab/st.m)****

If possible,Will be updated:

2-D S_transform;

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# `int48_t`

This header-only library provides a very simple implementation of a 48bit signed integer (aka `int48_t`). It is
written using the C++11 standard and should basically be runnable by every semi-great compiler out there. The class
is designed to behave like a normal integer type, so most conversions will be implicit. There are no external
dependencies, apart from the C++ standard library.

## License
Copyright © 2016 Marco Neumann

Distributed under the MIT License (MIT).


text:
# bisect

Bisect your async task into two steps, first perform async work in background and then apply the effect of work.

For example while you are fetching some data and updating view with new data. You can break task in following to improve perceived experience.

1. fetch the data (background work)
2. Apply the new data on your view (effect of work)

This is more of a pattern than a library. Library is pretty small.

## usage

```js
const start = bisect({
  background(...args) {
    // Async work which happens on background and does not have any effect on view or state. like just making fetch call
    // This method should return a promise.
    return fetch(url);
  },
  effect(data) {
    // this is where the effect from the async work is applied. For example you want to update view or state based on api response.
    updateView(data);
  },
  // Thresold to expire/discard background work by async task if it is not applied before a expiry period.
  // Default to Math.MAX_SAFE_INTEGER (never expire)
  expiry: 1000,
});
```

Then you can use it like

```js
let apply;

// this could be anything, not necessarily mouseenter on button
button.addEventListener("mouseenter", () => {
  apply = start(someParam);
});

button.addEventListener("click", () => {
  apply();
});
```

## Why bisect my async task?

Lets understand with an example. Let's say on an ecommorce site you have the product list. On click of a product you load data and show the detail on side drawer.

A very basic implementation would look something like this.

```js
function showProductDetail(productId) {
  return fetch(`/product/details/${productId}`)
    .then((response) => response.json())
    .then((data) => {
      const productDetail = formatData(data);
      openProductDetailDrawer(productDetail);
    });
}
```

Ignore the race conditions that can happen on this. In this we are just focusing on fetching a data and displaying them on a view.

Now on a basic flow, the User Interaction and Code Flow would be something like this.

- User clicks on product.
- You display a loader.
- You call showProductDetail method with that product id.
- The method fetches the data and once available it shows the data on the view.
- You clear the loader.

Let's say API takes 1s to load the data and openProductDetailDrawer takes 50ms to show it in the view.
So when user clicks a product it takes 1050ms for a user to present the result. Lets call that a waiting time of 1050ms.

We can definetly improve this experience. If we start loading the data before hand lets say when user hovers over the card. We can
reduce the overall waiting time as the waiting time starts after user clicks the product, and we have started loading it before hand.

But we can't just call showProductDetail on hover, as we can just predict the user intention but we are not sure if they will actully click it.

But, we can break this task into two parts.

1. Fetch the product detail when user hovers on the product. (Just the fetch, which doesn't have any effect on view).
2. Apply the data (call openProductDetailDrawer) on view only when user clicks.

Let's refactor this code into this two methods.

```js
function fetchProductDetail(productId) {
  return fetch(`/product/details/${productId}`).then((response) =>
    response.json()
  );
}

function showProductDetail(data) {
  const productDetail = formatData(data);
  openProductDetailDrawer(productDetail);
}
```

Then we can call the fetchProductDetail on hover and call showProductDetail on click with the response data of fetch. The usage may look something like this.

```js
let fetchPromise;

card.addEventListener("mouseenter", () => {
  fetchPromise = fetchProductDetail(productId);
});

card.addEventListener("click", () => {
  fetchPromise.then(showProductDetail);
});
```

There might be some other cases like discard promise if it happened before a threshold time.
Bisect provides a small util for writing it in cleaner way.

```js
const showProductDetail = bisect({
  background(productId) {
    return fetch(`/product/details/${productId}`).then((response) =>
      response.json()
    );
  },
  effect(data) {
    const productDetail = formatData(data);
    openProductDetailDrawer(productDetail);
  },
  expiry: 3000, // default to never expire
});
```

```js
let applyTask;

card.addEventListener("mouseenter", () => {
  applyTask = showProductDetail(productId);
});

card.addEventListener("click", () => {
  applyTask();
});
```

branch_name: refs/heads/main


text:
---
layout: post
title: "Particles leaving a finite cylinder through the ends"
author: "Jacob Schwartz"
categories: journal
tags: [algebra, geometry, integrals]
image: cylinder_neutron_flux_integral_coordinates.png
use_math: true
---
Several fusion start-up companies are proposing to use plasmas that can be approximated as a cylinder.
These would be encapsulated in cylindrical chambers, perhaps with the ends open to handle the plasma in a 'divertor' configuration.
Given a cylindrical plasma where the neutron source density depends only on $r$ (and not on $\theta$ or $z$),
what fraction of the neutrons would leave the cylinder though the circular ends? This becomes a tricky integral, even for simple radial profiles.
In this post we'll see how far we can get analytically before switching to a numerical method.

# Variable definitions
Let cylinder have radius 1 and length $A$. We will compute the fraction of neutrons leaving one circular face as a function of $A$.
The coordinates on that face are $(p, \theta')$, and the face is located at $z=0$.
The coordinates of a source point within the cylinder will be called $(r, \theta, z)$.
The neutron source density is $\rho(r)$.

## Integrand
The distance from a volume element at $(r, \theta, z)$ and the surface element at $(p, \theta')$ is

$$
d = \left((p\cos\theta' - r \cos\theta)^2 + (p \sin \theta' - r \sin\theta)^2 + z^2\right)^{1/2},
$$

and by trigonometry, the cosine of the angle between the source-target vector and the surface normal is $$\cos(\phi) = \frac{z}{d}$$.
If the surface element's normal is perpendicular to the neutron direction, it presents an infitesimal cross section; $\cos(\phi=\pi/2) = 0$.

All together, the fraction of neutrons from a volume element at $(r, \theta, z)$ which go on to impact the surface element at $(p, \theta')$ is

$$
\mathcal{I_0} = \frac{1}{4\pi} \frac{1}{d^2} \cos\phi = \frac{1}{4\pi} \frac{z}{\left((p\cos\theta' - r \cos\theta)^2 + (p \sin \theta' - r \sin\theta)^2 + z^2\right)^{3/2}}.
$$

The term ($1/4\pi$) assumes that neutrons are emitted isotropically from the source volume elements.
The second term captures the decrease in flux from an element with the distance, and the third term captures the angular dependence.

## The integral
The total flux through one circular end is

$$
\mathcal{F} = \int_{-\pi}^{\pi}d\theta' \int_{0}^1 dp \int_0^1 dr\, \int_{-\pi}^{\pi} d\theta \int_0^A dz  \; \mathcal{I_0} \,\rho(r) \, r\, p
$$

where the final $r$ and $p$ are the usual Jacobians for polar and cylindrical coordinates; since we're integrating over $\theta'$ and $\theta$ we need both.

Since the final overall intensity is independent of $\theta'$ (the source is symmetric around the axis)
we can make the problem a bit simpler by fixing $\theta' = 0$.

## First integration, $\theta'$
Since by construction the problem is symmetric around the axis, we can immediately remove the $\theta'$ integration by symmetry.
We multiply the result by $2\pi$ and set $\theta'$ to 0, so the new integrand is

$$
\mathcal{I_1} = \frac{1}{4\pi} \frac{z}{\left((p - r \cos\theta)^2 + (r \sin\theta)^2 + z^2\right)^{3/2}}.
$$

and

$$
\mathcal{F} = 2 \pi \int_{0}^1 dp \int_0^1 dr\, \int_{-\pi}^{\pi} d\theta \int_0^A dz  \; \mathcal{I_1} \,\rho(r) \, r\, p
$$

## Second integration, $z$
The second integration is carried out over $z$.

$$
\begin{align}
\int_0^A dz \, \mathcal{I_1} &= \frac{1}{4 \pi} \int_0^A dz \; \frac{z}{\left((p - r \cos\theta)^2 + (r \sin\theta)^2 + z^2\right)^{3/2}} \\ \mathcal{I_2} &= \frac{1}{4\pi}\left( \frac{1}{\sqrt{r^2 + p^2 - 2 r p \cos\theta}} - \frac{1}{\sqrt{A^2 + r^2 + p^2 - 2 r p \cos\theta}} \right).
\end{align}
$$

## Third integration, $\theta$
The third integration is carried out over $\theta$:

$$
\begin{align}
\mathcal{I}_3 &= \int_{-\pi}^{\pi} d\theta \, \mathcal{I_2} \\
&= \frac{1}{4\pi} \left(\frac{4 K\left(\frac{4\,r\,p}{(r + p)^2}\right)}{r + p}
- \frac{4 K\left(\frac{4\,r\,p}{\sqrt{A^2 + (r + p)^2}}\right)}{\sqrt{A^2 + \left(r + p\right)^2}}\right)
\end{align}
$$

where $K(m)$ is the complete elliptic integral of the first kind.

## Numerical integration, $r$ and $p$
We reacquaint ourselves with the full expression for the flux $\mathcal{F}$.
There are only two integrals remaining, over $r$ and $p$.

$$
\begin{align}
\mathcal{F} &= 2\pi \int_0^1 \int_0^1 dr\,dp\,\mathcal{I}_3 \, \rho(r)\,r\,p \\
            &= \frac{2\pi}{4\pi} 4 \int_0^1 \int_0^1 dr\,dp\,
 \left(\frac{K\left(\frac{4\,r\,p}{(r + p)^2}\right)}{r + p}
- \frac{K\left(\frac{4\,r\,p}{\sqrt{A^2 + (r + p)^2}}\right)}{\sqrt{A^2 + \left(r + p\right)^2}}\right)\, \rho(r)\,r\,p \\
            &= 2 \int_0^1 \int_0^1 dr\,dp\,
 \left(\frac{K\left(\frac{4\,r\,p}{(r + p)^2}\right)}{r + p}
- \frac{K\left(\frac{4\,r\,p}{\sqrt{A^2 + (r + p)^2}}\right)}{\sqrt{A^2 + \left(r + p\right)^2}}\right)\, \rho(r)\,r\,p
\end{align}
$$

This is a nice form for the expression as it is symmetric in $r$ and $p$, other than the radial source dependence $\rho(r)$.
I have not found an analytic means to proceed further, even when $\rho(r)$ is a constant.

The shape of this integrand is shown below.

{% include figure.html url="cylinder_neutron_flux_p_r.png"
caption="Figure 2: The numerical integrand $\mathcal{I}_3$, plotted with $A=1$ and constant $\rho(r)$.
(The ridge is infinite; ignore the artefacts at $p\le0.2$.) The two halves of the plane are symmetrical. "%}

There is an infinite ridge at $r=p$.
This is because $K(1) = \infty$ (a ComplexInfinity according to Mathematica).
It is probably better from a numerical integration perspective to not have to traverse the infinite ridge, and instead stay only on one side.
We can rewrite the integral's bounds as

$$
\begin{align}
\mathcal{F} &= 2 \int_0^1 dp\, \int_0^p dr \,
 \left(\frac{K\left(\frac{4\,r\,p}{(r + p)^2}\right)}{r + p}
- \frac{K\left(\frac{4\,r\,p}{\sqrt{A^2 + (r + p)^2}}\right)}{\sqrt{A^2 + \left(r + p\right)^2}}\right)\, \rho(r)\,r\,p \\
 &+ 2 \int_0^1 dp\, \int_p^1 dr \,
 \left(\frac{K\left(\frac{4\,r\,p}{(r + p)^2}\right)}{r + p}
- \frac{K\left(\frac{4\,r\,p}{\sqrt{A^2 + (r + p)^2}}\right)}{\sqrt{A^2 + \left(r + p\right)^2}}\right)\, \rho(r)\,r\,p
\end{align}
$$

We've gone as far as we can go here.
The next step is to compute the total neutron source rate; it'll be the denominator in the expression
for the fraction of neutrons leaving one end of the cylinder,

$$
f_\mathrm{one-end} = \frac{\mathcal{F}}{\mathcal{S}}.
$$
where $\mathcal{S}$ is the total neutron source rate.

## Total neutron source rate
The total source rate is

$$
\mathcal{S} = \int_0^A dz \int_{-\pi}^{\pi} d\theta \int_0^1 dr \, \rho(r) r = 2 \pi A \int_0^1 r dr\, \rho(r).
$$

When $\rho(r)$ is a constant with $r$ this reduces to $\pi A \rho$.

## Fraction of neutrons leaving either end
The quantity $f_\mathrm{one-end}$ is the computation of the fraction leaving one end; double it to get

$$
\begin{align}
f_\mathrm{either-end} &= 2 f_\mathrm{one-end} \\ &= \frac{
4 \int_0^1 dp\, \int_0^1 dr \,
 \left(\frac{K\left(\frac{4\,r\,p}{(r + p)^2}\right)}{r + p}
- \frac{K\left(\frac{4\,r\,p}{\sqrt{A^2 + (r + p)^2}}\right)}{\sqrt{A^2 + \left(r + p\right)^2}}\right)\, \rho(r)\,r\,p

}{
\pi A \int_0^1 r dr\, \rho(r)
}
\end{align}
$$

(For brevity I've combined the two halves of the numerator integration again.)

# Results for various radial source distributions

{% include figure.html url="cylinder_neutron_source_profiles.png"
caption="Figure 3: Three example source radial distributions: $\rho(r) = 1$, $\rho(r)=1-r^2$, and a line source."%}

I'm not totally sure about this, but I think that for most cylindrical fusion machines, the neutron source strength would increase toward the plasma axis $(r=0)$.
The radial dependence $\rho(r)$ would be between the extremes of a constant density (Figure 3 left) and a pure line source (right); a parabolic dependence (center) represents a 'typical' profile.

Figure 4 shows $f_\mathrm{body} \equiv 1 - f_\mathrm{either-end}$ evaluated for these three distributions.

{% include figure.html url="cylinder_neutron_ends_three_line_sources.png"
caption="Figure 4: Fraction leaving the cylinder body for the three radial distributions."%}

Note that the pure line source case __is__ exactly solvable; $f_\mathrm{body,line} = \left(\sqrt{1 + A^2} - 1\right) / A$.

For $A \gt 5$ the results are all within 5% of one another. This is encouraging as with decently large $A$ we can estimate $f_\mathrm{body}$ fairly well even for an unknown source profile.

The Mathematica integration code is reproduced below:
```
ρ[r_] := 1
(* ρ[r_] := 1 - r^2 *)

fEitherEnd[A_?NumericQ] :=
 NIntegrate[
     2 p r ( EllipticK[4 p r/(p + r)^2]/(p + r) -
        EllipticK[4 p r/(A^2 + (p + r)^2)]/Sqrt[
        A^2 + (p + r)^2]) ρ[r], {r, 0, 1}, {p, 0, 1},
     WorkingPrecision -> 10, Exclusions -> r==p] /
     (π A NIntegrate[r ρ[r], {r, 0, 1}])

fBody[A_?NumericQ] := 1 - fEitherEnd[A]
```


text:
# React-Js and Laravel CRUD

To run the program

Install first the Node Module

``
npm install
``

Create a database named **blog**

then migrate the database

``
php artisan migrate
``

then finally to deploy the website

``
php artisan serve
``

repository: RhandallTimtiman/reactjs-laravel-crud

repo_name: RhandallTimtiman/reactjs-laravel-crud


text:
# BMaps-Backend

## Documentation
Hosted on GitHub Pages at http://ucladevx.com/BMaps-Backend/

## Setting Up the Environment
- Follow instructions in main [BMaps](https://github.com/ucladevx/BMaps) repository
- Install git-crypt
- Generate an RSA gpg key at least 2048 bits in length. Email the key to a bmaps member familiar with the operation of git-crypt. Pull down the changes from the master branch after the bmaps member has told you to do so.
- Run `git-crypt unlock`
- Build the base image that contains all dependencies that are fairly static but take a while to install
  - `make build-base`
- NOTE: the database connection doesn't seem to work over UCLA_WEB wifis, a more secure connection is needed (UCLA_WIFI)

## How to Run Backend Locally

- Build and run container using local Postgres database
  - `make dev`
  - To use production database (not recommended for local development):
    - `make prod`
- Navigate to [http://localhost](http://localhost)
- Access flask api directly at port [5000](http://localhost:5000/)
  - Use `localhost:5000/api/<insert_api_route_here>`
  - e.g. `localhost:5000/api/events`
- Stop running with `CTRL+C` or `make stop` in a separate terminal window

## Repo Breakdown

- Database config/data is in `/database`
- Backend source code is in `src/`
- tkinter GUIs is in `tkinter/`
- Autodocumentation is in `docs/`
- Beautiful Soup Scraping is in `scraping/`

## Using git crypt to get access to .env files

- Generate a rsa2048 gpg key using the gpg tool
  - `gpg full-generate-key`
  - Make sure to record your passphrase in a secure location, and also to generate a revocation certificate for the key in case it gets compromised or lost
    - `gpg --output revocation-cert.asc --gen-revoke <PUB-KEY-SIG>`
- Convey your gpg key through a keyfile securely to a project member, either using a pub key server, or through another clandestine channel
  - To generate the key file:
    - `gpg --output <YOUR_NAME>.gpg --export <PUB-KEY-SIG>`
- The team member will then add your pub-key to their gpg key-chain using
  - `gpg --import <keyfile>`
  - Note that keyfile in this step is the same as the <YOUR_NAME>.gpg file generated in the previous step
  - They may also choose to sign the key if they trust you.
- Finally, the team member will run:
  - `git-crypt --add-gpg-user <team member to be added's email or any other identifier of key>`
  - Then they must push their changes (adding your pub key) made to the repository to the remote, and those changes pulled by you
  - Note that their changes will not appear when `git status` is run, so it may be necessary to make some other change in the repository to successfully push the newly added pub key within git crypt
- Finally, once you have the updated repository they pushed, run
  - `git-crypt unlock`
  - you will not need to run git-crypt unlock again, since git-crypt will automatically encrypt your .envs as you push them within this repo, and decrypt them as they are pulled from the remote. GLHF.

repository: ucladevx/Bmaps-Backend

gha_language: Jupyter Notebook

gha_license_id: MIT

repo_name: ucladevx/Bmaps-Backend


text:
# DevTools Timeline Viewer
##### Shareable URLs for your Chrome DevTools Timeline traces.

Works with public github urls, github gists, and files on google drive (once authenticated).

---

Once authorized, you'll see Timeline Viewer as a registered Google Drive viewer when opening .json files. Once you select the Timeline Viewer, it will open in a new tab and load the timeline asset from your Drive.

![](https://cloud.githubusercontent.com/assets/39191/18080010/67390d9a-6e48-11e6-98a3-9c8c81b1df67.png)

You can share this URL with any users who ① have authorized [Timeline Viewer](https://chromedevtools.github.io/timeline-viewer/) to Drive with Google OAuth and ② have View permission to the Google Drive asset.

![image](https://cloud.githubusercontent.com/assets/39191/18080845/fb39f056-6e4b-11e6-90df-6cda94bd2495.png)

Visit your Google security permissions if you'd like to revoke authorization.

## Dev

Run:
 - `yarn` or `npm i`
 - `yarn run dev` or `npm run dev` - it will open site in browser and run server for you.

Master branch's `docs` folder is what's published to gh-pages, to simplify deployment.

Auth keys have localhost:8000 whitelisted, so you can hack there.

* Private file: http://localhost:8000/?loadTimelineFromURL=0BzvYe7bYFf--aVhZM1RNR2N3cGc

### Updating Service Worker file

* `yarn run generate-sw` or `npm run generate-sw`

### Updating DevTools Version

* Remote debug Chrome on Android (Dev channel or Canary).
* (Verify it works as expected)
* Open devtools on devtools
* Look at `location.href` and grab the hash out of it
  * `copy(new URL(location.href).pathname.match(/@(\w+)/)[1])`
* Pop that into the hash in `docs/index.html`

repository: barkinet/timeline-viewer

repo_name: barkinet/timeline-viewer


text:
# ~/.config/fish/prompt

![Screenshot]

My minimalist `fish` prompt progressively discloses information as and when it
becomes relevant, including:

* User and hostname appear only when connecting remotely
* Current working directory, abbreviated but still readable at a glance
* Basic git status: branch name, with coloured indicators for untracked,
  unstaged, uncommitted, unsynced and stashed files
* Background job count, if > 0
* Local rbenv version, if different from the global version
* Non-zero exit statuses appear against the right margin, as numbers or (if
  applicable) signal names
* The right margin can also include the duration of the last command and/or an
  indicator of the current `vi` mode

Prompt-related functions live here to avoid cluttering up `../functions`. The
path to this directory must be added to `$fish_package_path` so everything can
auto-load.

[Screenshot]: https://raw.githubusercontent.com/zgracem/dotconfig/master/fish/prompt/prompt.png

## `fish_title` → `fish_window_title` + `fish_tab_title`

The code supporting [`fish_title`] ([`reader_write_title()` in reader.cpp][1])
writes simultaneously to both the terminal "window" and "icon" titles. I prefer
to set those separately; hence [`set_terminal_title.fish`][2], which allows
separate [`fish_window_title`][3] and [`fish_tab_title`][4] functions, the
output of which will appear in the terminal window or tab title, respectively,
each time the prompt is displayed.

[`fish_title`]: https://fishshell.com/docs/current/cmds/fish_title.html
[1]: https://github.com/fish-shell/fish-shell/blob/master/src/reader.cpp#L1457
[2]: https://github.com/zgracem/dotconfig/blob/main/fish/prompt/functions/set_terminal_title.fish
[3]: https://github.com/zgracem/dotconfig/blob/main/fish/prompt/functions/fish_window_title.fish
[4]: https://github.com/zgracem/dotconfig/blob/main/fish/prompt/functions/fish_tab_title.fish

repository: zgracem/dotconfig

gha_language: Shell

repo_name: zgracem/dotconfig


text:
CakePHP-Multiform-Navigation
============================

Gives easy persistent logic to maintain what steps come next in a form regardless of if the user is redirected to a page outside of the form.

When you create a multi-page form, one of the hardest things is tracking the path through this form, especially when redirected off to another page. I created this so that regardless of where on the site they needed to go (for instance if they needed to login) the user could be easily redirected back into the correct part of the site after this was done.

Basically it is just a neat way of handling the Session Variables that need to be set:

To redirect to the current/ previous / next step:

```php
if($this->CheckoutSteps->inCheckout()) {
    $this->CheckoutSteps->nextStep();
}
```

The setup for this is done in the component (it could be done with a constructor better if you intend to re-use this!), you set the steps up in such a way that each array element is consecutively setup with the preceeding step and next step (controller action names).
You also setup what the first step is and what the step is that requires them to login (if you are using a form that requires a user to be logged in after a certain point), and finally setup the sessionStore which is the variable in Session you want to store this in, ideally you want it as the one that gets destroyed when they log out.

```php
 function initialize(Controller $controller) {
            $this->controller = $controller;
            $this->steps = array(
                "login_register" => "address",
                "address" => "payment"
            );
            $this->firstStep = "address";
            $this->loginStep = "login_register";
            $this->sessionStore = "UserAuth.Checkout";

            if($this->Session->check($this->sessionStore)) {
                $this->currentStep = $this->Session->read($this->sessionStore);
            }
        }
```

And to set the steps up correctly automatically on the controller that handles the multiform requests you simply add the code to set the step in beforeFilter:

```php
public function beforeFilter() {
    parent::beforeFilter();
    $this->CheckoutSteps->setStep($this->action);
}
```

Hope this helps someone :)

repository: voycey/CakePHP-Multiform-Navigation

repo_name: voycey/CakePHP-Multiform-Navigation


text:
---
layout: layout.njk
title: </> kutty - high power tools for html
---

  </> kutty
  high powered tools for HTML

## Introduction

Kutty is a set of HTML extensions (attributes, request headers, etc.) that help you build
[advanced UX](/demo) with the simplicity and power of the hypertext we all know and love.

Kutty is a small (<6Kb min.gz'd), dependency-free & you can try it out quickly, without a huge rewrite.

## Quick Start

``` html
  <!-- Load from unpkg -->
  <script<EMAIL_ADDRESS>  <!-- have a button POST a click via AJAX -->
  <button kt-post="/clicked" kt-swap="outerHTML">
    Click Me
  </button>
```

This annotation tells kutty:

> "When a user clicks on this button, issue an AJAX request to /example, and replace the button with the response"

Kutty is based on [intercooler.js](http://intercoolerjs.org) and is the successor to that project.

repository: inouire/kutty

repo_name: inouire/kutty


text:
# 1€ Filter (One Euro Filter)
A simple Python implementation of the 1€ Filter (1e filter, 1 euro filter, One Euro Filter). The code in [`one_euro_filter.py`](one_euro_filter.py) can be used as pseudocode for implementing the algorithm in other languages. Detailed pseudocode about the underlying mathematics of the algorithm and sources can be found in a blog post that I wrote about it, [Noise Filtering Using 1€ Filter](https://jaantollander.com/post/noise-filtering-using-one-euro-filter/).

```python
import math

def smoothing_factor(t_e, cutoff):
    r = 2 * math.pi * cutoff * t_e
    return r / (r + 1)

def exponential_smoothing(a, x, x_prev):
    return a * x + (1 - a) * x_prev

class OneEuroFilter:
    def __init__(self, t0, x0, dx0=0.0, min_cutoff=1.0, beta=0.0,
                 d_cutoff=1.0):
        """Initialize the one euro filter."""
        # The parameters.
        self.min_cutoff = float(min_cutoff)
        self.beta = float(beta)
        self.d_cutoff = float(d_cutoff)
        # Previous values.
        self.x_prev = float(x0)
        self.dx_prev = float(dx0)
        self.t_prev = float(t0)

    def __call__(self, t, x):
        """Compute the filtered signal."""
        t_e = t - self.t_prev

        # The filtered derivative of the signal.
        a_d = smoothing_factor(t_e, self.d_cutoff)
        dx = (x - self.x_prev) / t_e
        dx_hat = exponential_smoothing(a_d, dx, self.dx_prev)

        # The filtered signal.
        cutoff = self.min_cutoff + self.beta * abs(dx_hat)
        a = smoothing_factor(t_e, cutoff)
        x_hat = exponential_smoothing(a, x, self.x_prev)

        # Memorize the previous values.
        self.x_prev = x_hat
        self.dx_prev = dx_hat
        self.t_prev = t

        return x_hat
```

repository: myxiz/AirTable

repo_name: myxiz/AirTable


text:
---
title: Getting started with Trust Tokens
subhead: Trust Tokens is a new API to help combat fraud and distinguish bots from real humans, without passive tracking.
authors:
  - samdutton
date: 2020-06-22
updated: 2021-02-01
hero: image/admin/okxi2ttRG3h1Z4F3cylI.jpg
thumbnail: image/admin/cTo0l2opcfNxg1TEjxSg.jpg
alt: Black and white photograph of hand holding token
tags:
  - blog
  - privacy
  - security
feedback:
  - api
---

{% YouTube 'WnCKlNE52tc' %}

## Summary

Trust tokens enable an origin to issue cryptographic tokens to a user it trusts.
The tokens are stored by the user's browser. The browser can then use the tokens
in other contexts to evaluate the user's authenticity.

The Trust Token API enables trust of a user in one context to be conveyed to another context without
identifying the user or linking the two identities.

You can try out Trust Tokens with our [demo](https://trust-token-demo.glitch.me) and, from Chrome
89, [inspect Trust Tokens](https://developers.google.com/web/updates/2021/01/devtools#trust-token)
in the Chrome DevTools **Network** and **Application** tabs.

  {% Img src="image/tcFciHGuF3MxnTr1y5ue01OGLBn2/krrI292OLd6awb4dxkN0.jpg", alt="Screenshot showing Trust Tokens in the Chrome DevTools Network tab.", width="800", height="584" %}

Trust Tokens in the Chrome DevTools Network tab.

  {% Img src="image/tcFciHGuF3MxnTr1y5ue01OGLBn2/cwR9JdoVo1M4VDovP2oM.jpg", alt="Screenshot showing Trust Tokens in the Chrome DevTools Application tab.", width="800", height="584" %}

Trust Tokens in the Chrome DevTools Application tab.

{% Aside %}
The Privacy Sandbox is a series of proposals to satisfy third-party use cases
without third-party cookies or other tracking mechanisms. See
[Digging into the Privacy Sandbox](/digging-into-the-privacy-sandbox)
for an overview of all the proposals.

**This proposal needs your feedback!** If you have comments, please [create an
issue](https://github.com/WICG/trust-token-api/issues/new) on the [Trust Token
explainer](https://github.com/WICG/trust-token-api) repository.
{% endAside %}

## Why do we need Trust Tokens?

The web needs ways to establish trust signals which show that a user is who they
say they are, and not a bot pretending to be a human, or a malicious third-party
defrauding a real person or service. Fraud protection is particularly important
for advertisers, ad providers, and CDNs.

Unfortunately, many existing mechanisms to gauge and propagate
trustworthiness—to work out if an interaction with a site is from a real human,
for example—take advantage of techniques that can also be used for
fingerprinting.

{% Aside 'key-term' %}
**Fingerprinting** enables sites to identify and track individual users by
getting data about their device, operating system, and browser setup (such as
language preferences,
[user agent](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/userAgent), and
available fonts) or changes in device state. This may be done on the server
by checking request headers or on the client with JavaScript.

Fingerprinting uses mechanisms that users aren't aware of and can't control.
Sites such as [Panopticlick](https://panopticlick.eff.org/) and
[amiunique.org](https://amiunique.org/) show how fingerprint data can be
combined to identify you as an individual.
{% endAside %}

The API must preserve privacy, enabling trust to be propagated across sites
without individual user tracking.

## What's in the Trust Tokens proposal?

The web relies on building trust signals to detect fraud and spamming. One way
to do this is by tracking browsing with global, cross-site per-user identifiers.
For a privacy-preserving API, that's not acceptable.

From the proposal
[**explainer**](https://github.com/WICG/trust-token-api#overview):

This API proposes a new per-origin storage area for "Privacy Pass" style
cryptographic tokens, which are accessible in third party contexts. These
tokens are non-personalized and cannot be used to track users, but are
cryptographically signed so they cannot be forged.

When an origin is in a context where they trust the user, they can issue
the browser a batch of tokens, which can be "spent" at a later time in a
context where the user would otherwise be unknown or less trusted.
Crucially, the tokens are indistinguishable from one another, preventing
websites from tracking users through them.

We further propose an extension mechanism for the browser to sign outgoing
  requests with keys bound to a particular token redemption.

## Sample API usage

The following is adapted from
[sample code in the API explainer](https://github.com/WICG/trust-token-api#sample-api-usage).

{% Aside %}
The code in this post uses updated syntax available since Chrome 88.
{% endAside %}

Imagine that a user visits a news website (`publisher.example`) which embeds
advertising from a third party ad network (`foo.example`). The user has
previously used a social media site that issues trust tokens (`issuer.example`).

The sequence below shows how trust tokens work.

1. The user visits `issuer.example`.

2. `issuer.example` verifies the user is a human, and runs the following
JavaScript:

```js
fetch('https://issuer.example/issue', {
  trustToken: {
    type: 'token-request'
  }
});
```

3. The user's browser stores the trust tokens associated with `issuer.example`.

4. Some time later, the user visits `publisher.example`.

5. `publisher.example` wants to know if the user is a human, so they ask
`issuer.example` by running the following JavaScript:

 ```js
 fetch('https://issuer.example/redeem', {
   trustToken: {
     type: 'token-redemption'
   }
 });
```

With this code:

 1. The browser requests a redemption.
 1. The issuer returns a Redemption Record (RR) which indicates
    that at some point they issued a valid token to this browser.
 1. When the promise returned resolves, the RR can be used in
    subsequent resource requests.

6. `publisher.example` can then run the following JavaScript in a top-level
document:

```js
fetch('foo.example/get-content', {
  trustToken: {
    type: 'send-redemption-record',
    issuers: ['https://issuer.example']
  }
});
```

With this code:

1. `foo.example`  receives the RR and can parse the record to determine whether
  `issuer.example` thought this user was a human.
1. `foo.example` responds accordingly.

{% Details %}
{% DetailsSummary %}
How can a website work out whether to trust you?
{% endDetailsSummary %}
You might have shopping history with an ecommerce site, checkins on a location
platform, or account history at a bank. Issuers might also look at other factors
such as how long you've had an account, or other interactions (such as CAPTCHAs
or form submission) that increase the issuer's trust in the likelihood that
you're a real human.
{% endDetails %}

### Trust token issuance

If the user is deemed to be trustworthy by a trust token issuer such as
`issuer.example`, the issuer can fetch trust tokens for the user by making a
`fetch()` request with a new `trustToken` parameter:

```js
fetch('issuer.example/.well-known/trust-token', {
  trustToken: {
    type: 'token-request'
  }
}).then(...)
```

This invokes an extension of the [Privacy Pass](https://privacypass.github.io/) issuance
protocol using a [new cryptographic primitive](https://eprint.iacr.org/2020/072.pdf):

1. Generate a set of pseudo-random numbers known as _nonces_.

1. Blind the nonces (encode them so the issuer can't view their contents) and attach them to the
request in a `Sec-Trust-Token` header.

1. Send a POST request to the endpoint provided.

The endpoint responds with blinded tokens (signatures on the blind nonces), then the tokens are
unblinded and stored internally together with the associated nonces by the browser as trust tokens.

### Trust token redemption

A publisher site (such as `publisher.example` in the example above) can check if
there are trust tokens available for the user:

```js
const userHasTokens = await document.hasTrustToken(<issuer>);
````

If there are tokens available, the publisher site can redeem them to get a
redemption record:

```js
fetch('issuer.example/.well-known/trust-token', {
  ...
  trustToken: {
    type: 'token-redemption',
    refreshPolicy: 'none'
  }
  ...
}).then(...)
```

Then the publisher site can send the RR to requests it makes using the
following API:

```js
fetch('<url>', {
  ...
  trustToken: {
    type: 'send-redemption-record',
    issuers: [<issuer>, ...]
  }
  ...
}).then(...);
```

The publisher should include the RR in requests that will require a trust
token, such as posting a comment, liking a page, or voting in a poll.

{% Aside %}
Trust tokens are only accessible through options to Fetch, XHR, and the HTML
`<iframe>` element: they cannot be accessed directly.
{% endAside%}

### Privacy considerations

Tokens are designed to be 'unlinkable'. An issuer can learn aggregate
information about which sites its users visit, but can't link issuance with
redemption: when a user redeems a token, the issuer can't tell the token apart
from other tokens it has created. However, trust tokens currently do not exist
in a vacuum: there are other ways an issuer could currently—in theory—join a
user's identity across sites, such as third-party cookies and covert tracking
techniques. It is important for sites to understand this ecosystem transition as
they plan their support. This is a general aspect of the transition for many
Privacy Sandbox APIs, so not discussed further here.

### Security considerations

**Trust token exhaustion:** a malicious site could deliberately deplete a user's
supply of tokens from a particular issuer. There are several mitigations against
this kind of attack, such as enabling issuers to provide many tokens at once, so
users have an adequate supply of ensuring browsers only ever redeem one token
per top-level page view.

**Double-spend prevention:** malware might attempt to access all of a user's
trust tokens. However, tokens will run out over time, since every redemption is
sent to the same token issuer, which can verify that each token is used only
once. To mitigate risk, issuers could also sign fewer tokens.

### Request mechanisms

It might be possible to allow for sending RRs outside of `fetch()`, for example
with navigation requests. Sites might also be able to include issuer data in
HTTP response headers to enable token redemption in parallel with page
loading.

**To reiterate: this proposal needs your feedback!** If you have comments, please
[create an issue](https://github.com/WICG/trust-token-api/issues/new) on the
Trust Token [explainer repository](https://github.com/WICG/trust-token-api).

## Find out more

-  [Trust Tokens demo](https://trust-token-demo.glitch.me)
-  [Digging in to the Privacy Sandbox](/digging-into-the-privacy-sandbox/)
-  [Trust Token API Explainer](https://github.com/WICG/trust-token-api)
-  [Chromium Projects: Trust Token API](https://sites.google.com/a/chromium.org/dev/updates/trust-token)
-  [Intent to Implement: Trust Token API](https://groups.google.com/a/chromium.org/g/blink-dev/c/X9sF2uLe9rA/m/1xV5KEn2DgAJ)
-  [Privacy Pass](https://privacypass.github.io/)
-  [Extensions of Privacy Pass](https://eprint.iacr.org/2020/072.pdf)

---

Thanks to Kayce Basques, David Van Cleve, Steven Valdez, Tancrède Lepoint and Marshall Vale for
their help with writing and reviewing this post.

Photo by [ZSun Fu](https://unsplash.com/photos/b4D7FKAghoE) on [Unsplash](https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText).


text:
![Maintenance Panel](/assets/reference/edit-objects/metadata/main/maintenance.png)

* Frequency   1{**type**: codelist (ISO MD_MaintenanceFrequencyCode); **multi-value**: NO; **extensible**: YES; **multi-value**: NO; **default**: empty}1  The frequency period for maintenance of this resource.

* Dates 1{**type**: array (obj: Date); **default**: empty}1 - Dates and datetimes related to maintenance of this resource. 2{[See object details](#date-object)}2

* Contacts 1{**type**: array (obj: Responsible Party); **default**: empty}1 - Persons and organizations to contact for information regarding maintenance of this resource. 2{[See object details](#responsible-party-object-contacts)}2

* Notes 1{**type**: array (string); **max length**: none; **default**: empty}1 - An array of notes or comments to provide additional information about this maintenance cycle.  Each note is a character string.

* Scope 1{**type**: codelist (ISO MD_ScopeCode, ADIwg codes); **extensible**: YES; **multi-value**: YES; **default**: empty}1 - A code to describe the class or context for which the maintenance cycle applies.

---

{% include "../include-objects/date-obj.md" %}

---

### Responsible Party Object (Contacts)

{% include "../include-objects/responsibleParty-obj.md" %}

repository: adiwg/mdEditor-doc

gha_language: SCSS

repo_name: adiwg/mdEditor-doc


text:
---
title: Effective Pair Programming
date: "2019-11-03T22:12:03.284Z"
excerpt: Pair Programming is a common concept across software development, however it can be misunderstood and badly implemented. In this post I run through the basics of pairing, why it's so invaluable, and my favourite method of pairing.
tags: ["Pairing", "Workplace"]
---

Pair programming is a common concept, especially in well-experienced teams - however, it can be daunting to new developers coming into the software scene, due to a lack of confidence coding around others, and also confusion around how it _should_ be done.

This article aims to explain how Pair Programming is intended to be done, discuss why it's so invaluable, and will talk through one of my favourite methods of pairing.

### What is Pair Programming?

Pair programming is a concept where two developers jointly work on a ticket to complete it - so this involves all code, tests and any other work needed to get it done.

Pairing involves both a Driver and a Navigator.

### Driver

The Driver should be on the keyboard. They are in charge of writing code on the screen and should be focused entirely on the current problem/task.

### Navigator

The Navigator should be observing and reviewing the code entered by the Driver.

They should _also_ be observing and thinking about the overall direction and structure of the work. So this will involve thinking of potential future problems and improvements the team can make.

This allows the Driver to focus solely on tackling the problem at hand.

The pair should switch roles frequently - I prefer switching every 15-30 minutes at hard enforced timescales.

That's it! There's a lot more rules and methods involved, but at a high level, that's enough to get started.

## Why we should pair program
> Whilst this means more dev-hours are spent on effort within a ticket, it has been proven to output far higher-quality code with [fewer defects](https://collaboration.csc.ncsu.edu/laurie/Papers/XPSardinia.PDF).

The obvious benefit is Two heads are better than one. Some caveats come with this, around ensuring that you work well together, don't get distracted etc. But the code you will produce will be better than if you are coding alone.

Not only this but there are a bunch of other reasons why pairing is fantastic:

### 1) Motivation/Focus
Having two people allows for the motivation and focus of one developer to travel through the power of osmosis (probably) to the other. One partner can help drive and motivate the other, and the role can switch throughout coding.

### 2) Knowledge Sharing
There are a couple of reasons why this is on the list:

#### The first is around Diverse teams

Better solutions happen when you have different kinds of people working together on a problem - whether it's different skillsets or mindsets. People bring different experiences to the table, assess the problem and information in different ways, and will approach and understand the problem in different ways - all of which are useful.

In bringing all these different mindsets and approaches together, you naturally discuss and work out the best approach and solution for the problem at hand. And in doing so, you are considering and understanding each other approach -  effectively testing and reducing the chance you'll pick a worse approach

#### The second is around Sharing Knowledge and confidence
People have different skillsets and knowledge - there's no getting around that. But pairing allows a really easy avenue and forum to spread that knowledge and upskill other members of your team. You will be able to teach and learn valuable hands-on skills that are only learnable from pairing with other developers - anything from language syntax and rules to overall system design.

Another benefit in doing this is that it's also showing that it is okay to not know the answer to a problem, and asking for help is much easier when there is a person right next to you!

Remember to provide feedback and constructively discuss code. There's no quicker way to kill someone's confidence than to unconstructively criticise their work and belittle what they do.

Some teams even go with the idea of not even doing Peer Reviews of the code as long as it has been paired on! (This is best left up the team to decide probably, although can be incredibly powerful if the pairs rotate through the team often).

### 3) Shared Breaks

> Sounds silly, but this is a real thing in my eyes.

In programming, flow is a very important thing.

By going for breaks and rest times at the time and same interval, it means you are constantly in sync with the other developer and allows you to progress and keep working incredibly efficiently. It also removes distractions outside of your pair and allows both developers to work in sync.

## Tips on getting the most out of pairing

### 1) Be ruthless with time
It's very easy to get bogged down on a problem and to let the other person bash their head at a keyboard for hours upon end to no avail. One of the most important things about Pair Programming is that there are two of you involved. You should always feel confident to say something like 'This doesn't seem like a good approach, maybe we should take a step back'.

Not only are you helping yourself, (as you are not providing much value in the above scenario, nor learning much), but you are also helping the other person - they might not know how long something is taking, nor when you both last evaluated where you were with the current problem.

**Fixed time limits are your friend here!**

## Ping Pong Pair Programming

> I'd like to talk about my most favourite method of pairing, called Ping Pong Pairing.

Ping Pong is a mixture of **Pair Programming** and **TDD (Test Driven Development)** - two of my favourite programming paradigms.

The idea is as follows:

Developer A Writes a failing test.

Developer B Writes the code to fix that test.

Developer B Writes the next failing test.

Developer A Writes the code to fix that test.

Developer A Writes the next failing test.

Developer B ...

And so on.

Ping Pong brings the best of both worlds together - bringing together all the benefits of small, correct pieces of code from using TDD, with the clear benefits of working closely alongside another developer.

If you've never tried Ping Pong Pairing, I would _highly_ recommend that you at least give it a try. It may take some time to get used to, but when you get into the flow and rhythm, I have found it to be one of the most powerful pairing techniques!

- Olly

repository: OllyNural/Portfolio

gha_language: JavaScript

repo_name: OllyNural/Portfolio


text:
---
layout: post
title:      "Authenticate This"
date:       2018-04-23 00:56:30 +0000
permalink:  authenticate_this
---

It's been interesting starting to build applications with Models, Views, and Controllers. It feels like I'm starting to understand what goes on behind the scenes when you log into a website.

First comes the database. You can set up ActiveRecord and use migrations to create your table with rake tasks, making sure to set up your gemfile, environment, and rakefile:

### A sample Gemfile
```
source 'https://rubygems.org'

gem 'sinatra'
gem 'activerecord'
gem 'sinatra-activerecord'
gem 'rake'
gem 'bcrypt'
gem 'require_all'
gem 'capybara'
gem 'rack_session_access'
gem 'rack-test'
gem 'shotgun'

group :development do
  gem 'pry'
  gem 'sqlite3'
  gem 'rspec'
  gem 'tux'
end
```

### A sample config/environment
```
require 'bundler'
Bundler.require

configure :development do
	set :database, {adapter: "sqlite3", database: "db/database.sqlite3"}
end
require_relative '../app/controllers/application_controller.rb'
require_all 'app/models'
```

### A sample Rakefile
```
require "./config/environment"
require "sinatra/activerecord/rake"
```

 The 'bcript' gem is used to encrypt your passwords. When you use a migration to create your users table, you can label your password column as password_digest. Since we never want to store our users' passwords in plain text in our database, this runs the passwords through a hashing algorithm. The hashed passwords are then stored, protecting the site's users if a hacker gets ahold of the database.

 Then we create a model, User, that inherits from ActiveRecord::Base and has the macro, has_secure_password. The has_secure_password macro gives us some helpful methods such as .authenticate, which we can use to check if the user input on the form matches a username and password that is stored in the database. [More Info Here](https://apidock.com/rails/v4.0.2/ActiveModel/SecurePassword/ClassMethods/has_secure_password)

 Then, we want to create our controller. It is a class that inherits from Sinatra::Base. First, we have to require our environment and our model, then inside our class, we have a bit of configuration to enable our sessions. Sessions allow us to keep track of a user by creating a hash that is stored on the server and passed to the user through cookies. We can access this hash in all of our views, and even change it so it can store the current user ID while a user is logged in.

```
require "./config/environment"
require "./app/models/user"
class ApplicationController < Sinatra::Base

  configure do
    set :views, "app/views"
    enable :sessions
    set :session_secret, "password_security"
  end

end
```
We can use helper methods within the controller to help our authentication process. Helper methods make our logic within the controller a little easier. We can use them to figure out if we should redirect the user, or render a page, based on whether or not the user is logged in, and which user it is.

```
helpers do
    def logged_in?
      !!session[:user_id]
    end

    def current_user
      User.find(session[:user_id])
    end
  end
```
We set up our routes and views. Our index page might greet the user and provide links to sign in or register. We can make a route in our controller that renders the index.erb file when a get request is sent to '/'

The '/login' and '/signup' routes each display similar forms with an input for username, password, and a submit button. The login form has an action attribute of '/login' and a method of 'post' - the registration form has an action attribute of '/signup' and a method of 'post'

Our controller receives the information the user submitted in the params hash. The post '/signup' action in the controller will try to create a new instance of user with the attributes provided by the user in params, and persist the data to the database. If the username or password is left blank, we can redirect to an error page with a link that directs back to the /signup page. Otherwise, we can sign them in right there, or redirect to our login page.

The post '/login' action in the controller will search the database for the params entered by the user. If the user is found, and the password is authenticated, then we add a new key of :user_id to our session hash, and set it equal to the id attribute of our user instance. Then, we are brought to the current user's account page. If not, we are brought to the error page.

```
 post "/login" do

    user = User.find_by(username: params[:username])
    if user && user.authenticate(params[:password])
      session[:user_id] = user.id
      redirect '/account'
    else
      redirect '/failure'
    end

  end
```

We can then use our helper methods to render the correct information on the '/account' page by making sure the user is logged in, and checking the current user. If the user is not logged in, we can redired to the error page. If the user is logged in, we can set the current user equal to an instance variable to be passed to the account.erb view so we can access and display any attribute we would like.

To logout, we simply clear the session hash.

```
get "/logout" do
    session.clear
    redirect "/"
  end
```

extension: markdown


text:
# Ophionectria tropicalis Speg., 1883 SPECIES

#### Status
SYNONYM

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

#### Published in
Anal. Soc. cient. argent. 16: 242-248 (1883)

#### Original name
Ophionectria tropicalis Speg., 1883

### Remarks
null

repository: mdoering/backbone

path: /life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Tubeufiaceae/Uredinophila/Uredinophila tropicalis/ Syn. Ophionectria tropicalis/README.md

repo_name: mdoering/backbone


text:
# element-calcum-style

## [Demo](https://yuvilio.github.io/element-calcum-style)

Calculate some data item about elements you select. Refresh it's value when you change a style with your inspector.

## Example usage

If using npm based system,

```bash
npm install element-calcum-style
```

```js
var elementCalcumStyle = require('element-calcum-style');
```

Alternately for a standalone window global, download the [latest element-calcum-style.js build here](http://yuvilio.github.io/element-calcum-style/build/element-calcum-style.js) and include it in  your script to have a global window.elementCalcumStyle available.

```html
<script src="element-calcum-style.js"></script>

```

Here is an example of an element whose children's height we want to see how they are affected when we adjust the parent element:

```html

<div class="some-element">
  <div class="box-1"></div>
  <div class="box-2"></div>
</div>
```

```js

elementCalcumStyle({
  selector: '.some-element [class*="box"] ',
  label: 'height', //data-height
  units: 'px',
  labelVisible: 1,
  eventOnElem: document.querySelector('.some-element'),
  style: 'height', //the one we'll affect in the inspector

  callback: function(el){ //the calculation we're doing on each selected element
    return el.offsetHeight;
  }
});

```

Optional css to reveal the data change visually

```css
.some-element p /* the elements we've recalculated */
{
  &:before {
    content: attr(data-height); /* the calculations we generated using the label picked (data-[label]) */

    /* The rest of the css is pretty arbitrary. adjust as needed */
    display: table;
    bottom: 20px;
    background-color: salmon;
    color: white;
    padding: 3px 2px;
    right: 0;

  }
}
```

## Questions

Isn't this the same as [element-calcum](https://github.com/yuvilio/element-calcum) ?

Not exactly.  element-calcum makes use of the DOM Level 2 [event listener API](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener) to listen for DOM events ('resize', 'mousein', ...). In contrast, element-calcum-style uses the [MutationObserver API](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to listen to style change events.

Can I use this on any web page?

Sure. You could host element-calcum locally and inject it into a page using browser extension like [Tampermonkey](http://tampermonkey.net/) or [Greasemonkey](https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/) to pull it in.

repository: yuvilio/element-calcum-style

repo_name: yuvilio/element-calcum-style


text:
# GGJ2018
Global Game Jam (Vancouver) 2018

## Project Name
[Maze Runner] (https://globalgamejam.org/2018/games/mazerunner)

## Description
A game developed using Unity (video game engine) for Global Game Jam (Vancouver) 2018.

## Screenshot
![alt text](https://github.com/johnp418/GGJ2018/blob/master/Assets/Images/Screen%20Shot%202018-01-28%20at%202.02.09%20PM.png "Maze Runner")

![alt text](https://github.com/johnp418/GGJ2018/blob/master/Assets/Images/Screen%20Shot%202018-01-28%20at%202.02.35%20PM.png "Maze Runner")

## Setup
```
git clone git@github.com:johnp418/GGJ2018.git

```
## To play
1. Memorize the directions based on number of tiles. One key press (arrow keys) equals one tile.
2. Once the timer disappears (and the maze is covered), generate a sequence of directions by pressing arrow keys. The sequence will appear on the left pane named "Your Move"
3. You may reset the sequence as you would like.
4. When you are ready to see the sequence in action, press 'Transmit' button.
5. Set your robot free.

## Credits
* Steve Kim
* Jongman Park
* Won Park
* Minje Lee


text:
# Work In Progress: Triggr

[![Build Status](https://travis-ci.org/FergusInLondon/Triggr.svg?branch=master)](https://travis-ci.org/FergusInLondon/Triggr) [![Test Coverage](https://codeclimate.com/github/FergusInLondon/Triggr/badges/coverage.svg)](https://codeclimate.com/github/FergusInLondon/Triggr/coverage) [![Code Climate](https://codeclimate.com/github/FergusInLondon/Triggr/badges/gpa.svg)](https://codeclimate.com/github/FergusInLondon/Triggr) [![Issue Count](https://codeclimate.com/github/FergusInLondon/Triggr/badges/issue_count.svg)](https://codeclimate.com/github/FergusInLondon/Triggr)
--

This is a Workflow Engine based on the [Hoa](http://hoa-project.net/En/) project's "[Ruler](http://hoa-project.net/En/Literature/Hack/Ruler.html)" library.

It's composed of `Ruleset` objects, a `ContextProvider` interface and a `EvaluationEngine`.

The primary idea is to implement the `ContextProviderInterface` on your models, and then store your rules either in the database or in individual objects - creating `Ruleset` objects from them.

The EvaluationEngine can then be triggered via a CronJob or an Events Handling system. A rough (draft API) looks something like this:

```php

$evalEngine = new EvaluationEngine();
$evalEngine->addRulesets([
	Some/Namespace/RulesetOne::class,
	Some/Namespace/RulesetTwo::class,
	Some/Namespace/RulesetThree::class,
	Some/Namespace/RulesetFour::class,
	Some/Namespace/RulesetFive::class,
]);

foreach ($contextProviders as $provider) {
	$evalEngine->evaluate( $provider );
}

```

## Testing

Testing is done via PHPSpec, and tests that the public interface works as expected - but makes no guarantees as to the internal workings. As such, if you wish to use this project please stick to the public API as seen in the above example(s).

A [full build history](https://travis-ci.org/FergusInLondon/Triggr/builds) for this project is available on Travis CI.

## License

All code contained in this repository is licensed under **[The MIT License](https://opensource.org/licenses/MIT)**.

> Copyright © 2016 Fergus Morrow<EMAIL_ADDRESS>>
> Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
>
> The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

repository: FergusInLondon/Triggr

repo_name: FergusInLondon/Triggr


text:
# NodeJS SDK Hello example

In this example we demonstrate:
- How to subscribe for realtime changes related to a specific account.
- How to decode events and other messages related to this account.

## Prerequisite

* Node.js >= [14.x installed](https://nodejs.org)
* [Docker](https://docs.docker.com/desktop/#download-and-install) installed and running
* [TONDEV CLI](https://docs.ton.dev/86757ecb2/p/179e51-tondev)

## Preparation

* [Run TON OS SE on your computer](https://docs.ton.dev/86757ecb2/p/19d886-ton-os-se)

```sh
tondev se start
```

You're all set! Check out the TON OS SE GraphQL web playground at http://<IP_ADDRESS>/graphql. For Windows, use http://<IP_ADDRESS>/graphql or http://localhost/graphql. Learn more about GraphQL API here.

See other available [TON OS SE management options in TONDEV](https://docs.ton.dev/86757ecb2/v/0/p/54722f-ton-os-se).

## Install packages & run:

```sh
npm i
npm start
```

repository: DanilaPeace/sdk-samples

repo_name: DanilaPeace/sdk-samples


text:
# New TODO task - [Download](https://github.com/nikitavoloboev/small-workflows/blob/master/todo-task/New%20todo%20task.alfredworkflow?raw=true)
> Write a task and save it to small file. Can then have Bitbar or Hammerspoon show contents of the task.

## Why use this?
I use this workflow to create (or update) a file named `todo` that I place in `~/app/hammerspoon/` directory.

I then execute this function from [Hammersoon](https://github.com/Hammerspoon/hammerspoon):
```Lua
function showTodoTask ()
hs.alert.show( ( hs.execute("~/app/hammerspoon/todo") ) )
end
hs.urlevent.bind("showTodoTask", showTodoTask)
```

Which shows the contents of this `todo` file in the middle of the screen to remind myself of what I need to do. It looks like this:

![](https://i.imgur.com/QIqdszD.png)

You can also point [BitBar](https://github.com/matryer/bitbar) or [TextBar](http://richsomerfield.com/apps/textbar/) to read the content of the file and that will show the `todo` task in your menu bar.

## Setup
You should change this folder before running the workflow and you can do it by double clicking `Run Script` object here:

![](https://i.imgur.com/gjnm7OG.png)

And then changing the folder here:

![](https://i.imgur.com/agl6XXD.png)

Default folder is `~/app/hammerspoon` which most certainly won't work for you as you won't have this folder. So change it to where you want the `todo` file to live!

## Contributing
See [contribution guidelines](../CONTRIBUTING.md#readme).


text:
# Russula nauseosa var. flavida Cooke VARIETY

#### Status
ACCEPTED

#### According to
Index Fungorum

#### Published in
Illustrations of British Fungi (Hymenomycetes) (London) 7: (1053) 1102 (1890)

#### Original name
Russula nauseosa var. flavida Cooke

### Remarks
null


text:
# Configuration

## Config

You may need to configure some options to tweak some of the plugin internals. You don't have to configure anything to get validation going but some defaults may require adjusting.

```js
import { configure } from 'vee-validate';

const config = {
  classes: {
    valid: 'is-valid',
    invalid: 'is-invalid'
  },
  bails: true,
  skipOptional: true,
  mode: 'aggressive',
  useConstraintAttrs: true
};

// Sets the options.
configure(config);
```

You can update the config with the `configure` method at any time during your app life-cycle.

## Reference

| Property     |   Type    |    Default     | Description                                                                |
| :----------- | :-------: | :------------: | :------------------------------------------------------------------------- |
| classes      | `object`  |                | The classes to be applied depending on the state of the input.             |
| mode         | `string`  | `'aggressive'` | Sets the interaction mode to one of the predefined modes.                  |
| bails        | `boolean` |     `true`     | Whether failed validations should exit or all rules are run to completion. |
| skipOptional | `boolean` |     `true`     | Optional fields with empty values will be excluded from validation.        |
| useConstraintAttrs | `boolean` | `true` | Enables [rule inference](./guide/html5-validation.md) on native HTML inputs. |
| defaultMessage | `string | () => string` | "{\_field\_} is not valid." | The fallback message for rules without messages. |

repository: alex-bilyk/vee-validate

repo_name: alex-bilyk/vee-validate


text:
+++
image = "img/portfolio/opencv-logo.png"
showonlyimage = false
title = "Detect Colours"
draft = false
weight = 3
+++

Use computer vision to detect colour in an image or an object.

<!--more-->

# Longer description

If you detect a certain colour (say red), trigger an action (e.g., get the computer to make a noise).

Use the OpenCV library.

blah blah

## Resources

* https://www.instructables.com/Color-Detection-in-Python-Using-OpenCV/
* https://data-flair.training/blogs/project-in-python-colour-detection/

---

* **Level**: Intermediate
* **Badge**: link to badge
* **Mentors**: one or more volunteers

repository: ewan-klein/prewiredplusplus

repo_name: ewan-klein/prewiredplusplus


text:
This is a sample CDK program. This program does not accept inputs and it is somewhat opinionated in how it works. It creates a VPC, an ECS cluster and it deploys Yelb as a group of ECS services.

In order to use CDK make sure you have it properly [installed on your system](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) or use [eksutils](https://github.com/mreferre/eksutils).

Once you have the pre-requisite above, just launch:

```
npm install
cdk deploy
```

repository: mreferre/yelb

gha_language: TypeScript

repo_name: mreferre/yelb


text:
# ䷄ Xū

* Waiting

> Chinese: xū 需 ䷄

**䷄ Xū** intimates that, with the sincerity which is declared in it, there will be brilliant success. With firmness there will be good fortune; and it will be advantageous to cross the great stream.

1. The first `NINE`, undivided, shows its subject waiting in the distant border. It will be well for him constantly to maintain (the purpose thus shown), in which case there will be no error.

> **䷄** changing to [**䷯**](e4ba95jing.md)

> Matching Line 1 in Adjacent Hexagram: [**䷅**](e8aebcsong.md#6.1)

2. The second `NINE`, undivided, shows its subject waiting on the sand (of the mountain stream). He will (suffer) the small (injury of) being spoken (against), but in the end there will be good fortune.

> **䷄** changing to [**䷾**](e697a2e6b58ejiji.md)

> Matching Line 2 in Adjacent Hexagram: [**䷅**](e8aebcsong.md#6.2)

3. The third `NINE`, undivided, shows its subject in the mud (close by the stream). He thereby invites the approach of injury.

> **䷄** changing to [**䷻**](e88a82jie.md)

> Matching Line 3 in Adjacent Hexagram: [**䷅**](e8aebcsong.md#6.3)

4. The fourth `SIX`, divided, shows its subject waiting in (the place of) blood. But he will get out of the cavern.

> **䷄** changing to [**䷪**](e5a4acguai.md)

> Matching Line 4 in Adjacent Hexagram: [**䷅**](e8aebcsong.md#6.4)

5. The fifth `NINE`, undivided, shows its subject waiting amidst the appliances of a feast. Through his firmness and correctness there will be good fortune.

> **䷄** changing to [**䷊**](e6b3b0tai.md)

> Matching Line 5 in Adjacent Hexagram: [**䷅**](e8aebcsong.md#6.5)

6. The topmost `SIX`, divided, shows its subject entered into the cavern. (But) there are three guests coming, without being urged, (to his help). If he receive them respectfully, there will be good fortune in the end.

> **䷄** changing to [**䷈**](e5b08fe7959cxiaoxu.md)

> Matching Line 6 in Adjacent Hexagram: [**䷅**](e8aebcsong.md#6.6)

## Notes

**䷄ Xū** means waiting. Strength confronted by peril might be expected to advance boldly and at once to struggle with it; but it takes the wiser plan of waiting till success is sure. This is the lesson of the hexagram. That `sincerity is declared in it` is proved from the fifth line in the position of honour and authority, central, itself undivided and in an odd place. In such a case, nothing but firm correctness is necessary to great success.

`Going through a great stream`, an expression frequent in the [Yì Jīng](https://ctext.org/book-of-changes), may mean undertaking hazardous enterprises, or encountering great difficulties, without any special reference; but more natural is it to understand by the great stream, `the Yellow river`, which the lords of [Zhōu](https://en.wikipedia.org/wiki/Zhou_dynasty) must cross in a revolutionary movement against the [dynasty of Yīn](https://en.wiktionary.org/wiki/殷代) and its tyrant. The passage of it by [king Wǔ](https://en.wikipedia.org/wiki/King_Wu_of_Zhou), the son of [Wén](https://en.wikipedia.org/wiki/King_Wen_of_Zhou) in B. C. 1122, was certainly one of the greatest deeds in the history of China. It was preceded also by long waiting, till the time of assured success came.

`The border` under line 1 means the frontier territory of the state. There seems no necessity for such a symbolism. `The sand` and `the mud` are appropriate with reference to the watery defile; but it is different with `the border`. The subject of the line appears at work in his distant fields, not thinking of anything but his daily work; and he is advised to abide in that state and mind.

`The sand` of paragraph 2 suggests a nearer approach to the defile, but its subject is still self-restrained and waiting. I do not see what suggests the idea of his suffering from `the strife of tongues`.

In paragraph 3 the subject is on the brink of the stream. His advance to that position has provoked resistance, which may result in his injury.

Line 4 has passed from the inner to the upper trigram, and entered on the scene of danger and strife; -- `into the place of blood`. Its subject is `weak and in the correct place for him`; he therefore retreats and escapes from the cavern, where he was engaged with his enemy.

Line 5 is strong and central, and in its correct place, being that of honour. All good qualities therefore belong to the subject of it, who has triumphed, and with firmness will triumph still more.

Line 6 is weak, and has entered deeply into the defile and its caverns. What will become of its subject? His correlate is the strong line 3 below, which comes with its two companions to his help. If they are respectfully received, that help will prove effectual. P. Regis tries to find out a reference in these `three guests` to three princes who distinguished themselves by taking part with [Zhōu](https://en.wikipedia.org/wiki/Zhou_dynasty) in its struggle with [Yīn](https://en.wiktionary.org/wiki/殷代) or [Shāng](https://en.wikipedia.org/wiki/Shang_dynasty); see [Appendixes II](appendix02s1.md#p-278). I dare not be so confident of any historical reference.

license: Unlicense

gha_license_id: Unlicense


text:
---
title: KBD67 X 8008 (MKII)
date: 2020-07-14T17:44:28.534Z
uuid: 891bf808-8a36-421f-b120-08d035689538
keywords: Mechanical Keyboard, KBD67 MKII, Zykos, Polycarbonate keyboard
image: /assets/images/keyboards/kbd67-mkii/1.jpeg
build:
  case: KBD67-MKII - Polycarbonate
  plate: Brass
  stabs: Durock
  switches: Zykos
  keycaps: GMK 8008 (base + accent)
  pcb: MKII Solder
  mount: Top
---

This build was a labor of love and some pain and misery. But in the end, I am quite pleased with how it turned out.

This build started a couple of days prior. I have had a Mira SE with a stainless steel plate that has been in a pre-build mode for a while. I wasn't sure what switches I wanted to use with it, and I did not have a QMK compatible PCB.

Someone on r/mm was kind enough[^kind] to sell me a spare h87a, so it was time to move onto the switches.

I had 90 Holy Pandas sitting around, waiting for a good project. I thought about using them but then decided to go bigger....and make some Zykos.

Zykos are a frankenswitch (created by Chewy of MechsOnDeck) made with the bottom housing of a Zealios, the top of a YOK, and a halo stem (your preference on spring). Since I had the Holy Panda's on hand, I decided to order some 78g Zealios and build me some Zykos.

I had heard many horror stories about things going wrong with both building the Zykos and then installing them in a PCB. Despite this, I had zero issues making the switches (beginner's luck).

With the switches assembled[^ahhh] (and lubed), it was time to start the build. I added the stabilizers to the PCB and grabbed the stainless steel plate. Then everything came to a crashing halt. The tolerances for the stainless steel plate were super tight (or perhaps the Zealios bottoms were slightly out of spec). It took quite a bit to get the first couple of switches in, and I started to get concerned about properly installing the switches in the middle of the plate. Also, I only have 90 Zykos and would need 88 to complete the Mira build. I started to get concerned I would end up short a couple of switches and decided it was best to go in a different direction.

As luck would have it, I had a Polycarbonate KBD67 MKII and brass plate arriving the next day. This felt like a good fallback option for the Zykos. In my mind, the brass plate and polycarbonate would play nicely with Zykos.

Unfortunately, similar to the stainless steel plate, the brass plate's tolerances were tight as well. How tight you ask?

Knowing I needed 68 Zykos to complete the build and had 90 available gave me some solace. In the end, only two Zykos were damaged beyond repair, which was related to needing to remove a couple of them.

In an effort not to destroy the pins while trying to get the switches in the plate and PCB, I installed most of the switches into the plate and then carefully aligned the PCB afterward. Aligning all the pins was a huge PITA. In hindsight, I probably should have done 10 or 15 this way. But in the end, I got them all lined up, fixed a bent pin (or two), and soldered it up and was ready to go.

I put on some keycaps and, at the last second, decided to swap the spacebar.  Do to all of my handling and moving around during the alignment, the spacebar wire popped out. It must have been hanging on by a thread, and once I pulled the spacebar off, it also came out.

Knowing how tight all the switches were, I was not eager to desolder the entire PCB and getting tools between the plate and PCB was not possible. Thankfully, after a couple of minutes of trying, I could see that if I removed the spacebar switch and a couple behind it, it would open things up. I was able to wrap a bit of solder wire around the stabilizer bar, then pulled it into the stabilizer and clicked it in.

![Busted Wire](/assets/images/keyboards/kbd67-mkii/wire.jpeg)

## Onto the build

This is my first polycarbonate build. Once complete, I immediately regretted not grabbing the Klippe PC and getting in on the Rutika GB recently (really regret this one). The feel and sound from the polycarbonate are quite lovely. I am usually not an RGB fan (and this PCB has none), but the polycarbonate has heft and enough clarity to make it worthwhile.

I was not aware of when I purchased this board because the bottom row has limited layout options. This is a good thing[^well]. However, I had blindly assumed there would be a 7U option, which sadly, there is not. The only options on the bottom row are 6.25U spacebar or split spacebar.

Other than that, I have no real issues. The KBD676 MKII is a very nice board, especially for the price.

### Update

The Zykos are very aggressive. After listening to some sound profiles, I wanted to [tone down the spacebar](https://youtu.be/MMyvfpUWymw) a bit. I recently caught one [Langlandia's](https://www.twitch.tv/langelandia) Iron165 builds (rubbing two of them right in my mug) and noticed he was using a silent switch on the spacebar. I typically use a 98g spring on the spacebar to tone things down a bit, but I decided to give a silent Healio a try. I am not sure I will do this all the time, but for the Zykos + brass plate, I think it is a win.

[^kind]: I truly mean kind enough. There was an open group buy for the h87a and he essentially old it to me for what it would cost to replace at GB + shipping. Thank you again!
[^ahhh]: If you go this route, set aside a couple of hours. It is quite a bit of work to disassemble, lube, and then reassemble.
[^well]: Well, I guess this assumes the limited layout options include your preferred layout options. :P


text:
This directory is for files that were used for managing the site for the NSF SatC conference but aren't necessary to
get the application working at a basic level. If you wish to make use of some of the files, be aware that in their current state
some may not work from this directory, and would have to be moved into the rematchr directory in order to work.

File Descriptions
=============
- breakouts.py: Contains a python list of information about breakout groups.
- collaborators.py:  A module that created a csv file to show the PI's and their collaborators. This was used in the matching phase
of the overall project, during which we wanted to avoid matching two PI's who had worked together already.
- fixnew.py: A script written to update the database with some new information. Not a general use program.
- generate_schedules.py: Used to create the meeting schedules for each attendee.
- load_breakouts.py: Loaded the information about breakouts into the database.
- load_matches.py: Takes a groups.csv file created by the matching process and loads that information into the database.
- login.sh: A shell script that was used for logging into the server.
- parsecsv.py: A script that was used to create an "emails2texts.pickle" file that was used in the modeling process. It takes a csv
file with information about attendees and uses the aggregated investigators and projects models to create a mapping (literally
a python dictionary) from each attendees email to pure text versions of their project abstracts.
- rating.py: A django form for PI's to rate their meetings.
- soupextract.py: Scraped pdfs from websites when our plan was to use attendees entire publications as the text information for modeling
instead of the NSF project abstracts.
- stopwords: words to exclude from counting/wordclouds/text analysis.
- testemails.py: Part of the process for the NSF conference was an email blast; this tested the provided addresses.
- updateattendees.py: Like fixnew.py, another script to update the database with some new information. Not a general use program.
- utils.py: A copy of utils.py from the rematchr directory.
- wordcounts.py: Processed text and counted words. Once used for wordclouds or other graphics.

repository: ctames/conference-host

repo_name: ctames/conference-host


text:
# Vanilla-JS-Library-Boilerplate

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A simple boilerplate for building a JavaScript library. It uses ES6 modules and only exposes the necessary functions from within. This is meant as a starting point. Includes a basic counter in the library.

## Quick Start

1. Clone or Download the repository
2. run `yarn install`
3. run `yarn start` to view the demo page at `localhost:8031`
4. Adjust to your liking

## Scripts

- `yarn start` for development, shows a demo page where you can test your libaray
- `yarn build` for building and readying for production
- `yarn test` for running all jest tests
- `yarn lint` runs eslint

There are a few other scripts stet up for commits and pushes. Check out package.json and

## Includes the following for your convenience

- [Babel](https://babeljs.io/) (for ES6)
- [Webpack](https://webpack.js.org/) (for bundling)
- [Yarn](https://yarnpkg.com/lang/en/) (for package management)
- [ESLint](https://eslint.org/) (for linting)
- [Jest](https://facebook.github.io/jest/) (for testing)
- [Husky](https://github.com/typicode/husky) (for pre-commit and pre-push hooks)

repository: eljamez/Vanilla-JS-Library-Boilerplate

repo_name: eljamez/Vanilla-JS-Library-Boilerplate


text:
# Nduja

Nduja is a software that de-anonymize crypto-currencies' addresses.

The theory behind Nduja are explained [in this repository](https://github.com/mzanella/CNSProject).

## Getting Started

You can either clone the repo or download a release.
To run this program you have two alternatives: install it natively or using
docker.

### The Native Way

1. Install python3.5 or above
2. Install pip3
3. Install the python graph-tool, following [these instructions](https://git.skewed.de/count0/graph-tool/wikis/installation-instructions)
4. Clone or download the repository
5. Go in the project main directory
6. Install the python dependencies `pip install -r requirements`
7. Setup the configuration file:
   - `cp conf_reference.json Nduja/conf.json`
   - Fill `Nduja/conf.json` with your API keys
8. Setup the format file:
   - `cp format_reference.json Nduja/format.json`
   - Modify the `Nduja/format.json` to contain only the cryptocurrencies you are interested in.
9. Run nduja: `python3.x Nduja`

### The Docker Way

1. Install docker and docker-compose
2. Clone or download the repository
3. Go in the project main directory
7. Setup the configuration file:
   - `cp conf_reference.json Nduja/conf.json`
   - Fill `Nduja/conf.json` with your API keys
8. Setup the format file:
   - `cp format_reference.json Nduja/format.json`
   - Modify the `Nduja/format.json` to contain only the cryptocurrencies you are interested in.
4. `docker-compose up --build`

## Running the tests

## Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

## Authors

* **Mirko Bez** - *Initial work* - [herrBez](https://github.com/herrBez)
* **Marco Zanella** - *Initial work* - [mzanella](https://github.com/mzanella)

See also the list of [contributors](https://github.com/herrBez/Nduja/contributors) who participated in this project.

## License

This project is licensed under the 3-Clause BSD-License - see the [LICENSE](LICENSE) file for details

repository: herrBez/Nduja

gha_language: Python

repo_name: herrBez/Nduja


text:
---
layout: post
title: GSoC Week 10: Nuclear moon bases
date: 2018-07-24T00:30:00Z
tags: scummvm
---

Last week I worked on mission 6, "That Old Devil Moon". It features some interesting lore
of two ancient civilizations that annihilated each other through the use of nuclear
weaponry. What a totally, uh, alien and unthinkable prospect, haha...

This mission features the most obscure puzzle in the game, which involves converting
"sacred numbers" from base 10 to base 3 to crack passcodes! While I personally can handle
a bit of base conversion, the even bigger sin is that the hint required to open the door
is missable!  I definitely had to look up a walkthrough here.

{% include image.html url="/images/gsoc-week-10-base3.png" %}

Incidentally, while implementing the text input boxes, I found a way to crash the game.
Simply fill up the box, then repeatedly press the "end" key, enter a character, press
"end" again, etc. Soon the text buffer overflows into something that's probably important
and the game crashes. This works because the "end" button is the only one that doesn't
check if the length of the string exceeds the maximum text size. Naturally this is fixed
in scummvm.

In addition, this mission, too, has some ways to get an infinite score, by repeatedly
scanning or using the computers in the final room. Using McCoy's tricorder on the air in
this room also works. That's all in the way of bugs that I've found, though.

GSoC officially ends next week. I've opened up my pull request to the main branch, though
the engine is still incomplete, so I can continue working on it in-tree; in addition to
working on the final mission this week, I have some feedback to take care of before the
pull request gets accepted.


text:
# `selectors`

`selectors` is a library for parsing and converting diagnostics selectors.

## Building

This project should be automatically included in builds.

## Using

`selectors` can be used by depending on the
`//src/lib/diagnostics/selectors` gn target and then using
the `selectors` crate in a rust project.

`selectors` is not available in the sdk and is intended to be used only by
diagnostics binaries.

## Testing

Unit tests for `selectors` are available in the
`selectors` package:

```
$ fx test selectors_tests
```

You'll need to include `//src/lib/diagnostics/selectors:tests` in your
build, either by using `fx args` to put it under `universe_package_labels`, or
by `fx set [....] --with //src/lib/diagnostics/selectors:tests`.

repository: gnoliyil/fuchsia

repo_name: gnoliyil/fuchsia


text:
# ON-SURVEYS
 Web platform for making online surveys and questionnaires.

### Getting started
- Install NodeJS
- Clone this repository in the `on-surveys` folder (and make it current directory via `cd on-surveys`)
- Install npm packages via the
```sh
$ npm install
```
- Run the server via the
```sh
$ npm run start

```

At this point demo on-surveys service will be available at the http://localhost:80 address.
If everything is ok, you should see project home page with login and registration form.
This project uses MongoDB as a database so make sure you install that too.

## Authors

* **Olympia Nika**

## License

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

repository: OlyNk/on-surveys

repo_name: OlyNk/on-surveys


text:
# Sticks AI
* A program that uses Expectimax (or Minimax) search to win a game of sticks
* The rules of Sticks can be found here (with some differentiations noted below): https://en.wikipedia.org/wiki/Chopsticks_(hand_game)
  - Note that this program can only support 2 players (which can be any combination of humans vs AIs)
  - No player can split and have a hand with at least five fingers after the split, or have the same configuration as before the split
  - If a player's hand reaches at least five fingers, it is considered a dead hand
* Run Game.py to start the game and enter in the number of humans playing (0 - 2)
* Supported commands:
  - tap [your hand] [opponent hand]
    - left hand is represented by 0
    - right hand is represented by 1
  - split [new left hand value] [new right hand value]


text:
---
layout: event
title: Google IO Extended
category: events
starttime: 2013-05-26 11:00:00
endtime: 2013-05-26 14:00:00
author: [GDG Group]
venue: NSL
---

Wondering what Google I/O is?

Have a look at it [here](https://developers.google.com/events/io/).

##Agenda##
*	Skype chats with eminent Google Developers in India
*	Hands-on Android Session
*	Introduction to Android
*	Course Overview
*	Introduction
*	Android Background
*	Android Architecture
*	Android Applications
*	APIs
*	Making a Basic Android Application

##Extras##
We did have a pizza party sponsored by GDG after the end of the talk.

Event pics can be found on our [fb-page](https://www.facebook.com/media/set/?set=a.562633230456313.1073741830.543079142411722&type=3)


text:
## Example how to use the serverless-vault-plugin

### Install docker and run vault in your local env
* To install docker look at [docker instalation page](https://docs.docker.com/install/)

Then, run:
```
sudo docker run -dt --cap-add=IPC_LOCK -e "VAULT_DEV_ROOT_TOKEN_ID=4bea777b-9752-4c57-972d-02d091715254" -e 'VAULT_DEV_LISTEN_ADDRESS=<IP_ADDRESS>:8200' vault
```

It will create a docker container with vault and a root token: 4bea777b-9752-4c57-972d-02d091715254.

Then, install npm and nodeJs: [see it here](https://www.npmjs.com/get-npm)

then, run:
```
npm i
```
It will create a `node_modules` path.

Access your container and add the following commands (inside of the container).
```
export VAULT_ADDR='http://<IP_ADDRESS>:8200'

vault write secret/example-app SECRET_1="foo" SECRET_2="bar" SECRET_3="foobar"
```

Set your token as env var in your deployment machine (or your local machine) `*Pssiu: It is just to not let you commit any token on serverless.yml file.`
```
export TOKEN_VAULT=4bea777b-9752-4c57-972d-02d091715254.
```
Then, finnaly run your app deployment application:
```
sls deploy -s dev
```

### Example how to use the plugin with Userpass method auth
Create a user/ pass on vault. Access your vault container and run: (inside of the container)
```
export VAULT_ADDR='http://<IP_ADDRESS>:8200'

vault login -method=userpass username=myuser password=mypassword
```

then, add it your `serverless.yml`
```
custom:

  vault:
    method: "userpass"
    user: "myuser"
    password: "mypassword"
    url: "https://localhost:8200"
    secret: "secret/example-app"
    ssl_check: false
  kms:
    keyId: ${env:KEY_KMS_ID}

```

### Sugestions:
1. User always a valid certificate for vault
2. Get preference to use userpass method with a expiration token ttl, userpass will retrieve a temp token to retrieve the passwords
3. Never commit your passwords or users, use it as your env vars or try to create it in a separeted file the you can add in your gitignore
4. Look always to your policies, set the right policies to your lambda app (to use kms using always less permissions as possible)
5. Create a fork from this repository and contribute

Cheers!

repository: bichotll/serverless-vault-plugin

repo_name: bichotll/serverless-vault-plugin