text:
# Announce: Rakudo Star Release 2017.01

## A useful and usable production distribution of Perl 6

On behalf of the Rakudo and Perl 6 development teams, I'm pleased to
announce the November 2016 release of "Rakudo Star", a useful and usable
production distribution of Perl 6. The tarball for the January 2017 release
is available from <http://rakudo.org/downloads/star/>.

Binaries for macOS and Windows (64 bit) are also available.

This is the sixth post-Christmas (production) release of Rakudo Star and
implements Perl v6.c. It comes with support for the MoarVM backend (all module
tests pass on supported platforms).

This is the first Rakudo Star release to include "zef" as module installer.
"panda" is to be shortly replaced by "zef" and will be removed in the near
future.

It's hoped to produce quarterly Rakudo Star releases during 2017 with 2017.04
(April), 2017.07 (July) and 2017.10 (October) to follow.

Please note that this release of Rakudo Star is not fully functional with the
JVM backend from the Rakudo compiler. Please use the MoarVM backend only.

In the Perl 6 world, we make a distinction between the language ("Perl 6") and
specific implementations of the language such as "Rakudo Perl".

This Star release includes [release 2017.01] of the [Rakudo Perl 6 compiler],
version 2017.01 of [MoarVM], plus various modules, documentation, and other
resources collected from the Perl 6 community.

[release 2017.01]: https://raw.githubusercontent.com/rakudo/rakudo/2017.01/docs/announce/2017.01.md
[Rakudo Perl 6 compiler]: http://github.com/rakudo/rakudo
[MoarVM]: http://moarvm.org/

The Rakudo compiler changes since the last Rakudo Star release of 2016.11 are
now listed in "2016.12.md" and "2017.01.md" under the "rakudo/docs/announce"
directory of the source distribution.

Notable changes in modules shipped with Rakudo Star:

    + DBIish: Pg: TypeConverter post-merge cleanup
    + Linenoise: Remove dependency on Native::Resources
    + Pod-To-HTML: Bump version for #22 fix
    + Terminal-ANSIColor: Drop 'nqp' dependency
    + doc: Too many to list
    + json: Fix parsing of string literals with a leading combining character.
    + json\_fast: bump version since we now escape null bytes
    + panda: modified to warn of its removal in the short term
    + perl6-http-easy: Several pull requests merged
    + perl6-lwp-simple: Tweak tests to work with TAP::Harness
    + perl6-pod-to-bigpage: bump version
    + test-mock: Bump version.
    + zef: imported

There are some key features of Perl 6 that Rakudo Star does not yet
handle appropriately, although they will appear in upcoming releases.
Some of the not-quite-there features include:

  * advanced macros
  * non-blocking I/O (in progress)
  * some bits of Synopsis 9 and 11

There is an online resource at <http://perl6.org/compilers/features>
that lists the known implemented and missing features of Rakudo's
backends and other Perl 6 implementations.

In many places we've tried to make Rakudo smart enough to inform the
programmer that a given feature isn't implemented, but there are many
that we've missed. Bug reports about missing and broken features are
welcomed at<EMAIL_ADDRESS>
See <http://perl6.org/> for links to much more information about
Perl 6, including documentation, example code, tutorials, presentations,
reference materials, design documents, and other supporting resources.
Some Perl 6 tutorials are available under the "docs" directory in
the release tarball.

The development team thanks all of the contributors and sponsors for
making Rakudo Star possible. If you would like to contribute, see
<http://rakudo.org/how-to-help>, ask on the<EMAIL_ADDRESS>mailing list, or join us on IRC \#perl6 on freenode.

repository: rba/star

repo_name: rba/star


text:
CLOUD-LIKE VPC ENVIRONMENT DONE IN LIBVIRT / QEMU ON LINUX
==========================================================

## 1. PURPOSE

Use local resources (cpu, memory and disk storage) for creating VPC-like fully-automated environment for research and development.

## 2. ARCHITECTURE

![fake-vpc's architecture](docs/svg/architecture.svg)

## 3. REQUIREMENTS

### 3.1 SOFTWARE

__System packages__:
- cdrkit (for mkisofs)
- cloud-utils (for preparing VM initialization media)
- gcc
- git
- gnumake
- go (for building extra terraform providers)
- libffi (devel)
- libvirt (devel)
- libxslt (devel)
- openssl (devel)
- pipenv
- pkgconfig
- python3
- rsync (needed by ansible)

__Base software__:
- [packer (Hashicorp)](https://releases.hashicorp.com/packer/)
- [terraform (Hashicorp)](https://releases.hashicorp.com/terraform/)
- [terragrunt (Github)](https://github.com/gruntwork-io/terragrunt/releases)

__Terraform providers__:
- [terraform-provider-external (Hashicorp)](https://releases.hashicorp.com/terraform-provider-external/)
- [terraform-provider-libvirt (Github)](https://github.com/dmacvicar/terraform-provider-libvirt/releases)
- [terraform-provider-local (Hashicorp)](https://releases.hashicorp.com/terraform-provider-local/)
- [terraform-provider-null (Hashicorp)](https://releases.hashicorp.com/terraform-provider-null/)
- [terraform-provider-template (Hashicorp)](https://releases.hashicorp.com/terraform-provider-template/)

__Python packages__:
- ansible
- ipaddress
- pyyaml
- terraform\_external\_data

### 3.2 INCLUDED AUTOMATION

If you're using [NixOS](https://nixos.org/) you can just enter Nix shell and continue from there:
```bash
$ nix-shell
```

Otherwise just install prerequisites listed above [3.1](#31-software) as you would normally do in your Linux distro.

All the "Hashicorp" providers can be installed manually or by `terraform` itself. The "libvirt" provider has to be built from source.

For your convenience we've included `makefile` scripts that can install and build all the requirements. If you've decided to go with the "makefile" way,
just make sure that your `$GOPATH` and `$PATH` variables point to existing directories beforehand:

```bash
$ cat ~/.profile
```
```bash
...
export GOPATH="$HOME/go"
export PATH="$GOPATH/bin:$PATH"
...
```

To install requirements  run:

```bash
$ make requirements _GOPATH_=~/go
```
[>>> CONSOLE OUTPUT <<<](docs/make-requirements-output.md)

To verify golang binaries run:

```bash
$ ls -1F ~/go/bin/
```
```
packer@
packer-1.5.1*
terraform@
terraform-0.12.19*
terraform-provider-external@
terraform-provider-external-1.2.0*
terraform-provider-libvirt@
terraform-provider-libvirt-0.6.1*
terraform-provider-local@
terraform-provider-local-1.4.0*
terraform-provider-null@
terraform-provider-null-2.1.2*
terraform-provider-template@
terraform-provider-template-2.1.2*
terragrunt@
terragrunt-0.21.11*
```

To verify python packages run:

```bash
$ ls -1F .venv/lib/python3.7/site-packages/
```
```
ansible/
ansible-2.9.4.dist-info/
ansible_test/
cffi/
cffi-1.13.2.dist-info/
_cffi_backend.cpython-37m-x86_64-linux-gnu.so*
cryptography/
cryptography-2.8.dist-info/
easy_install.py
ipaddress-1.0.23.dist-info/
ipaddress.py
jinja2/
Jinja2-2.11.0.dist-info/
markupsafe/
MarkupSafe-1.1.1.dist-info/
pip/
pip-20.0.2.dist-info/
pkg_resources/
__pycache__/
pycparser/
pycparser-2.19.dist-info/
PyYAML-5.3.dist-info/
setuptools/
setuptools-45.2.0.dist-info/
six-1.14.0.dist-info/
six.py
terraform_external_data/
terraform_external_data-1.0.1.dist-info/
wheel/
wheel-0.34.2.dist-info/
yaml/
```

```bash
$ PIPENV_IGNORE_VIRTUALENVS=1 PIPENV_VENV_IN_PROJECT=1 pipenv run pip list
```
```
Package                 Version
----------------------- ----------
ansible                 2.9.4
certifi                 2019.6.16
cffi                    1.13.2
cryptography            2.8
ipaddress               1.0.23
Jinja2                  2.11.0
MarkupSafe              1.1.1
pip                     20.0.2
pipenv                  2018.11.26
pycparser               2.19
PyYAML                  5.3
setuptools              45.2.0
six                     1.14.0
terraform-external-data 1.0.1
virtualenv              16.4.3
virtualenv-clone        0.5.3
wheel                   0.34.2
```

## 4. USAGE

### 4.1 CREATE VPC ENVIRONMENT

Example config `LIVE/vpc1/terragrunt.hcl`:
```hcl
include {
    path = "${find_in_parent_folders()}"
}

terraform {
    source = "../../terraform/vpc/"
}

inputs = {
    vpc_id = "vpc1"

    ssh_keys = [
        file("~/.ssh/id_ed25519.pub"),
    ]

    pool_directory = "/stor/libvirt/fake_vpc"

    base_images = {
        utl = "../../../../../packer/utl/.cache/output/packer-utl.qcow2"
        vpc = "../../../../../packer/vpc/.cache/output/packer-vpc.qcow2"
    }

    networks = [
        {
            name    = "vpc1gw"
            subnet  = "<IP_ADDRESS>/16"
            macaddr = "52:54:00:69:00:%02x"
        },
        {
            name    = "vpc1a"
            subnet  = "<IP_ADDRESS>/24"
            macaddr = "52:54:00:10:01:%02x"
        },
        {
            name    = "vpc1b"
            subnet  = "<IP_ADDRESS>/24"
            macaddr = "52:54:00:10:02:%02x"
        },
        {
            name    = "vpc1c"
            subnet  = "<IP_ADDRESS>/24"
            macaddr = "52:54:00:10:03:%02x"
        },
    ]

    utl_hosts = [
        {
            name   = "vpc1u"
            vcpu   = 1
            memory = "512"
        },
    ]

    vpc_hosts = [
        {
            name    = "vpc1a"
            vcpu    = 4
            memory  = "3096"
            storage = "128849018880"  # 120GiB
        },
        {
            name    = "vpc1b"
            vcpu    = 4
            memory  = "3096"
            storage = "128849018880"  # 120GiB
        },
        {
            name    = "vpc1c"
            vcpu    = 4
            memory  = "3096"
            storage = "128849018880"  # 120GiB
        },
    ]
}
```

To deploy "vpc1" environment run (packer images will be built automatically):
```bash
$ make vpc-apply
```
[>>> CONSOLE OUTPUT <<<](docs/vpc-apply-output.md)

To list running libvirt domains:
```bash
$ sudo virsh list
```
```
 Id   Name    State
-----------------------
 5    vpc1u   running
 6    vpc1c   running
 7    vpc1b   running
 8    vpc1a   running
```

### 4.2 CREATE K8S ENVIRONMENT

Example config `LIVE/k8s1/terragrunt.hcl`:
```hcl
include {
    path = "${find_in_parent_folders()}"
}

terraform {
    source = "../../terraform/k8s/"
}

inputs = {
    k8s_id = "k1"

    availability_zones = [
        {
            name   = "vpc1a"
            subnet = "<IP_ADDRESS>/24"
        },
        {
            name   = "vpc1b"
            subnet = "<IP_ADDRESS>/24"
        },
        {
            name   = "vpc1c"
            subnet = "<IP_ADDRESS>/24"
        },
    ]

    ssh_keys = [
        file("~/.ssh/id_ed25519.pub"),
    ]

    master = {
        count   = 3
        vcpu    = 2
        memory  = "2048"
        image   = "../../../../../packer/k8s/.cache/output/packer-k8s.qcow2"
        storage = "17179869184"  # 16GiB
    }

    compute = {
        count   = 1
        vcpu    = 2
        memory  = "1024"
        image   = "../../../../../packer/k8s/.cache/output/packer-k8s.qcow2"
        storage = "17179869184"  # 16GiB
    }
}
```

To deploy "k8s1" environment run (packer image will be built automatically):
```bash
$ make k8s-apply
```
[>>> CONSOLE OUTPUT <<<](docs/k8s-apply-output.md)

To list running libvirt (nested) domains:
```bash
$ make ssh-utl
```
```
Warning: Permanently added '<IP_ADDRESS>' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-74-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun Feb 16 19:45:54 UTC 2020

  System load:  0.0               Users logged in:     0
  Usage of /:   14.8% of 9.52GB   IP address for ens3: <IP_ADDRESS>
  Memory usage: 23%               IP address for ens4: <IP_ADDRESS>
  Swap usage:   0%                IP address for ens5: <IP_ADDRESS>
  Processes:    86                IP address for ens6: <IP_ADDRESS>

8 packages can be updated.
8 updates are security updates.

Last login: Sun Feb 16 19:15:00 2020 from <IP_ADDRESS>
```
```bash
ubuntu@vpc1u:~$ ssh vpc1a sudo virsh list
```
```
Warning: Permanently added 'vpc1a,<IP_ADDRESS>' (ECDSA) to the list of known hosts.
 Id    Name                           State
----------------------------------------------------
 1     k1c1                           running
 2     k1m1                           running
```
```bash
ubuntu@vpc1u:~$ ssh vpc1b sudo virsh list
```
```
Warning: Permanently added 'vpc1b,<IP_ADDRESS>' (ECDSA) to the list of known hosts.
 Id    Name                           State
----------------------------------------------------
 1     k1m2                           running
```
```bash
ubuntu@vpc1u:~$ ssh vpc1c sudo virsh list
```
```
Warning: Permanently added 'vpc1c,<IP_ADDRESS>' (ECDSA) to the list of known hosts.
 Id    Name                           State
----------------------------------------------------
 1     k1m3                           running
```

### 4.3 DEPLOY KUBERNETES (USING KUBELO)

To prepare ansible inventory run:
```bash
$ cat >kubelo/kubelo.ini <<EOF
[all:vars]
cluster_name=k1
ansible_user=ubuntu
cloud_provider=

[bastion]
vpc1u ansible_host=<IP_ADDRESS>

[etcd]
k1m1
k1m2
k1m3

[master]
k1m1
k1m2
k1m3

[compute]
k1c1
EOF
```

To deploy kubernetes:
```bash
$ (cd kubelo/ && ansible-playbook kubelo.yml)
```
[>>> CONSOLE OUTPUT <<<](docs/kubelo-output.md)

To list nodes and pods:
```bash
$ make ssh-utl
```
```
Warning: Permanently added '<IP_ADDRESS>' (ECDSA) to the list of known hosts.
Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-74-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Sun Feb 16 19:15:00 UTC 2020

  System load:  0.0               Users logged in:     0
  Usage of /:   14.8% of 9.52GB   IP address for ens3: <IP_ADDRESS>
  Memory usage: 23%               IP address for ens4: <IP_ADDRESS>
  Swap usage:   0%                IP address for ens5: <IP_ADDRESS>
  Processes:    86                IP address for ens6: <IP_ADDRESS>

8 packages can be updated.
8 updates are security updates.

Last login: Sun Feb 16 18:39:00 2020 from <IP_ADDRESS>
```
```bash
ubuntu@vpc1u:~$ ssh k1m1 -t sudo -i kubectl get nodes
```
```
Warning: Permanently added 'k1m1,<IP_ADDRESS>' (ECDSA) to the list of known hosts.
NAME              STATUS   ROLES    AGE     VERSION
k1c1.vpc1.local   Ready    <none>   4m27s   v1.14.6
k1m1.vpc1.local   Ready    master   8m35s   v1.14.6
k1m2.vpc1.local   Ready    master   5m48s   v1.14.6
k1m3.vpc1.local   Ready    master   6m2s    v1.14.6
Connection to k1m1 closed.
```
```bash
ubuntu@vpc1u:~$ ssh k1m1 -t sudo -i kubectl get pods --all-namespaces
```
```
Warning: Permanently added 'k1m1,<IP_ADDRESS>' (ECDSA) to the list of known hosts.
NAMESPACE     NAME                                      READY   STATUS    RESTARTS   AGE
kube-system   coredns-584795fc57-27x9j                  1/1     Running   0          8m10s
kube-system   coredns-584795fc57-q5bfv                  1/1     Running   0          8m11s
kube-system   kube-apiserver-k1m1.vpc1.local            1/1     Running   0          7m33s
kube-system   kube-apiserver-k1m2.vpc1.local            1/1     Running   0          5m58s
kube-system   kube-apiserver-k1m3.vpc1.local            1/1     Running   0          6m11s
kube-system   kube-controller-manager-k1m1.vpc1.local   1/1     Running   0          7m36s
kube-system   kube-controller-manager-k1m2.vpc1.local   1/1     Running   0          5m57s
kube-system   kube-controller-manager-k1m3.vpc1.local   1/1     Running   0          6m11s
kube-system   kube-flannel-ds-amd64-4xf2z               1/1     Running   0          5m59s
kube-system   kube-flannel-ds-amd64-jwpfs               1/1     Running   0          8m11s
kube-system   kube-flannel-ds-amd64-npcg4               1/1     Running   0          4m37s
kube-system   kube-flannel-ds-amd64-xlz5x               1/1     Running   0          6m11s
kube-system   kube-proxy-7pr5d                          1/1     Running   0          8m11s
kube-system   kube-proxy-gwfss                          1/1     Running   0          4m37s
kube-system   kube-proxy-hwtjz                          1/1     Running   0          5m59s
kube-system   kube-proxy-w5j59                          1/1     Running   0          6m11s
kube-system   kube-scheduler-k1m1.vpc1.local            1/1     Running   1          7m45s
kube-system   kube-scheduler-k1m2.vpc1.local            1/1     Running   0          5m57s
kube-system   kube-scheduler-k1m3.vpc1.local            1/1     Running   0          6m11s
kube-system   tiller-deploy-7b98f7c844-768jz            1/1     Running   0          3m11s
Connection to k1m1 closed.
```

### 4.4 DESTROY K8S ENVIRONMENT

To destroy "k8s1" environment (along with kubernetes):
```bash
$ make k8s-destroy
```
[>>> CONSOLE OUTPUT <<<](docs/k8s-destroy-output.md)

### 4.5 DESTROY VPC ENVIRONMENT

To destroy "vpc1" environment:
```bash
$ make vpc-destroy
```
[>>> CONSOLE OUTPUT <<<](docs/vpc-destroy-output.md)

![:thinking-face:](https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/160/twitter/233/thinking-face_1f914.png)

[//]: # ( vim:set ts=2 sw=2 et syn=markdown: )

branch_name: refs/heads/master

extension: md

gha_language: HCL

license_type: permissive


text:
# vat-api

vat-api has five endpoints:
  - GET obligations
  - POST returns
  - GET returns
  - GET payments
  - GET liabilities

### Prerequisites
- Scala 2.12.x
- Java 8
- sbt > 1.3.7
- [Service Manager](https://github.com/hmrc/service-manager)

### Development Setup

Run from the console using: `sbt "~run 9675"`

## Highlighted SBT Tasks
Task | Description | Command
:-------|:------------|:-----
test | Runs the standard unit tests | ```$ sbt test```
func:test  | Runs the functional tests | ```$ sbt func:test ```
dependencyCheck | Runs dependency-check against the current project. It aggregates dependencies and generates a report | ```$ sbt dependencyCheck```
dependencyUpdates |  Shows a list of project dependencies that can be updated | ```$ sbt dependencyUpdates```
dependencyUpdatesReport | Writes a list of project dependencies to a file | ```$ sbt dependencyUpdatesReport```

### Reporting Issues

You can create a GitHub issue [here](https://github.com/hmrc/vat-api/issues).

### License

This code is open source software licensed under the [Apache 2.0 License]("http://www.apache.org/licenses/LICENSE-2.0.html")

repository: hmrc/vat-api

branch_name: refs/heads/main

gha_language: Scala

repo_name: hmrc/vat-api


text:
# Target Specification and Hardware Registers with UTRA

Xous isolates target-specific code, such as the location and fields of hardware registers, inside the Unambiguous Thin Register Astraction (UTRA).

The UTRA is contained in the `utralib` crate, and its contents are generated from [SVD files](https://www.keil.com/pack/doc/CMSIS/SVD/html/svd_Format_pg.html) using [`svd2utra`](https://crates.io/crates/svd2utra). SVD itself is an XML format commonly used by hardware vendors for the interchange of SoC registers, and is a native output format of SoC building tools such as LiteX. SVD files are also readily available for many commercial MCUs.

## Specifying Targets

Services that talk to hardware will typically have one or more `implementation` modules that encapsulate the target-specific back ends. These are gated with `#[cfg(feature="X")]` directives, where "X" is the specific build target.

This means that a specific build target is selected by passing a `--feature` flag during compilation, e.g. `--feature precursor`, `--feature hosted`, or `--feature renode`.

## About the UTRA

UTRA is a register abstraction for accessing hardware resources. It tries to be:

* Unambiguous -- the access rules should be concise and unambiguous to a systems programmer with a C background
* Thin -- it should hide constants, but not bury them so they become difficult to verify

Here is an example of an ambiguous style of register access, from a
PAC generated using [svd2rust](https://crates.io/crates/svd2rust):

```rust,noplayground,ignore
    // this seems clear -- as long as all the bit fields are specified
    // (they actually aren't, so some non-obvious things are happening)
    p.POWER.power.write(|w|
       w.discharge().bit(true)
        .soc_on().bit(false)
        .kbddrive().bit(true)
        .kbdscan().bits(3)
      );

    // what should this do?
    // 1. just set the discharge bit to true and everything else to zero?
    // 2. read the register first, change only the discharge bit to true, leaving the rest unchanged?
    p.POWER.power.write(|w|
       w.discharge().bit(true)
      );

    // answer: it does (1). You need to use the `modify()` function to have (2) happen.

```

While the closure-chaining is clever syntax, it's also ambiguous.
First, does the chaining imply an order of writes happening in
sequence, or do they all happen at once? The answer depends on Rust's
optimizer, which is very good and one can expect the behavior to be
the latter, but it is still write-ordering behavior that depends upon
the outcome of an optimizer and not a linguistic guarantee. Second,
the term `write` itself is ambiguous when it comes to bitfields: do we
write just the bitfield, or do we write the entire register, assuming
the rest of the contents are zero? These types of ambiguity make it
hard to audit code, especially for experts in systems programming
who are not also experts in Rust.

The primary trade-off for achieving unambiguity and thinness is less
type checking and type hardening, because we are not fully taking
advantage of the advanced syntax features of Rust.

That being said, a certain degree of deliberate malleability in the
register abstraction is desired to assist with security-oriented
audits: for a security audit, it is often just as important to ask
what the undefined bits do, as it is to check the settings of the
defined bits. Malleabilty allows an auditor to quickly create targeted
tests that exercise undefined bits. Existing Rust-based access crates
create strict types that eliminate the class of errors where constants
defined for one register are used in an incorrect type of register,
but they also make it very hard to modify in an ad-hoc manner.

## UTRA API Details

This crate is designed to serve as an alternative to `svd2rust`. It generates
a crate which consists of:

1. A library which is used to perform register accesses
2. A "header file" (library) that is auto-generated from a given `soc.svd` file

The library provides the a function template for `CSR` that provides the following
methods:

* `.r(reg: Register) -> T` - Read. Reads the entire contents of a CSR
* `.rf(field: Field) -> T` - Read Field. Read a CSR and return only the masked and shifted value of a sub-field
* `.wo(reg: Register, value:T)` - Write only. Write `value` into a register, replacing its entire contents
* `.wfo(field: Field, value:T)` - Write field only. Write `value` into a field of a register, zeroizing all the other fields and replacing its entire contents
* `.rmwf(field: Field, value:T)` - Read-modify-write a register. Replace just the contents of `field` while leaving the other fields intact. The current implementation makes no guarantees about atomicity.

`Register` and `Field` are generated by the library; `Field` refers to
the `Register` to which it belongs, and thus it is not necessary to
specify it explicitly. Furthermore, the base address of the `CSR` is
bound when the object is created, which allows the crate to work both
with physical and virtual addresses by replacing the base address with
the desired value depending upon the active addressing mode.

In addition to the `CSR` function template, convenience constants for
the CSR base, as well as any memory bases and interrupts, are also
generated by this crate.

This set of API calls supports the most common set of use cases, which
is reading, writing, and updating single fields of a register, or
entire registers all at once.

The API does not natively support setting two fields
simultaneously. This is because there can be nuances to this that
depend upon the hardware implementation, such as bit fields that are
self-resetting, registers that self-clear on read, or registers that
have other automatic and implicit side effects.

Users that require multiple bit fields to be set simultaneously must
explicitly read the CSR value, bind it to a temporary variable, mask
out the fields they want to replace, and combine in the values before
writing it back to the CSR.

To aid with this, the following helper functions are also available:

* `zf(field:Field, value:T) -> T` - Zeroize field. Take bits corresponding to `field` and set it to zero in `value`, leaving other bits unchanged
* `ms(field:Field, value:T) -> T` - Mask and shift. Take value, mask it to the field width, and then shift to its final position.

The idea here is that the `.r(register)` method is used to read the
entire register; then successive `.zf(field, value)` calls are made to
clear the fields prior to setting. Field values are OR'd with the
result of `.ms(field, value)` to create the final composite register
value.  Finally, `.wo(value)` is used to overwrite the entire
register with the final composite register value.

The `.ms(field,value)` can also be used to synthesize initial register
values that need to be committed all at once to a hardware register,
before a `.wo(value)` call.

## Example Usage

Let's assume you've used svd2utra.py to create a `utra` crate in the
same directory as svd2utra.py, and you've added this to your `Cargo.toml` file.
Now, inside your `lib.rs` file, you might have something like this:

```rust,noplayground,ignore
use utra

fn test_fn() {
        // Audio tests

        // The audio block is a pointer to *mut 32.
        let mut audio = CSR::new(HW_AUDIO_BASE as *mut u32);

        // Read the entire contents of the RX_CTL register
        audio.r(utra::audio::RX_CTL);

        // Or read just one field
        audio.rf(utra::audio::RX_CTL_ENABLE);

        // Do a read-modify-write of the specified field
        audio.rmwf(utra::audio::RX_CTL_RESET, 1);

	// Do a multi-field operation where all fields are updated in a single write.
	// First read the field into a temp variable.
        let mut stat = audio.r(utra::audio::RX_STAT);
	// in read replica, zero EMPTY and RDCOUNT
	stat = audio.zf(utra::audio::RX_STAT_EMPTY, stat);
	stat = audio.zf(utra::audio::RX_STAT_RDCOUNT, stat);
	// in read replica, now set RDCOUNT to 0x123
	stat |= audio.ms(utra::audio::RX_STAT_RDCOUNT, 0x123);
	// commit read replica to register, updating both EMPTY and RDCOUNT in a single write
	audio.wo(utra::audio::RX_STAT, stat);

        // UART tests

        // Create the UART register as a pointer to *mut u8
        let mut uart = CSR::new(HW_UART_BASE as *mut u8);

        // Write the RXTX field of the RXTX register
        uart.wfo(utra::uart::RXTX_RXTX, b'a');

        // Or you can write the whole UART register
        uart.wo(utra::uart::RXTX, b'a');
        assert_ne!(uart.rf(pac::uart::TXFULL_TXFULL), 1);

        // Anomalies

        // This compiles but requires a cast since `audio` is a pointer to
        // u32, whereas `uart` is a pointer to u8.
        audio.wfo(utra::uart::RXTX_RXTX, b'a' as _);

        // This also compiles, despite the fact that the register offset is
        // mismatched and nonsensical
        audio.wfo(utra::uart::TXFULL_TXFULL, 1);
}

```

repository: betrusted-io/xous-book

gha_language: Rust

repo_name: betrusted-io/xous-book


text:
# LuaLines
>*Small line parser written in pure Lua*

##Overview
I needed fast small parser for my school project (parsing .gpx file with thousands lines). I needed to parse whole <tag> block with patterns between them, which I was looking for. For example:

```
<wpt lat="47.9576349" lon="16.787799">
  <name>Jois</name>
  <extensions>
    <ogr:osm_id>538174</ogr:osm_id>
    <ogr:other_tags>"traffic_sign"=>"city_limit"</ogr:other_tags>
  </extensions>
</wpt>
<wpt lat="48.1896356" lon="17.2557963">
    <ogr:osm_id>702570</ogr:osm_id>
    ....
</wpt>
<rte lat=...
...
</rte>
```
And from this file I needed all with *wpt* tags and contains *traffic_sign*. Sure you can do it with some regex, but to me, this is more handy and easier to work with.
I added some easy parsing with single or more patterns and going to add more functionality to LuaLines. Just scroll down and check for its options.

##Usage
```
Usage: [-hsvn] [-m num] [-f file] <input file>

	-h 	    	help
	-s	    	parse lines based on single pattern match
	-m [num]	parse lines based on more patterns match
	-v	    	don't print parsed output
	-n	    	parse lines based on more patterns insi
```
* -s  - used to find lines which contains our typed pattern
* -m [num]  - used to find lines which contains our typed patterns (num could be 1, so will be same as *-s*)
* -n  - follow instructions, first type starting and ending pattern, then which patterns find between them. If you want to parse whole paragraph, then type
How many patterns to find: 0

##Installation
Make:
```
git clone https://github.com/robooo/LuaLines.git
cd LuaLines/
make
```
Or with luarocks:
```
TO DO
```

##Examples
###single parse
 * lualines -s -f /path/to/save /file/path/to/parse

###multi parse
 * lualines -m 3 -f /path/to/save /file/path/to/parse

###inner parse
Let's work this file, its path is */file/path/to/parse.txt*:
```
<tag1>This is what I want</tag1>
<tag1>This is not what I want</tag1>
<tag2>Bad too<tag2>
<bad_tag>This is what I want2</tag1>
```
and we want get 1. and 4. line

> lualines -n -f /path/to/save.txt /file/path/to/parse.txt
> First tag: <tag1>
> Last tag: </tag1>
> How many patterns to find: 1
> 1.pattern: is what
> OUTPUT:
> <tag1>This is what I want</tag1>
> 1 lines parsed, save to file? y/n
> y
> Continue? y/n
> y
> First tag: <bad_tag>
> Last tag: </tag1>
> How many patterns to find: 1
> 1.pattern: is what
> OUTPUT:
> <bad_tag>This is what I want2</h1>
> 1 lines parsed, save to file? y/n
> y
> Continue? y/n
> n

Now when we open *save.txt* file, we will see our parsed lines.

license: MIT

repository: katka-juhasova/BP-data

repo_name: katka-juhasova/BP-data


text:
  Animal Shelter API

  Last Updated: January 22th, 2021

# ℹ Description

This is the code to run an Animal Shelter API that can give, change, delete, etc. all data of the animal shelter!

# 🧑💻 Contributers

| Name | GitHub Profile |
|------|----------------|
|[Ben McFarland](https://www.linkedin.com/in/benjamin-mcf/)|[Harzulu](https://github.com/harzulu)|

# 📞 API Endpoints and Examples

  Click to view

## 🐕 Dogs:

**GET http://localhost:5001/api/dogs**

Output:
```
[
    {
        "dogId": 1,
        "name": "Uma",
        "breed": "Pit Bull"
    },
    {
        "dogId": 2,
        "name": "Abner",
        "breed": "Australian Cattledog"
    },
    {
        "dogId": 3,
        "name": "Jackson",
        "breed": "Lab Mix"
    }
]
```

**GET http://localhost:5001/api/dogs/2**

Output:
```
[
    {
        "dogId": 2,
        "name": "Abner",
        "breed": "Australian Cattledog"
    }
]
```

**POST http://localhost:5001/api/dogs**

Body:
```
{
  "dogId": 11,
  "name": "Teddy",
  "breed": "Greyhound"
}
```

**PUT http://localhost:5001/api/dogs/2**

Body:
```
{
  "dogId": 2,
  "name": "Roger",
  "breed": "Bulldog"
}
```

**DELETE http://localhost:5001/api/dogs/2**

Output:
```

```

## 🐈 Cats:

**GET http://localhost:5001/api/cats**

Output:
```
[
  {
        "catId": 1,
        "name": "Baby Girl",
        "breed": "Short Hair"
    },
    {
        "catId": 2,
        "name": "Inky",
        "breed": "Short Hair"
    },
    {
        "catId": 3,
        "name": "Marley",
        "breed": "Siamese"
    }
]
```

**GET http://localhost:5001/api/cats/3**

```
[
  {
    "catId": 3,
    "name": "Marley",
    "breed": "Siamese"
  }
]
```

**POST http://localhost:5001/api/cats**

```
{
  "catId": 7,
  "name": "Lilly"
  "breed": "Long Hair"
}
```

**PUT http://localhost:5001/api/cats/3**

```
{
  "catId": 3,
  "name": "Gus"
  "breed": "Persian"
}
```

**DELETE http://localhost:5001/api/cats/3**

Output:
```

```

# ⚙ Technologies Used

  Expand Tech/tools

* Microsoft Visual Studio Code
* Git/GitHub
* C#
* .NET Core
* REPL
* ASP.NET MVC
* CSS
* Bootstrap
* EF Core
* MySQL/My SQL Workbench
* Postman
* Swagger/Swagbuckle

# 💾 Installation Requirements

## For Both  Mac & Windows systems

* Once you have Git installed on your computer, go to this GitHub repository, click the "Fork" button in the upper right hand corner of the page, and clone this application with the following command:

 `git clone https://github.com/harzulu/AnimalShelter.Solution`.

## 📁 Installing C#, .NET, dotnet script, & MySQL

### **This program requires C# and the .NET Framework to be installed on your machine:**

## For Mac 
 * Download this .NET Core SDK (Software Development Kit). Clicking this link will prompt a .pkg file download from Microsoft.
* Open the .pkg file. This will launch an installer which will walk you through installation steps. Use the default settings the installer suggests.
* Confirm the installation is successful by opening your terminal and running the command `$ dotnet --version`, which should return something like: `2.2.105`.

## For Windows (10+)

* Download this 64-bit .NET Core SDK (Software Development Kit). Clicking these links will prompt a .exe file download from Microsoft.
* Open the file and follow the steps provided by the installer for your OS.
* Confirm the installation is successful by opening a new Windows PowerShell window and running the command `dotnet --version`. You should see something a response like this: `2.2.105`.

## For Mac & Windows Operating Systems

* Install dotnet script with the following terminal command:

 `dotnet tool install -g dotnet-script`.

# 🖥 Opening the Project on your Local System

* Once the project has been cloned to your computer and you have all the necessary items on your local computer, open the project in the application of your choice (Visual Code Studio was used and is recommended by the application builder)

### AppSettings.json File

You will need to create an `appsettings.json` file in the `AnimalShelter` folder.

Once you have the file made, put in this code:

```
{
    "Logging": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
      "DefaultConnection": "Server=localhost;Port=3306;database=[DATABASE_NAME];uid=root;pwd=[PASSWORD];"
    }
}
```
**Make sure to have a MySQL server up and running on your machine on port 3306**

**Replace `PASSWORD` with the password to your server created for this project**
**Replace `DATABASE_NAME` with the name of your database**

### MySQL Database Setup

* First, using your terminal or command line, navgate to the AnimalShelter folder in AnimalShelter.Solution: `/AnimalShelter.Solution/AnimalShelter`.
* Next, run the command: `dotnet ef database update`.
* You should have your database created for this project.

### Calling the API
* Finally, run the command `dotnet build` to get bin/ and obj/ folders downloaded, then `dotnet run` to run the application. The program should be connected to a localhost port, most likely 5000. Your terminal or command line should specify which port it is on.
* Once you have your project running, this is the base API path: `http://localhost:[PORT_NUMBER]/api/[ANIMAL]`.
* View [here](#📞-api-endpoints-and-examples) to see what end points you can call.

# 😎 Using Swagger UI

### The Swagger UI is already incorporated. To view the UI:

* Run the command `dotnet run` to make your application live.
* Find the port number your console gives you that the site is live on. This will usually be port 5000 or 5001.
* In your web browser, go to this URL: `http://localhost:[PORT_NUMBER]/index.html`.

# ☎ Support / Contact Details

* Ben McFarland<EMAIL_ADDRESS>
# 🪲 Bugs / Issues

No known bugs or issues

# © License & Copyright

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

Copyright (c) 2021 *_Ben McFarland_*


text:
# Registrator

Service registry bridge for Docker for ARM.

Full documentation available at http://gliderlabs.com/registrator

## Getting Registrator

Get the latest release, master, or any version of Registrator via [Docker Hub](https://registry.hub.docker.com/r/chmod750/registrator):

	$ docker pull chmod750/registrator:latest

Latest tag always points to the latest release. There is also a `:master` tag
and version tags to pin to specific releases.

## Using Registrator

The quickest way to see Registrator in action is our
[Quickstart](https://gliderlabs.com/registrator/latest/user/quickstart)
tutorial. Otherwise, jump to the [Run
Reference](https://gliderlabs.com/registrator/latest/user/run) in the User
Guide. Typically, running Registrator looks like this:

    $ docker run -d \
        --name=registrator \
        --net=host \
        --volume=/var/run/docker.sock:/tmp/docker.sock \
        chmod750/registrator:latest \
          consul://localhost:8500

## CLI Options
```
Usage of /bin/registrator:
  /bin/registrator [options] <registry URI>

  -cleanup=false: Remove dangling services
  -deregister="always": Deregister exited services "always" or "on-success"
  -internal=false: Use internal ports instead of published ones
  -ip="": IP for ports mapped to the host
  -resync=0: Frequency with which services are resynchronized
  -retry-attempts=0: Max retry attempts to establish a connection with the backend. Use -1 for infinite retries
  -retry-interval=2000: Interval (in millisecond) between retry-attempts.
  -tags="": Append tags for all registered services
  -ttl=0: TTL for services (default is no expiry)
  -ttl-refresh=0: Frequency with which service TTLs are refreshed
```

## Contributing

Pull requests are welcome! We recommend getting feedback before starting by
opening a [GitHub issue](https://github.com/chmod750/registrator/issues).

## License

MIT

<img src="https://ga-beacon.appspot.com/UA-58928488-2/registrator/readme?pixel" />


text:
# Yatat
Yet another (public domain) Twitter archive tool!

A (Linux/MacOS) commandline application to help you bulk delete some tweets from your Twitter archive.

### Offline browsing steps:

#### 1. Download your [twitter-archive.zip](https://help.twitter.com/managing-your-account/how-to-download-your-twitter-archive) from Twitter:
    https://help.twitter.com/managing-your-account/how-to-download-your-twitter-archive

#### 2. Create your local working directory
````bash
$ mkdir /path/to/workdir/
````

#### 3. Unpack your twitter-archive.zip, copy data file "tweet.js" to a working directory:
```bash
$ unzip twitter.zip
$ cp twitter/data/tweet.js /path/to/workdir
```

#### 4. Open the "tweet.js" copy in a text-editor
and remove ```window.YTD.tweet.part0 = ``` from the first line of your tweet.js working copy! Otherwise it can't be read by the app.

#### 5. Run Yatat in offline browsing mode:
```bash
$ python3 yatat.py /path/to/workdir
```

* You will be asked to enter your Twitter username for internal textual representation only. No login, credentials needed at this point!

Now browse your archive, make decisions... should be self-explaining...

Get your [Twitter API credentials](https://developer.twitter.com) ready.
 You'll need
         'YOUR-CONSUMER-KEY', 'YOUR-CONSUMER-SECRET',
        'YOUR-ACCESS-KEY', 'YOUR-ACCESS-SECRET'

 and run Yatat in online mode:

```bash
$ python3 yatat.py /path/to/workdir /path/to/auth.yaml
```

The path to file auth.yaml must be writable and the file is created on-the-fly during first run. You will be asked for your Twitter credentials!

When successfully logged in, you can choose to destroy selected tweets from the menu.

---

##### Files

Browsing and decision progress is stored in files in the working directory:

+ *yatat.keep* - stores tweets you keep
+ *yatat.destroy* - stores tweets you want to delete
+ *yatat.destroyed* - stores tweet ids of already destroyed tweets

---

This software is distributed as source from GIT only.
Find the source at [github.com/schlind/Yatat](https://github.com/schlind/Yatat) - Cheers!

license: Unlicense

repository: schlind/Yatat

repo_name: schlind/Yatat


text:
# in-toto governance
This document covers the project's governance and committer process.  The
project consists of the in-toto
[specification](https://github.com/in-toto/docs) and
[reference implementation](https://github.com/in-toto/in-toto).

## Maintainership and Consensus Builder
The project is maintained by the people indicated in
[MAINTAINERS.txt](MAINTAINERS.txt).  A maintainer is expected to (1) submit and
review GitHub pull requests and (2) open issues or [submit vulnerability
reports](https://github.com/in-toto/in-toto#security-issues-and-bugs).
A maintainer has the authority to approve or reject pull requests submitted by
contributors.  The project's Consensus Builder (CB) is
Justin Cappos<EMAIL_ADDRESS>@JustinCappos>.

## Contributions
A contributor can [submit GitHub pull
requests](https://github.com/in-toto/in-toto#instructions-for-contributors)
to the project's repositories.  They must follow the project's [code of
conduct](CODE-OF-CONDUCT.md), the [code style
guidelines](https://github.com/secure-systems-lab/code-style-guidelines), and
must unit test any new software feature or change.  Submitted pull requests
undergo review and automated testing, including, but not limited to:

* Unit and build testing via [Travis CI](https://travis-ci.org/) and
[Tox](https://tox.readthedocs.io/en/latest/)
* Static code analysis via [Pylint](https://www.pylint.org/) and
[Bandit](https://wiki.openstack.org/wiki/Security/Projects/Bandit)
* Review by one or more maintainers

## Changes in maintainership

A contributor to the project must express interest in becoming a maintainer.
The CB has the authority to add or remove maintainers.

## Changes in governance
The CB supervises changes in governance.

repository: DataDog/in-toto

branch_name: refs/heads/develop

gha_license_id: MIT

repo_name: DataDog/in-toto


text:
# [Benchmarks for Deep Off-Policy Evaluation](https://openreview.net/forum?id=kWSeGEeHvF8)
### Contact<EMAIL_ADDRESS>
In
[D4RL](https://sites.google.com/view/d4rl/home) and [RL Unplugged: Benchmarks for Offline Reinforcement Learning](https://arxiv.org/abs/2006.13888),
we released a suite of benchmarks for offline reinforcement learning. They are designed to facilitate ease of use, so we provided the datasets
with a unified API which makes it easy for the practitioner to work with all
data in the suite once a general pipeline has been established.

Here, we release policies which can be used in conjunction with the RL Unplugged
and D4RL datasets to facilitate off-policy evaluation and offline model selection
benchmarking.

In this release, we provide:

-   Policies for the tasks in the D4RL, DeepMind Locomotion and Control Suite datasets
    (described below).

-   Policies trained with the following algorithms (D4PG, ABM, CRR, SAC, DAPG and BC) and snapshots along the training trajectory. This faciliates benchmarking offline model selection.

The policies are available under
[gs://gresearch/deep-ope](https://console.cloud.google.com/storage/browser/gresearch/deep-ope), with the RL Unplugged policies in the subdirectory [gs://gresearch/deep-ope/rlunplugged](https://console.cloud.google.com/storage/browser/gresearch/deep-ope/rlunplugged) and the D4RL policies in the subdirectory [gs://gresearch/deep-ope/d4rl](https://console.cloud.google.com/storage/browser/gresearch/deep-ope/d4rl).

## Task Descriptions

### DeepMind Locomotion Dataset

These tasks are made up of the corridor locomotion tasks involving the CMU
Humanoid, for which prior efforts have either used motion capture data
([Merel et al., 2019a], [Merel et al., 2019b]) or training from scratch
([Song et al., 2020]). In addition, the DM Locomotion repository contains a set of
tasks adapted to be suited to a virtual rodent ([Merel et al., 2020]). We
emphasize that the DM Locomotion tasks feature the combination of challenging
high-DoF continuous control along with perception from rich egocentric
observations. For details on how the dataset was generated, please refer to
[RL Unplugged: Benchmarks for Offline Reinforcement Learning](https://arxiv.org/abs/2006.13888).

### DeepMind Control Suite Dataset

DeepMind Control Suite ([Tassa et al., 2018]) is a set of control tasks
implemented in MuJoCo ([Todorov et al., 2012]). We consider a subset of the tasks
provided in the suite that cover a wide range of difficulties.

Most of the datasets in this domain are generated using D4PG. For the
environments Manipulator insert ball and Manipulator insert peg we use V-MPO
([Song et al., 2020]) to generate the data as D4PG is unable to solve these tasks.
We release datasets for 9 control suite tasks. For details on how the dataset
was generated, please refer to
[RL Unplugged: Benchmarks for Offline Reinforcement Learning](https://arxiv.org/abs/2006.13888).

### D4RL Dataset

A subset of the tasks within the D4RL ([Fu et. al. 2020]) for offline reinforcement
learning is included. These tasks include maze navigation with different robot
morphologies, hand manipulation tasks ([Rajeswaran et. al. 2017]), and tasks from
the OpenAI Gym bechmark ([Brockman et. al. 2016]).

Each task includes a variety of datasets in order to study the interaction between
dataset distributions and policies. For further information on what datasets
are available, please refer to [D4RL: Datasets for Deep Data-Driven Reinforcement Learning](https://arxiv.org/abs/2004.07219).

## Using the policies

The `rlunplugged_policies.json` file provides metadata about the policies in this dataset.
It is structured as a list of dictionaries, one for each policy, where the keys
contain metadata including:

-   policy_path: The path to the policy on Google Cloud Storage.

-   task.task_name: The task that the policy is trained for.

-   agent_name: The training algorithm used to learn the policy.

-   snapshot_name: Contains the learning step for this policy snapshot.

-   return_mean: The mean return estimated with Monte Carlo rollouts.

-   return_std: The standard error of the mean estimate.

The 'd4rl_policies.json' file contains metadata in a similar format:

-   policy_path: The path to the policy on Google Cloud Storage.

-   task.task_names: A list of tasks that the policy is trained for. (Each task represets a different dataset)

-   agent_name: The training algorithm used to learn the policy.

-   return_mean: The mean return estimated with Monte Carlo rollouts.

-   return_std: The standard error of the mean estimate.

Requirements:

*   Install dependencies: `pip install -r requirements.txt`
*   (Optional) Setup MuJoCo license key for DM Control and D4RL environments
    ([instructions](https://github.com/deepmind/dm_control#requirements-and-installation)).

### Policy loading example

RLUnplugged policies are stored as
[TensorFlow SavedModels](https://www.tensorflow.org/guide/saved_model). Calling
the policy on an observation returns an action sample. See `load_rlunplugged_policy_example.py` for an example of loading a policy.

D4RL policies are stored as pickle files containing weights.
See `load_d4rl_policy_example.py` for an example of loading a policy.
### Compute evaluation metrics

```
TODO Fill in example computing groundtruth and evaluation metrics.
```

## Dataset Metadata

The following table is necessary for this dataset to be indexed by search
engines such as Google Dataset Search.

    property
    value

    name
    Benchmarks for Deep Off-Policy Evaluation

    url
    https://github.com/google-research/deep_ope

    sameAs
    https://github.com/google-research/deep_ope

    description

      Data accompanying
[Benchmarks for Deep Off-Policy Evaluation]().

    provider

            property
            value

            name
            Google

            sameAs
            https://en.wikipedia.org/wiki/Google

[Agarwal et al., 2020]: https://arxiv.org/abs/1907.04543
[Brockman et. al. 2016]: https://arxiv.org/abs/1606.01540
[Fu et. al. 2020]: https://arxiv.org/abs/2004.07219
[Machado et al., 2018]: https://arxiv.org/abs/1709.06009
[Merel et al., 2019a]: https://arxiv.org/abs/1811.09656
[Merel et al., 2019b]: https://arxiv.org/abs/1811.11711
[Merel et al., 2020]: https://arxiv.org/abs/1911.09451
[Rajeswaran et. al. 2017]: https://arxiv.org/abs/1709.10087
[Song et al., 2020]: https://arxiv.org/abs/1909.12238
[Tassa et al., 2018]: https://arxiv.org/abs/1801.00690
[Todorov et al., 2012]: https://homes.cs.washington.edu/~todorov/papers/TodorovIROS12.pdf


text:
# BayesRate
BayesRate is a program to estimate speciation and extinction rates from dated phylogenies in a Bayesian framework.

The methods are described in:

Silvestro, D., Schnitzler, J. and Zizka, G. (2011) A Bayesian framework to estimate diversification rates and their variation through time and space. BMC Evolutionary Biology, 11, 311

Silvestro D., Zizka G. & Schulte K. (2014) Disentangling the effects of key innovations on the diversification of Bromelioideae (Bromeliaceae). Evolution, 68, 163-175.

BayesRate currently runs under Mac OS X and Windows. Please note that under Windows some functions have restricted options, but this does not affect the overall capabilities of the program. BayesRate was successfully tested using R versions 2.13 - 3.3, and Python versions 2.6.4 and 2.7 (but currently does not support Python 3).

Python libraries required:
dendropy: https://github.com/jeetsukumaran/DendroPy
numpy: http://www.numpy.org
scipy: http://scipy.org/scipylib/

repository: schnitzler-j/BayesRate

repo_name: schnitzler-j/BayesRate


text:
# <img src="https://github.com/pip-services/pip-services/raw/master/design/Logo.png" alt="Pip.Services Logo" style="max-width:30%">
# IoC container for Dart

This framework is a part of the [Pip.Services](https://github.com/pip-services/pip-services) project.
It provides an inversion-of-control component container to facilitate the development of composable services and applications.

As all Pip.Services projects this framework is implemented in a variety of different languages: Java, .NET, Python, Node.js, Golang and Dart.

The framework provides a light-weight container that can be embedded inside a service or application, or can be run by itself,
as a system process, for example. Container configuration serves as a recipe for instantiating and configuring components inside the container.
The default container factory provides generic functionality on-demand, such as logging and performance monitoring.

- **Core** - Component container and container as a system process
- **Build** - Container default factory
- **Config** - Container configuration
- **Refer** - Container references

Quick Links:

* [Downloads](https://github.com/pip-services3-node/pip-services3-container-node/blob/master/doc/Downloads.md)
* [API Reference](https://pub.dev/documentation/pip_services3_components/latest/pip_services3_components/pip_services3_components-library.html)
* [Building and Testing](https://github.com/pip-services3-node/pip-services3-container-node/blob/master/doc/Development.md)
* [Contributing](https://github.com/pip-services3-node/pip-services3-container-node/blob/master/doc/Development.md#contrib)

## Acknowledgements

The Dart version of Pip.Services is created and maintained by:
- **Sergey Seroukhov**
- **Levichev Dmitry**

The documentation is written by:
- **Mark Makarychev**
- **Levichev Dmitry**


text:
<!-- markdownlint-disable MD026 MD041 -->

.center[

# Making of [urlhandlers://](#start)

## Press space to proceed

## Or go directly to the [Project Repo](https://github.com/ouspg/urlhandlers)

]

---

name: start

## Autumn 2015 - Inspiration

* You might have noticed, @turmio [hacks terminals :)](http://www.crashterminal.org)
  * Learns to launch them automagically from the web
  * [x-man-page:///security](x-man-page:///security)
  * [x-man-page:///security;type=a](x-man-page:///security;type=a)
  * Asks aloud 'Is it safe?'

.right[![Man security](img/manpages.png)]

---

## Spoils of the man pages

* We wrote [a DTrace script for `execve` on OSX](https://github.com/ouspg/urlhandlers/blob/master/osx/execve.d)

<!-- markdownlint-disable MD013 -->

```console
'login' '-pfq' 'nkapu' '/usr/bin/man' '-P' 'cat' '-k' 'security'
sh[33926] -> /usr/bin/apropos '/usr/bin/apropos' 'security'
sh[33927] -> /usr/bin/basename 'basename' '/usr/bin/apropos'
sh[33929] -> /usr/bin/man 'man' '--path'
sh[33930] -> /usr/bin/tr 'tr' ':' '\040'
sh[33933] -> /usr/bin/grep 'grep' '-i' 'security' '/usr/share/man/whatis'
sh[33934] -> /bin/cat 'cat'
sh[33935] -> /usr/bin/grep 'grep' '-i' 'security' '/usr/local/share/man/whatis'
```

<!-- markdownlint-enable MD013 -->

* We wrote [a vulnerability assessment](https://github.com/ouspg/urlhandlers/blob/master/cases/x-man-page.md)

* To us it appears to be .red[**safe by accident**]
  from shell meta-character injection ... for now ... with our skills!

---

## Winter 2015-2016 - Happy hobby hacking

* Temptation and occasional random hacking
* A bit of workshopping with [Kapsi Ry](https://www.kapsi.fi) activists
* A private Wiki for the collaboration
* We realized that there were
  * Plenty of URL handlers that launch **out of the browser behavior**
  * Even more handler specific query parameters
  * A bunch browsers (browsers, electron apps, chat clients, ...)
  * Many injection vectors (web, email, document, direct, **redirect**, ...)
  * -> Too many combinations to cover and behaviors to analyze

.right[![Handlers to Devices](img/devices.png)]

---

## Logic of the denial

Some browsers whitelist autolaunch, blacklist deny, sometimes prompt
and sometimes don't when you try to active URL handlers. Safari used
to launch them all.

### Thumbs up for the paranoid browser

1. Browser -> Server: q?
1. Server -> Browser: Check this out, `img src="danger://"`
1. Browser: Yikes, **Thou shalt not pass!**

### ... we just wish it was smart as well!

1. Browser -> Server: q?
1. Server -> Browser: Check this out, `img src="http://bouncer/fuu"`
1. Browser -> Bouncer: q?
1. Bouncer -> Browser: You should redirect to `danger://`
1. Browser: **Ah ok, here goes!**

---

## Spring 2016 - a "project" & complexity explosion

* A public reposity @ <https://github.com/ouspg/urlhandlers/>
  * [preset URLs with query parameters](https://github.com/ouspg/urlhandlers/blob/master/web/db/handlerpresets.json)
  * [background links about URL schemes and prior vulnerabilities](https://github.com/ouspg/urlhandlers/blob/master/web/db/handlerurls.json)
  * [vulnerability assessment dissection of select URL handlers](https://github.com/ouspg/urlhandlers/tree/master/cases)
* Got a domain and **started** a web UI @ <http://hack.urlhandlers.info>
  * Like a real project, it is still WIP and doesn't do much yet :)
* Wrote tools to collect registered handlers on the OSX and Windows
  * Collected the results (handler, application, ...) in [a JSON in the repo](https://github.com/ouspg/urlhandlers/blob/master/web/db/handlerinfo.json)

.right[![Plenty of Handlers](img/handlers.png)]

---

## Summer 2016 - 3 weeks of (real) (paid) work

* @nkapu hired for few weeks at the [OUSPG Open](https://github.com/ouspg/ouspg-open/),
  thanks to Google for sponsorship
* more tools, experiments and results into the repo
* focus on the awareness
  * documenting also as [videos](https://www.youtube.com/channel/UChoH-hBnBp_cS_awaOEtT_A)
  * preparing a [Assembly Summer 2016 ARTtech presentation](http://hack.urlhandlers.info/assembly/)

### Up next- State of the art at the beginning of the summer - [xmas://](#xmas)

```html
...
<iframe src="dict://Oulu"></iframe>
<iframe src="steam://installaddon/halflifehd"></iframe>
<iframe src="word:http://www.microsoft.com/investor/downloads/events/CreditSuisseReller.docx"></iframe>
<iframe src="applescript:"></iframe>
<iframe src="bitcoin:3JDs4hAZeKE7vER2YvmH4yTMDEfoA1trnC?amount=666&label=bitcoin&message=prevails"></iframe>
<iframe src="hpevent:"></iframe>
<iframe src="vnc:"></iframe>
<iframe src="macappstores://itunes.apple.com/app/id403961173?mt=12"></iframe>
...
```

---

name: xmas
class: center, middle

.myvideo[mov/xmas-1.1.1.mp4]

---

## Autumn 2016 - Party is over?

* Back to school
* "Just one more" presentation to some vulnerability researchers
* Apple fixes some problems, yay!
* Progress on understanding the implications 0.01/100

### Up next - State of the Art at the end of the summer - [panic://](#panic)

```html
...
<iframe src="applefeedback:"></iframe>
<iframe src="applefeedback:"></iframe>
<iframe src="applefeedback:"></iframe>
<iframe src="applefeedback:"></iframe>
<iframe src="applefeedback:"></iframe>
<iframe src="applefeedback:"></iframe>
<iframe src="applefeedback:"></iframe>
<iframe src="applefeedback:"></iframe>
<iframe src="applefeedback:"></iframe>
...
```

---

name: panic
class: center, middle

.myvideo[mov/panic-1.0.mp4]

---

## Winter 2016-2017 - Disobey!

* Here we are :)
* Progress 0.02/100, need help
  * Only 3 out of the hundreds handlers dissected
  * Only fraction of the browsers checked
  * Only simplest of the injection vectors scratched
  * Testing UI and bouncer backend very much work in progress
* But hey, instead of coding we managed to enroll to Google Cloud Functions
  (a bit like Amazon's lambda) alpha to use the latest tech.
  Just to find out that didn't have even time to read the emails. :)

.right[![Plenty of Handlers](img/googlemails.png)]

---

class: center, middle

## Thanks to Everyone!

### <https://github.com/ouspg/urlhandlers/>

repository: ouspg/urlhandlers

gha_language: JavaScript

repo_name: ouspg/urlhandlers


text:
# **How to Contribute**
0. **Please contact us first**. Describe the intended contribution(s). In addition to being polite, this ensures that you aren't doing the same thing as someone else.
1. Fork the code: in Julia, type `] dev SeisIO`.
2. Choose an appropriate branch:
  - For **bug fixes**, please use `master`.
  - For **new features** or **changes**, don't use `master`. Create a new branch or push to `dev`.
3. When ready to submit, push to your fork (please, not to `master`) and submit a Pull Request (please, not to `master`).
4. Please wait while we review the request.

# **General Rules**

## **Include tests for new code**
* We expect at least 95% code coverage on each file.
* Our target code coverage is 98% on both [CodeCov](https://codecov.io/gh/jpjones76/SeisIO.jl) and [Coveralls](https://coveralls.io/github/jpjones76/SeisIO.jl?branch=master). We're rarely below 97%. Please don't break that for us.
* Good tests include a mix of [unit testing](https://en.wikipedia.org/wiki/Unit_testing) and [use cases](https://en.wikipedia.org/wiki/Use_case).

Data formats with rare encodings can be exceptions to the 95% rule. For example, SEG Y is one of four extant file formats that still uses [IBM hexadecimal Float](https://en.wikipedia.org/wiki/IBM_hexadecimal_floating_point); we've never encountered it, so we can't test it, but it exists. We understand the need to handle these digital coelocanths, but please consider their rarity before deciding that SeisIO should support one. (For example, although Int24 encoding of SEED data exists in theory, we cannot find a single researcher who's encountered it; this includes IRIS DMC staff.)

## **Don't add dependencies to the SeisIO core module**

## **Write comprehensible code**
Other contributors must be able to understand your work. People must be able to use it. Scientific software shouldn't require a Ph.D. to use, even if one needs a Ph.D. to understand the science.

## Please limit calls to other languages
For reasons of transparency, portability, and reproducibility, external calls must meet three conditions:
1. Works correctly in (non-emulated) Windows, Linux, and Mac OS.
1. Source code free and publicly available. "Please contact the author for the source code" emphatically **does not** meet this standard.
1. Must free pointers after use. If we can make your code trigger a segmentation fault, we have no choice but to reject it.

We strongly recommend only calling external functions for tasks with no Julia equivalent (e.g. plotting) or whose native Julia versions perform poorly (e.g. `DateTime`).

### Prohibited external calls
* No software with (re)distribution restrictions, such as Seismic Analysis Code (SAC)
* No commercial software, such as MATLAB™ or Mathematica™
* No software with many contributors and no clear control process, such as ObsPy, Gnu Octave, or the Arch User Repository (AUR)

# **Processing/Analysis Contributions**
Code for processing or analysis must conform to additional specifications:

## Log function calls to `:notes`
Logging to `:notes` should contain enough detail that someone who reads `:notes` can replicate the work, starting with reading raw data from `:src`. Therefore, processing and analysis calls must be logged in the `:notes` field of (each affected channel of) each relevant object:
* Use the function `note!`; see the documentation for examples.
* Within each note, record function calls and relevant options in comma-delineated fields:
  - The first field is the function name.
  - Fields after the first contain input values that affect the result.
  - Optionally, you can place human-readable information in the last field.
* An example of logging for reproducibility:
```
2019-04-19T06:28:32.313: filtfilt!, fl=1.0, fh=15.0, np=4, rp=8, rs=30, rt=Bandpass, dm=Butterworth
2019-04-19T07:20:57.531: ungap!, m=true, tap=false, filled 4 gaps (sum = 1590288 μs)
```
* An example of inadequate logging:
```
2019-04-19T06:28:32.313: called my_wavelet_function with exit code 0
2019-04-19T06:29:20:000: best basis, Haar wavelet, j=3
```

## Don't assume ideal objects
Your code must handle (or skip, as needed) channels in `GphysData` subtypes (and/or `GphysChannel` subtypes) with undesirable features. Examples from our tests include:
* irregularly-sampled data (`S.fs[i] == 0.0`), such as campaign-style GPS, SO₂ flux, and rain gauge measurements.
* data with (potentially very many) time gaps of arbitrary lengths.
  - Example: one of the mini-SEED test files comes from Steve Malone's [rebuilt Mt. St. Helens data](https://ds.iris.edu/ds/newsletter/vol16/no2/422/very-old-mount-st-helens-data-arrives-at-the-dmc/). Because the network was physically dangerous to maintain, the full record spans several months but there are >200 time gaps, ranging in size from a few samples to a week and a half. Such gaps are _very_ common in records that predate the establishment of dedicated scientific data centers.
* segments and channels with very few data points (e.g. a channel `i` with `length(S.x[i]) < 10`)
* data that are neither seismic nor geodetic (e.g. timing, radiometers, gas flux)
* empty or unusual `:resp` or `:loc` fields

You don't need to plan for others' PEBKAC errors, but these situations aren't mistakes.

It's OK to skip channels that cannot logically be processed by your code. For example, one can't bandpass filter irregularly-sampled data in a straightforward way; even *approximate* filtering requires interpolating to a regularly-sampled time series, filtering that, and extracting results at the original sample times. That's a cool trick to impress one's Ph.D. committee, but we see little demand for filtering irregularly-sampled univariate geophysical data...

## Don't assume a work flow
If a function assumes or requires specific preprocessing steps, the best practice is to add code in the function that checks `:notes` for prerequisite steps and applies them as needed.

## Leave unprocessed data alone
Skip channels (or segments within channels) that you don't process. Never alter or delete unprocessed data. We realize that some code requires very specific data (for example, three-dimensional trace rotation requires a multicomponent seismometer); in these cases, use `getfield` and `getindex` to select applicable channels.

### Tips for selecting the right data
In an object that contains data from more than one instrument type, finding the right channels to process is non-trivial. For this reason, whenever possible, SeisIO follows [SEED channel naming conventions](http://www.fdsn.org/seed_manual/SEEDManual_V2.4_Appendix-A.pdf) for the `:id` field. Thus, there are at least two ways to identify channels of interest:
1. Get the single-character "channel instrument code" for channel `i` (one way is ``split(S.id[i], '.')[4][2]``). Compare that to the [standard SEED instrument codes](https://ds.iris.edu/ds/nodes/dmc/data/formats/seed-channel-naming/).
  - This method can break on instruments whose IDs don't follow the SEED standard; placing the `split` command in a `try/catch` loop is a useful precaution here.
  - Channel code `Y` is ambiguous; beware of matching on it.
2. Check `:units`. This is usually safe, but can be problematic in two situations:
  - Some sources report units in "counts" (e.g., "counts/s", "counts/s**2"), because the "stage zero" gain is also a unit conversion.
  - Some units are ambiguous; for example, displacement seismometers and GPS displacement both use units of distance.


text:
# Steps to create code deployment
* Create a target EC2 instance
* Create IAM role for codedeploy
* Your code repo can be S3 bucket or github repo
* Create deployment group: oneatatime, halfatatime, allatonce.
* Start to deploy: create a deploy application, choose your destination EC2 instance or staging or production or multiple group.
* Deploy new application: choose deployment group, pick up git repo (rbmiao) to connect, and repo name, and commit ID.
* finish these steps, aws starts deployment.

# Trouble shooting:
* when codeployment agent has been installed.
* git commit ID is correct
* /var/log/codedeploy

# codedeploylab
This lab is to show how a AWS Code Pipeline is created using AWS Code Build, AWS Code Deploy.

This amazon web services AWS Code Deploy Setup (EC2, IAM, Github) tutorial shows how to have an AWS EC2 instances host your App that is in your Github repository.

* Learn AWS Code Deploy Setup with a demo.
* Different attributes of AWS CodeDeploy.
* Specifying EC2, Github & IAM role for CodeDeploy.
* Checking CodeDeploy logs.
* Understand CodeDeploy pricing.

In this AWS Code Deploy Setup tutorial will give an overview of Amazon lambda and its features. AWS CodeDeploy is a service that automates code deployments to Amazon EC2 instances. Code Deploy is a great way to configure multiple different applications such as DEV, QA, PROD and deploy to them each individually. You can deploy from Github to your servers or S3 for convenience. You also have a feature of rolling deployments so that if one server fails a deployment the others won't try to update and remain online. This feature will help minimize downtime.

AWS CodeDeploy is a deployment service that automates application deployments to Amazon EC2 instances, on-premises instances, serverless Lambda functions, or Amazon ECS services.

You can deploy a nearly unlimited variety of application content, such as code, serverless AWS Lambda functions, web and configuration files, executables, packages, scripts, multimedia files, and so on. AWS CodeDeploy can deploy application content that runs on a server and is stored in Amazon S3 buckets, GitHub repositories, or Bitbucket repositories. AWS CodeDeploy can also deploy a serverless Lambda function. You do not need to make changes to your existing code before you can use AWS CodeDeploy.

AWS CodeDeploy makes it easier for you to:

* Rapidly release new features.
* Update AWS Lambda function versions.
* Avoid downtime during application deployment.

Handle the complexity of updating your applications, without many of the risks associated with error-prone manual deployments.

The service scales with your infrastructure so you can easily deploy to one instance or thousands.

# Reference:
https://www.youtube.com/watch?v=K8J6ngMekx4

repository: rbmiao/aws-codedeploy

repo_name: rbmiao/aws-codedeploy


text:
# DarkIex

**TODO: Add description**

## Installation

If [available in Hex](https://hex.pm/docs/publish), the package can be installed
by adding `dark_iex` to your list of dependencies in `mix.exs`:

```elixir
def deps do
  [
    {:dark_iex, "~> 0.1.0"}
  ]
end
```

Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc)
and published on [HexDocs](https://hexdocs.pm). Once published, the docs can
be found at [https://hexdocs.pm/dark_iex](https://hexdocs.pm/dark_iex).

## Linking

```bash
ln -s ~/.iex.exs ~/dark_iex/.iex.exs
```


text:
# Native dependencies

## Adding a React Native dependency

All iOS code is kept in `ios` folder and using the same `Podfile` that's why process of adding a new React Native dependency can be achieved by running a command:

```bash
react-native link NATIVE_DEPENDENCY_NAME
```

To keep the convention of adding new dependency, only where it's exactly needed, you have to move (in `Podfile`) linked library to proper section:

1. Extend `hotels_package_module()` when dependency is used only in hotels package.

2. Extend `mmb_package_module()` when dependency is used only in mmb package.

## Add a new internal/external native dependecy

1. Add dependency folder inside `RNModules`

2. Define **`NEW_DEPENDENCY`** in `Podfile` file in `subspecs` within `pod 'RNModules'`

```
def react_native_modules()
  pod 'RNModules', path: './RNModules', subspecs: [
    'RNLogging',
    'RNTranslationManager',
    'RNCurrencyManager',
    'RNDeviceInfo',
    'RNAppleWallet',
    'RNCardManager',
    'NEW_DEPENDENCY'
  ]
end
```

3. Define source files for dependency in `RNModules.podspec`:

```
  s.subspec "NEW_DEPENDENCY" do |ss|
    ss.source_files = 'NEW_DEPENDENCY/NEW_DEPENDENCY/*.{h,m}'
  end
```

4. Run `pod install` in `ios` folder

repository: alienzhou/mobile

repo_name: alienzhou/mobile


text:
# Moneywave

[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
[![Build Status][ico-travis]][link-travis]
[![Total Downloads][ico-downloads]][link-downloads]

A PHP library for consuming the Moneywave API services.
You can check out the documentation to see all that is available: [https://moneywave-doc.herokuapp.com/](https://moneywave-doc.herokuapp.com/)

* [Quickstart](#quickstart)
* [Introduction](#introduction)
* [Configuration](#configuration)
* [Usage](#usage)
* [Services](#services)
* [Handling Responses](#handling-responses)

Quickstart
--------
To get started, you simply need to install it via `composer`:

    $ composer require emmanix2002/moneywave

This will add it to your `composer.json` and install it as a project dependency.

Introduction
--------
All the _Features_ and _Resources_ available on the **Moneywave** service are exposed as
_**Services**_. Hence, to use any of the services, it first needs to be created.

> All Features and Resources on the Moneywave API are exposed as services in this library.

The entry point to this library is the `Moneywave` class.

    $moneywave = new Moneywave();

We'll discuss more about this later.

Configuration
--------
To use the library, you need to get your credentials from your Moneywave account. They provide you two keys:

- API Key
- Secret Key

Your account can be in one of two states: `Test` or `Production`. For each of these _states_, you'll use different
**keys**.
These **keys** are required by the `Moneywave` class (and must be protected -- they are used to authenticate
the merchant account); to use them with this library, you can use one of two possible methods.

#### Environment Variables
Using this method stores the key in a specific file on your server, meaning the values are not **hardcoded** into your
code. The library expects to find a file called `.env` at the same level as your _**composer**_ `vendor` directory.

    .env
    vendor/
    composer.json
    composer.lock

As you can see above, the setting file should be at the level described. The content of the file should be the same as
you can find in the `.env.example` like so:

    # your account Moneywave API key
    MONEYWAVE_API_KEY="your API key goes here"
    # your account Moneywave Secret key
    MONEYWAVE_SECRET_KEY="your secret key goes here"
    # the environment - staging | production
    MONEYWAVE_ENV="staging"

Those values must be set to use the library; with this done, you can simply call:

    $moneywave = new Moneywave();

#### Pass into the Constructor
The second way to configure the Moneywave client is to pass all the settings into the constructor.
Unlike **method one**, you'll need to store the keys somewhere and provide them to the client when you instantiate it.

    $moneywave = new Moneywave(null, $apiKey, $secretKey); # this defaults to the STAGING environment
    $moneywave = new Moneywave(null, $apiKey, $secretKey, Environment::STAGING);

Usage
--------
When the client is instantiated (**see** [configuration](#configuration)), it automatically starts up the
`VerifyMerchant` service. This service gets an `access token` from the Moneywave service that will be used
to **authorize** every other request you make against the API.
Every `access token` has a lifespan of `2 hours`. In your application, you have one of 2 options:

- Save the retrieved token to your `Session` to use it across multiple requests
- Allow the library request one for every call made to the API

For the first option, take a look at the sample files in the `examples` directory. You'll see something like
this:

    use Emmanix2002\Moneywave\Exception\ValidationException;
    use Emmanix2002\Moneywave\Moneywave;

    require(dirname(__DIR__).'/vendor/autoload.php');
    session_start();

    try {
        $accessToken = !empty($_SESSION['accessToken']) ? $_SESSION['accessToken'] : null;
        $mw = new Moneywave($accessToken);
        $_SESSION['accessToken'] = $mw->getAccessToken();
        $query = $mw->createWalletBalanceService();
        $response = $query->send();
        var_dump($response->getData());
        var_dump($response->getMessage());
    } catch (ValidationException $e) {
        var_dump($e->getMessage());
    }

This makes it possible to use the same `access token` for another request from the same machine.

Services
--------
After instantiating the `Moneywave` object, you follow these steps to use a service:

* create an instance of the required service from it by calling one of the `create*Service()` methods
* set the properties on the **service object**
* call the `send()` method on the created **service object**.

Each feature and resource maps to a service; the mappings can be easily inferred from the **class name**.
The table below describes all the services:

| Class Name                | Service Call                          |
|---------------------------|---------------------------------------|
| AccountNumberValidation   | createAccountNumberValidationService  |
| AccountToAccount          | createAccountToAccountService         |
| AccountToWallet           | createAccountToWalletService          |
| AccountTransfer           | createAccountTransferService          |
| Banks                     | createBanksService                    |
| CardToBankAccount         | createCardToBankAccountService        |
| CardTokenization          | createCardTokenizationService         |
| CardToWallet              | createCardToWalletService             |
| CardTransfer              | createCardTransferService             |
| Disburse                  | createDisburseService                 |
| DisburseBulk              | createDisburseBulkService             |
| InternetBankingToWallet   | createInternetBankingToWalletService  |
| QueryCardToAccountTransfer| createQueryCardToAccountTransfer      |
| QueryDisbursement         | createQueryDisbursementService        |
| RetryFailedTransfer       | createRetryFailedTransferService      |
| TotalChargeToCard         | createTotalChargeToCardService        |
| ValidateCardTransfer      | createValidateCardTransferService     |
| ValidateTransfer          | createValidateTransferService         |
| VerifyMerchant            | createVerifyMerchantService           |
| WalletBalance             | createWalletBalanceService            |

Each service has a list of properties that must be set on it before it can be sent to the API; if one or more of
these properties are not set, calling `send()` throws a `ValidationException`.
Let's use the `Account Number validation API` _resource_ as an example:
From the documentation, the following properties are required:

| Field Name    | Description                               |
| ------------- | ----------------------------------------- |
| account_number| the account number of the sender          |
| bank_code     | the bank code of the account to resolve   |

To use the library, we'll do something like this:

    $moneywave = new Moneywave();
    $accountValidation = $moneywave->createAccountNumberValidationService();
    $accountValidation->account_number = '0690000004';
    $accountValidation->bank_code = Banks::ACCESS_BANK;
    $response = $accountValidation->send();

If one of those fields was not set on the _service object_, a `ValidationException` exception would have been thrown.

> Every field defined within the Moneywave documentation (for a service) can be set as a property on the
> created service object.

#### Special Fields
There are certain fields which are special, and do not need to be set by you (although you can choose to set them);
they'll be automatically given their required value by the library. Find them listed below:

| Field     | Description                                                                   |
| --------- | ----------------------------------------------------------------------------- |
| apiKey    | this will be set to the API key used to instantiate the `Moneywave` object    |
| secret    | this will be set to the secret key used for the `Moneywave` object            |
| fee       | set by **default** to `0`                                                     |
| recipient | for the `createCardToWalletService`, this is set to `wallet` by default       |
| currency  | automatically set to Naira `Currency::NAIRA`                                  |

#### Special Services
Just as there're special fields, there're also some special service objects, that present more than the regular:
`send()` method.

#### Transfers (`createCardToBankAccountService()`, `createCardToWalletService()`)
These transfer services are special because, most times, they're _2-legged_. They involve the following steps:

1 The transfer leg
2 The validation leg

These steps work one after the other; and both steps must be completed to _*complete*_ the transfer.
There're 2 services that take care of the `validation` leg; they are:

- `createValidateCardTransferService()`: allows you to validate a _*card to wallet*_ or _*card to account*_ transfer
made with a _Verve_ debit card
- `createValidateTransferService()`: allows you to validate a _*card to wallet*_ or _*card to account*_ transfer made
with an account. That is, the __charge_with__ field was set to `ChargeMethod::ACCOUNT`.

So, when you receive a success response from the API after the _first leg_; you start the validate leg.

_*NOTE*_: For Mastercard and Visa card transfers, you'll receive a `authurl` key in the successful API response; you
 are to _*redirect*_ to this URL for the payer to validate the transfer. After success or failure, the payer will be
 redirected back to the URL set in the `redirecturl` field of the transfer request.

##### createDisburseBulkService()
This service is for disbursing cash from your `Moneywave` wallet to multiple bank accounts. It has a special method on
it for adding the individual `beneficiary` accounts.

    addRecipient(string $bankCode, string $accountNumber, float $amount, string $reference = null);

This method allows you to add each beneficiary account in turn:

    $bulkDisbursement = $moneywave->createDisburseBulkService();
    $bulkDisbursement->lock = 'wallet password';
    $bulkDisbursement->ref = 'unique reference';    # suggestion: you could use a UUID; check out ramsey/uuid package
    $bulkDisbursement->senderName = 'MoneywaveSDK';
    $bulkDisbursement->addRecipient(Banks::ACCESS_BANK, '0690000004', 1)
                     ->addRecipient(Banks::ACCESS_BANK, '0690000005', 2);

Look at the `examples/disburse_bulk.php` file for the full example.

Handling Responses
----------
If all the required fields on the **service object** (see [services](#services)) have been set, the call to `send()`
will return a _response object_ which is an instance of the `MoneywaveResponse` class.
Continuing with the _Account Validation_ example above:

    $response = $accountValidation->send();

A successful response `JSON` will be of this form:

    {
        status: "success",
        data: {
            name: "MICHAEL JACKSON"
        }
    }

While a failure response `JSON` will be of the form:

    {
        status: "error",
        message: "error message description",
        code: "error code string; e.g. INVALID_ID",
        data: "data string -- this is absent most of the time"
    }

The `$response` variable presents a few functions that can be used to work with this data:

    # was a request successful?
    if ($response->isSuccessful()) {
        # do something with the returned data
        $name = $response->getData()['name'];
    } else {
        # this was a failure
        $message = $response->getMessage();
        $code = $response->getCode();
        $data = $response->getData();
    }

_**NOTE**_: All keys within the response `JSON` are also accessible from the **response object** as properties:

    if ($response->isSuccessful()) {
        $name = $response->getData()['name'];
    } else {
        $message = $response->message;
        $code = $response->code;
    }

As another example, the response from the `VerifyMerchant` service looks like this:

    {
        status: "success",
        token: "" // a valid merchant token
    }

Using the response, you'll have to do this:

    $response = $verifyService->send();
    if ($response->isSuccessful()) {
        $token = $response->token;
    } else {
        # process the error response as you normally would
    }

The table below describes the methods defined on the `MoneywaveResponse` object:

| Method            | Return Type   | Description                               |
| ----------------- | ------------- | ----------------------------------------- |
| getRawResponse()  | string        | the JSON response from the API            |
| isSuccessful()    | bool          | checks if the `status` key `=== "success"`|
| getCode()         | string        | returns the `code` key                    |
| getMessage()      | string        | returns the `message` attribute           |
| getData()         | array         | returns the `data` key                    |

**NOTE**: For responses where `data` is a string; it returns this array `[data: string]`

[ico-version]: https://img.shields.io/packagist/v/emmanix2002/moneywave.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/emmanix2002/moneywave/master.svg?style=flat-square
[ico-code-quality]: https://img.shields.io/scrutinizer/g/emmanix2002/moneywave.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/emmanix2002/moneywave.svg?style=flat-square

[link-packagist]: https://packagist.org/packages/emmanix2002/moneywave
[link-travis]: https://travis-ci.org/emmanix2002/moneywave
[link-code-quality]: https://scrutinizer-ci.com/g/emmanix2002/moneywave
[link-downloads]: https://packagist.org/packages/emmanix2002/moneywave
[link-author]: https://github.com/emmanix2002

gha_language: PHP