text:
QB Role `default_dir` Strategies
==============================================================================

Details on the acceptable values for the `default_dir` metadata key for QB roles, which I'm calling *strategies*.

-   `null` (or missing entirely) - **No strategy, DIRECTORY arg required on CLI**

    No strategy for figuring out a default directory.

    A {QB::UserInputError} will be raised by {QB::Role.default_dir}

-   `false` - **DIRECTORY arg not used**

    Role does not use a directory argument.

    Providing one via the command line *should* result in an error (though this is untested), and `qb_dir` will not be set in Ansible.

-   **Strategies with no parameters**

    Encoded as simple string values.

    -   `'cwd'` - **Current working directory**

        Use the working directory the `run` command was executed in.

        This is expected to pretty much always succeed.

        > **Example**
        >
        >     default_dir: cwd
        >

    -   `'git_root'` - **Git repo root**

        Use the root of the Git repo for the working directory the run command was executed in.

        Raises an error if that directory is not part of a Git repo.

        > **Example**
        >
        >     default_dir: git_root
        >

-   **Strategies with parameters**

    Encoded as directories with a single string key denoting the strategy pointing to a value holding the parameters.

    -   `{exe: <path:string>}` - **Run an executable**

        Run the executable at `path` and use the output, which should be a single string directory path (we do chomp what we get back).

        The exe is fed a `JSON` dump of the role options at the time via  `STDIN`, so it can dynamically determine the directory based on those if it wants.

        If `path` is relative, it's assumed to be relative to the *role directory*, **NOT** the working directory.

        Raises errors when things go wrong.

        > **Example** Role-relative executable
        >
        > This will attempt to resolve the default directory by executing the `<role_path>/bin/get_default_dir` file
        >
        >     default_dir:
        >       exe: bin/get_default_dir
        >

    -   `{find_up: <rel_path:string>}` - **Find a path walking up**

        Walk up the directory hierarchy from the CLI working directory looking for the first place that `rel_path` exists.

        This is used to do things like find the `Gemfile`, nearest
        `.gitignore`, etc:

        > **Example** Find the nearest `Gemfile` walking up directories
        >
        >     default_dir:
        >       find_up: Gemfile
        >

        > **Example** Find the nearest `.gitignore` walking up directories
        >
        >     default_dir:
        >       find_up: .gitignore
        >

        `rel_path` can be deep too:

        > **Example** Find the nearest directory walking up for which `<dir>/dev/ref` exists
        >
        >     default_dir:
        >       find_up: dev/ref
        >

    -   `{from_role: <role:string}` - **Use value from another role**

        Use the value from another QB role, which this one presumably includes.

        `role` can be anything you would normally use to locate a role using `qb run`, etc. (partial or full name or path).

        > **Example** Use the value for the `qb/ruby/bundler` role
        >
        >     default_dir:
        >       from_role: qb/ruby/bundler
        >

-   `Array` - **Multiple strategies (fallbacks)**

    A list of strategies to try; first to succeed wins.

    > **Example** Closest `Gemfile` or Git root
    >
    > Walk up directories looking for `Gemfile`, and if one can't be found then use the Git repo root.
    >
    >     default_dir:
    >     -   find_up: Gemfile
    >     -   git_root
    >

repository: nrser/qb

gha_language: Ruby

gha_license_id: MIT

repo_name: nrser/qb


text:
# RockLib.Logging.Microsoft.Extensions Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## 2.0.1 - 2023-02-21

#### Changed
- Updated RockLib.Logging package reference to `4.0.2`

## 2.0.0 - 2022-11-15

#### Added
- Added `.editorconfig` and `Directory.Build.props` files to ensure consistency.

#### Changed
- Supported targets: net6.0, netcoreapp3.1, and net48.
- As the package now uses nullable reference types, some method parameters now specify if they can accept nullable values.

## 2.0.0-alpha.1 - 2022-11-10

#### Added
- Added `.editorconfig` and `Directory.Build.props` files to ensure consistency.

#### Changed
- Supported targets: net6.0, netcoreapp3.1, and net48.
- As the package now uses nullable reference types, some method parameters now specify if they can accept nullable values.

## 1.0.5 - 2021-08-11

#### Changed

- Changes "Quicken Loans" to "Rocket Mortgage".
- Updates RockLib.Logging to latest version, [3.0.8](https://github.com/RockLib/RockLib.Logging/blob/main/RockLib.Logging/CHANGELOG.md#308---2021-08-11).

## 1.0.4 - 2021-07-30

#### Changed

-  Updates [RockLib.Logging](https://github.com/RockLib/RockLib.Logging/blob/main/RockLib.Logging/CHANGELOG.md#307---2021-07-30) package to latest version.

## 1.0.3 - 2021-07-27

#### Changed

- Updates [RockLib.Logging](https://github.com/RockLib/RockLib.Logging/blob/main/RockLib.Logging/CHANGELOG.md#306---2021-07-22) package to latest version.

#### Added

- Adds [RockLib.Logging.Microsoft.Extensions.Analyzers](https://github.com/RockLib/RockLib.Analyzers/blob/main/Logging.Microsoft.Extensions/CHANGELOG.md#100---2021-07-21) package reference.

## 1.0.2 - 2021-05-06

#### Added

- Adds SourceLink to nuget package.

#### Changed

- Updates RockLib.Logging package to latest version, which includes SourceLink.

----

**Note:** Release notes in the above format are not available for earlier versions of
RockLib.Logging.Microsoft.Extensions. What follows below are the original release notes.

----

## 1.0.1 - 2021-02-19

Adds net5.0 target.

## 1.0.0 - 2020-11-16

Initial release.

## 1.0.0-alpha02 - 2020-08-26

Updates RockLib.Logging package to the latest version, 2.1.4.

## 1.0.0-alpha01 - 2020-08-24

Initial prerelease.

license: MIT

branch_name: refs/heads/main

extension: md

gha_language: C#

license_type: permissive


text:
# FLAME
#### A cool flamegraph library for rust

Flamegraphs are a great way to view profiling information.
At a glance, they give you information about how much time your
program spends in critical sections of your code giving you some
much-needed insight into where optimizations may be needed.

Unlike tools like `perf` which have the OS interrupt your running
program repeatedly and reports on every function in your callstack,
FLAME lets you choose what you want to see in the graph by adding
performance instrumentation to your own code.

Simply use any of FLAMEs APIs to annotate the start and end of a
block code that you want timing information from, and FLAME will
organize these timings hierarchically.

### [Docs](https://docs.rs/flame/)

Here's an example of how to use some of FLAMEs APIs:

```rust
extern crate flame;

use std::fs::File;

fn main() {
    // Manual `start` and `end`
    flame::start("read file");
    let x = read_a_file();
    flame::end("read file");

    // Time the execution of a closure.  (the result of the closure is returned)
    let y = flame::span_of("database query", || query_database());

    // Time the execution of a block by creating a guard.
    let z = {
        let _guard = flame::start_guard("cpu-heavy calculation");
        cpu_heavy_operations_1();
        // Notes can be used to annotate a particular instant in time.
        flame::note("something interesting happened", None);
        cpu_heavy_operations_2()
    };

    // Dump the report to disk
    flame::dump_html(&mut File::create("flame-graph.html").unwrap()).unwrap();

    // Or read and process the data yourself!
    let spans = flame::spans();

    println!("{} {} {}", x, y, z);
}
```

And here's a screenshot of a flamegraph produced by `dump_html` (from a different project):

![flamegraph](./resources/screenshot.png "Flamegraph example")

### Full Example
```rust
use std::fs::File;

use flame;

fn make_vec(size: usize) -> Vec<u32> {
    // start_guard needs to drop to calculate duration.
    let _fg = ::flame::start_guard("make_vec");

    let mut res = flame::span_of("vec init", || vec![0_u32; size]);
    for x in 0..size {
        res[x] = ((x + 10)/3) as u32;
    }
    let mut waste_time = 0;
    for i in 0..size*10 {
        waste_time += i
    }
    res
}

fn more_computing(i: usize) {
    let _fg = ::flame::start_guard("more_computation");

    for x in 0..(i * 100) {
        let mut v = make_vec(x);
        let x = Vec::from(&v[..]);
        for i in 0..v.len() {
            let flip = (v.len() - 1) - i as usize;
            v[i] = x[flip];
        }
    }
}

fn some_computation() {
    let _fg = ::flame::start_guard("some_computation");

    for i in 0..15 {
        more_computing(i);
    }
}

fn main() {
    let _fg = ::flame::start_guard("main");

    some_computation();
    // in order to create the flamegraph you must call one of the
    // flame::dump_* functions.
    flame::dump_html(File::create("flamegraph.html").unwrap()).unwrap();
}
```

Below is the resulting flamegraph.

![flamegraph](./resources/flamegraph.png "Flamegraph example")

[llogiq](https://github.com/llogiq) has created [flamer](https://github.com/llogiq/flamer),
a compiler plugin that automatically inserts FLAME instrumentation into annotated functions
allowing you to write code like

```rust
#[flame]
fn this_function_is_profiled() {
    ...
}
```

repository: llogiq/flame

branch_name: refs/heads/master

gha_language: Rust

gha_license_id: NOASSERTION

repo_name: llogiq/flame


text:
---
layout: post
title: Week 5
---

 - what type of things are you looking for when you select an open source project to work on?

 	I'm looking for open source projects that I have used or have heard about. I am also looking for projects that have a large need for contributors, and perhaps also projects that have a humanitarian focus.

 - what are you able to offer to the team that you will be working on for the project? (what are your strengths)

 	My strength is that I will continue to try to solve a problem until it is solved. So if there is a project that needs someone to be able to reproduce a bug or to fix a bug, I will be able to keep working on reproducing or fixing the bug until me or someone else is able to.

 - what are you hoping to learn from working on an open source project?

 	I am hoping to learn more about large scale projects- projects that are bigger than an average class project. I also hope to learn more about how developers interact with each other on IRC chats and discussions.

 - what are you most worried about when you are thinking about and planning to work on an open source project?

 	I am most worried about find something to do- finding an issue that is easy enough for me to handle. I am also worried about whether I will be able to follow the contribution guidelines properly. In some repositories, people are quick to downvote comments they feel are not helpful to the issue, so that worries me.

 - Questions for Aurelia:

 1. When and how did you become interested in open source?
 2. What is a web-cartographer and why are you interested in that field?


text:
# Python 3

These are blocks of code that can be useful for doing coding problems. They might be used as-is, or altered to suite a specific problem.

I'm currently translating all of my Java code into Python, so there's not as much here right now.

## <!-- omit in toc -->Contents

- [Factoring](#factoring)
  - [Greatest Common Divisor](#greatest-common-divisor)
  - [Prime Factorization](#prime-factorization)
  - [Prove Primality](#prove-primality)
  - [Miller-Rabin Primality Test](#miller-rabin-primality-test)
- [Disjoint Sets Data Structure](#disjoint-sets-data-structure)
- [Trees](#trees)
  - [Trie Data Structure](#trie-data-structure)
  - [Fenwick Tree](#fenwick-tree)

## Factoring

### Greatest Common Divisor

[Source](https://en.wikipedia.org/wiki/Euclidean_algorithm)

```python
def gcd(a: int, b: int) -> int:
    """Finds the greatest common divisor of two integers using the Euclidean
        division algorithm.

    Args:
        a (int): The first integer.
        b (int): The second integer.

    Returns:
        int: The GCD of a and b.
    """

    # a holds the last-last remainder of a % b
    # b hold the last remainder of a % b
    while b != 0:
        a, b = b, a % b
    # stop when a % b == 0
    return a
```

### Prime Factorization

Repeatedly divides a given number to count the factors. Time-complexity is _O(n^0.5)_, where _n_ is the size of the factored number.

It can greatly benefit from a fast prime check, to see if a number has any factors (see below).

```python
def prime_factors(num: int) -> list[tuple[int]]:
    """Finds all prime factors of a number

    Args:
        num (int): The number to prime factorize.

    Returns:
        list[tuple[int]]: A list of factors from least to greatest in tuple form: (factor, power)
    """

    factors = []
    # return numbers that are too small
    if num < 4:
        factors.append((num, 1))
        return factors
    # add the number of twos that divide num
    if (num & 1) == 0:
        power = 0
        while (num & 1) == 0:
            power += 1
            num >>= 1
        factors.append((2, power))
        if num == 1:
            return factors
    # num must be odd
    limit = num ** 0.5 + 1
    pf = 3
    while pf < limit:
        if num % pf == 0:
            power = 0
            while num % pf == 0:
                power += 1
                num //= pf
            factors.append((pf, power))
            if num == 1:
                return factors
            limit = num ** 0.5 + 1
        pf += 2
    # num is a prime greater than 2
    factors.append((num, 1))
    return factors
```

[back to top](#python-3)

### Prove Primality

The only way to prove that a number is prime is to check smaller numbers for factors. The time-complexity is _O(n^0.5)_. There are shortcuts that can be taken for [special cases](https://en.wikipedia.org/wiki/Primality_test), and probabilistic primality tests perform much better.

```python
def primality(num: int) -> bool:
    """Checks if a number is prime.

    Args:
        num (int): The number to check for primality.

    Returns:
        bool: Whether the number is prime.
    """

    if num % 2 == 0:
        return num == 2
    if num < 2:
        return False
    # check for factors up to the square root of num
    for f in range(3, int(num ** 0.5)):
        if num % f == 0:
            return False
    return True
```

[back to top](#python-3)

### Miller-Rabin Primality Test

This is a probabilistic primality test. It will always detect a prime number (no false negatives), but has a false positive rate of at most _4^-k_, where _k_ is the number of repetitions that the test is performed. For large numbers, the accuracy improves to _8^-k_. Time-complexity is _O(k lg^3(n))_, where _k_ is the number of repetitions and _n_ is the tested number.

Performance can be improved by using [specific witnesses](https://en.wikipedia.org/wiki/Miller–Rabin_primality_test#Testing_against_small_sets_of_bases) rather than random ones.

Sources: [Wikipedia](https://en.wikipedia.org/wiki/Miller–Rabin_primality_test), [GeeksforGeeks](https://www.geeksforgeeks.org/primality-test-set-3-miller-rabin/?ref=lbp)

```python
def primality_test(num: int, rep: int) -> bool:
    """Performs the Miller-Rabin primality test to determine if a number is a
        probable prime.

    Args:
        num (int): The number to test for primality.
        rep (int): The number of repetitions to perform the test.

    Returns:
        bool: True if the number is a probable prime. False if the number is
            composite.
    """

    # handle small cases
    if num % 2 == 0:
        return num == 2
    if num < 9:
        return num > 1
    # find d by factoring out all powers of 2
    d = num - 1
    r = 0
    while d & 1 == 0:
        d >>= 1
        r += 1
    # repeat the test for the specified number of repetitions
    for _ in range(rep):
        if not test_witness(num, d, r):
            return False
    # num is a probable prime
    return True

def test_witness(num: int, d: int, r: int) -> bool:
    """Tests a number for the Miller-Rabin primality test with a random
        witness.

    Args:
        num (int): The number to test for primality.
        d (int): The number (num - 1) with all powers of 2 removed.
        r (int): The power of 2 removed to make d, (2 ** r * d == num - 1)

    Returns:
        bool: Whether the number passed the test.
    """

    a = random.randint(2, num - 2)
    x = mod_pow(a, d, num)
    if x == 1 or x + 1 == num:
        return True
    for _ in range(r - 1):
        x = x * x % num
        if x + 1 == num:
            return True
        # check if x won't change
        if x == 1:
            break
    return False

def mod_pow(base: int, exp: int, mod: int) -> int:
    """Performs exponentiation with modulo.

    Args:
        base (int): The number to exponentiate.
        exp (int): The exponent.
        mod (int): The modulo number.

    Returns:
        int: The result, (base ** exp % mod)
    """

    res = 1
    base %= mod
    while exp > 0:
        # multiply res if exp is odd
        if exp & 1 == 1:
            res = res * base % mod
        # square the base if exp is even
        exp >>= 1
        base = base * base % mod
    return res
```

[back to top](#python-3)

## Disjoint Sets Data Structure

Useful for keeping track of sets of disjoint elements, and performing unions between sets. Time-complexity is _Θ(m lg\*(n))_, where _m_ is the number of operations and _n_ is the number of sets.

This code uses path-compression and union by rank.

```python
class DSet:
    """A disjoint set.

    Attributes:
        parent (DSet): The DSet used to find the set's representative.
        rank (int): The maximum path length to a child DSet.
    """

    def __init__(self) -> None:
        """Inits DSet as a new set."""

        self.parent = self
        self.rank = 0

def find(x: DSet) -> DSet:
    """Finds a set's representative.

    Args:
        x (DSet): The disjoint set that we're searching for.

    Returns:
        DSet: The representative of the disjoint set.
    """

    if x is not x.parent:
        x.parent = find(x.parent)
    return x.parent

def union(a: DSet, b: DSet) -> None:
    """Unions two sets.

    Args:
        a (DSet): The first set to union.
        b (DSet): The second set to union.
    """

    a = find(a)
    b = find(b)
    if a is b:
        return
    if a.rank > b.rank:
        b.parent = a
    else:
        a.parent = b
        if a.rank == b.rank:
            b.rank += 1
```

[back to top](#python-3)

## Trees

### Trie Data Structure

Used to store a dictionary of patterns. Time-complexity is linear in the length of the pattern.

[source (the java code)](https://www.geeksforgeeks.org/trie-insert-and-search/)

```python
class Trie:
    """A trie data structure.

    Attributes:
        ALPHABET_SIZE (int): The size of the alphabet.
        root (Node): The root node of the trie.
    """

    ALPHABET_SIZE = 26

    def __init__(self) -> None:
        """Inits an empty Trie."""

        self.root = self.Node()

    def insert(self, pattern: str) -> None:
        """Inserts a pattern into this trie.

        Args:
            pattern (str): The pattern to be inserted.
        """

        crawl = self.root
        # crawl down the trie, creating new nodes as needed
        for c in pattern:
            child = self.index(c)
            if crawl.children[child] is None:
                crawl.children[child] = self.Node()
            crawl = crawl.children[child]
        # crawl is the last chr in pattern
        crawl.isend = True

    def search(self, pattern: str) -> bool:
        """Finds a pattern in this trie.

        Args:
            pattern (str): The pattern to search for.

        Returns:
            bool: True if the pattern is in this trie.
        """

        crawl = self.root
        # crawl down the trie
        for c in pattern:
            child = self.index(c)
            # check if the chr exists
            if crawl.children[child] is None:
                return False
            crawl = crawl.children[child]
        # check if the last chr is in the pattern and is an end node
        return crawl is not None and crawl.isend

    @staticmethod
    def index(c: chr) -> int:
        """Determines the index of a chr in a children array.

        Args:
            c (chr): The chr to index.

        Returns:
            int: The index of c in a children array.
        """

        return ord(c) - ord("a")

    class Node:
        """A node in a trie.

        Attributes:
            children (list[{Node, None}]): The characters that are children of
            this Node.
            isend (bool): Indicates if this Node is the end of a pattern.
        """

        def __init__(self) -> None:
            """Inits an empty Node."""

            self.children = [None] * Trie.ALPHABET_SIZE
            self.isend = False
```

[back to top](#python-3)

### Fenwick Tree

A binary indexed tree. Useful for finding the sum of a range of values in an array in logarithmic time. Each node in the tree stores the sum within a range from the index down to the index minus the smallest set bit in the index's binary representation.

> Example
> 10 = 0b1010
> 2 = 0b0010
> 10 - 2 = 8
> tree[10] = sum of values[9..10]

```python
class Fenwick_Tree:
    """A Fenwick Tree (Binary Indexed Tree).

    Attributes:
        values (list[int]): The list of values.
        tree (list[int]): The Fenwick Tree. Indexes are offset by 1.
    """

    def __init__(self, size: int) -> None:
        """Inits a fenwick tree with all zero values.

        Args:
            size (int): The number of values in the tree.
        """

        self.values = [0] * size
        self.tree = [0] * (size + 1)

    def update(self, index: int, value: int) -> None:
        """Updates the value of an index.

        Args:
            index (int): The index to be updated.
            value (int): The value to update the index to.
        """

        dif = value - self.values[index]
        self.values[index] = value
        # update the value of the index and all successors
        index += 1
        while index < len(self.tree):
            self.tree[index] += dif
            index += index & (-index)

    def count(self, index: int) -> int:
        """Counts values up to an index.

        Args:
            index (int): The last index to include in the count.

        Returns:
            int: The sum of values in the range [0 : index].
        """

        count = 0
        # add the value of the index and all ancestors
        index += 1
        while index > 0:
            count += self.tree[index]
            index -= index & (-index)
        return count
```

[back to top](#python-3)

repository: charlotte-zhuang/coding-problems

repo_name: charlotte-zhuang/coding-problems


text:
# keyboard

## class KDKeyboardListener

The keyboard listener is responsible for listening to keyboard combinations, and dispatching the appropriate behavior. It represents a prioritized grouping of keyboard maps (see below). It has some interesting attributes.

* Only one keyboard listener can be active at a given time. When you call listen on an instance, that implies that whatever instance is currently listening will be reset.
* It has numerical levels of priority that are more or less arbitrary: you can use these to organize key combos in whatever way you want. Perhaps you have global key combos, contextual key combos, and user defined key combos. Your application can decide the semantics, but the rule is, only the matching combination of the highest priority will be called.
* You can add and remove keyboard mappings to any listener, active or not, at any time.

## api

### new KDKeyboardListener

Instantiate a new KDKeyboardListener instance. There are no parameters.

### l.addComboMap(comboMap[, priority])

Add a combo map to the triage at a given priority. If you don't provide a priority, it will default to either the value of the priority property of the keyboard map itself, if any, or zero.

### l.removeComboMap(comboMap)

Remove a combo map from the triage.

### l.listen()

Start listening to keyboard events. This action implictly unseats the current listener, if any, which will have its reset method called.

### l.reset()

Stops listening to keyboard events, but does not clear any currently registered listeners.

### l.getCombos()

Returns an array of all currently listening keyboard maps, ordered by priority and flattened.

### l.combos(callback)

Iterates over `getCombos()` with the supplied callback of the signature:

'callback(combo, options, listener)`

Where:

`combo` - the combo that was invoked.

`options` - the options that were passed; can be `null`.

`listener` - the behavior function that is mapped to the combo.

### l.isActive()

Is the keyboard listener active?

### KDKeyboardListener.current()

Returns the current keyboard listener, if any, otherwise returns a temporary one.

## class KDKeyboardMap

This class represents a map of keyboard combinations to behaviors.  The combinations are represented using a simple DSL, and the behaviors are just functions.

## api

### new KDKeyboardMap(options)

Instantiate a new KDKeyboardMap instance.  Options are:

`map` - a simple dictionary mapping combos to their behaviors.

`priority` — a number representing the relative priority for this map.  This is arbitrary.  Higher priority is better.

### m.addCombo(combo[, options], behavior)

Adds a combo to the map.  It will overwrite any preexisting same combo.  Options are:

`global` - Default true.  When false, key combinations will not be listened to while an input element is selected.

### m.removeCombo(combo)

Removes a combo from the map.

### m.eachCombo(callback)

Iterates over the map, supplying the given callback with the following signature:

`callback(combo, options, listener)`

Where:

`combo` - the combo that was invoked.

`options` - the options that were passed; can be `null`.

`listener` - the behavior function that is mapped to the combo.

repository: gokhansongul/kd

repo_name: gokhansongul/kd


text:
---
layout: inner-page-no-masthead
title: Functional Programming in Scala Capstone
course-page: https://www.coursera.org/learn/scala-capstone
date: 01-02-2017
end-date: 01-04-2017
platform: coursera
specialization: fpfun
specialization-order: 5
paid: false
showDate: false
---

In the final capstone project you will apply the skills you learned by building a large data-intensive application using real-world data.

You will implement a complete application processing several gigabytes of data. This application will show interactive visualizations of the evolution of temperatures over time all over the world.

The development of such an application will involve:
 — transforming data provided by weather stations into meaningful information like, for instance, the average temperature of each point of the globe over the last ten years ;
 — then, making images from this information by using spatial and linear interpolation techniques ;
 — finally, implementing how the user interface will react to users’ actions.

repository: jvican/scala-lang

gha_language: CSS

repo_name: jvican/scala-lang


text:
# 0.0.1-dev.9

- feat: add `FakeFlowController<T>` for verifying flow interactions

# 0.0.1-dev.8

- feat: `FlowBuilder` accepts an optional `FlowController<T>`
- feat: throw `FlutterError` when `context.flow` is called outside of a `FlowBuilder`

# 0.0.1-dev.7

- **BREAKING**: update `onGeneratePages` to include previous `pages`

# 0.0.1-dev.6

- feat: add `onComplete`

# 0.0.1-dev.5

- docs: fix README badges (CORS)

# 0.0.1-dev.4

- **BREAKING**: replace `builder` with `onGeneratePages`
- fix: navigation animation
- fix: system back navigation

# 0.0.1-dev.3

- fix: pop after external state change exception
- test: 100% coverage

# 0.0.1-dev.2

- feat!: remove explicit `FlowController` from `builder`

# 0.0.1-dev.1

- feat: initial release of `FlowBuilder`


text:
# JSON Store
Detailed information on the usage of the JSON Store REST service.

| Contents
| ---
| [Configuration](#configuration)
| [CRUD Operations](#crud-operations)
| - [Read](#read)
| - [Create](#create)
| - [Update](#update)
| - [Partial Update](#partial-update)
| - [Delete](#delete)

## Configuration
*This service does NOT use authentication - everything is fully accessible without any credentials.*

This service dynamically loads collections from the `./data/` folder, located with the server. Any JSON file in this folder will be accessible via requests.

## CRUD Operations

All requests are sent to `/jsonstore/:resource`. Resources can be nested and have any shape. Individual properties can be accessed by appending `/:propName` to the endpoint as deep as you require. Supported requests are `GET`, `POST`, `PUT`, `PATCH`, `DELETE`

### Read

Send a `GET` request to the endpoint. The response will be in JSON format.

**Examples**

Retrieve everything inside the `books` collection:
- **Method:** `GET`
- **Endpont:** `/jsonstore/books`

Retrieve entry with ID **"asdf-1234"** from the `books` collection:
- **Method:** `GET`
- **Endpont:** `/jsonstore/books/asdf-1234`

### Create

Send a `POST` request to the endpoint. The shape of the body is not restricted. The service will respond with the object, created in the store, which will have an added `_id` property, that is automatically generated.

**Examples**

Create a new entry inside the `books` collection:
- **Method:** `POST`
- **Endpont:** `/jsonstore/books`
- **Headers:** `Content-Type: application/json`
- **Body:** *JSON-formatted data*

### Update

Send a `PUT` request to the endpoint, appending the Id or any appropriate property name. The existing resource will be **fully replaced**! The service will respond with the updated object.

**Examples**

Update entry with ID **"asdf-1234"** in the `books` collection:
- **Method:** `PUT`
- **Endpont:** `/jsonstore/books/asdf-1234`
- **Headers:** `Content-Type: application/json`
- **Body:** *JSON-formatted data*

### Partial Update

Send a `PATCH` request to the endpoint, appending the Id or any appropriate property name. The service will perform a **shallow merge** with the new data and respond with the updated object.

**Examples**

Partially update entry with ID **"asdf-1234"** in the `books` collection:
- **Method:** `PATCH`
- **Endpont:** `/jsonstore/books/asdf-1234`
- **Headers:** `Content-Type: application/json`
- **Body:** *JSON-formatted data*

### Delete

Send a `DELETE` request to the endpoint, appending the Id or any appropriate property name. The service will respond with the deleted object.

**Examples**

Delete entry with ID **"asdf-1234"** from the `books` collection:
- **Method:** `DELETE`
- **Endpont:** `/jsonstore/books/asdf-1234`

repository: NPashofff/softuni-practice-server

repo_name: NPashofff/softuni-practice-server


text:
##CARP

This repository maintains the source code of our implementation on CARP, context-aware reliability prediction of black-box services.

Read more information from our paper: [[Paper](http://arxiv.org/abs/1503.00102)][[Project page](http://wsdream.github.io/CARP)]

###Related Links

- [Publication list of Web service recommendation research](https://github.com/wsdream/pywsrec/blob/master/docs/paperlist.rst)

- [WS-DREAM QoS datasets](https://github.com/wsdream/dataset)

###Dependencies
- Python 2.7 (https://www.python.org)
- numpy 1.8.1 (http://www.scipy.org)
- scipy 0.13.3 (http://www.scipy.org)

The benchmark is implemented as a Python package. For efficiency purpose, the core algorithms are written as C++ extension for Python with the use of [Cython](http://cython.org "a language and compiler to write C/C++ extenstions for Python").

###Feedback
For bugs and feedback, please post to [our issue page](https://github.com/wsdream/CARP/issues). For any other enquires, please drop an email to our team (wsdream.maillist@gmail.com).

###License
[The MIT License (MIT)](./LICENSE)

Copyright © 2015, [WS-DREAM](https://wsdream.github.io), CUHK


text:
---
title: "Lessons, not losses (nor wins)"
created_at: 2020-11-14T17:23:56.000Z
published_at: 2020-11-14T17:42:22.000Z
---
Overheard on the Twitterverse today:

> There are only wins or lessons. No losses. ~ @thisiskp\_

That's the growth mindset right there. It's easy to feel demoralised when we framed situation in winners versus losers, victories versus defeats. It's all too easy to play this zero sum game. But having a growth mindset means that losses get reframed into lessons. You didn't fail, you just found one way out of many ways that wouldn't work, hence trimming down the universe of what doesn't work and increasing the likelihood that you'll eventually get to something that does work.

If you think about it, by the same thread, wins aren't really wins either. You found a way that worked today. It might not work tomorrow, or some time in the future. It might have been completely happenstance or circumstantial. You might just be lucky. At best a win is a clue, that you might be on to something big. It's a never-ending iterative process, cycles after cycles of sniffing out clues and iterating, improving, evolving. Life is such – always in the process of becoming.

So, perhaps the original line needs revision?

**_There are only lessons. No wins, no losses._**


text:
# Challenge 27

## Print last lines

> **Difficulty**: Easy

Write a function that accepts a filename on disk, then prints its last N lines in reverse order, all on a single line separated by commas.

### Sample input and output

Here is your test input file:

``` text
Antony And Cleopatra
Coriolanus
Cymbeline
Hamlet
Julius Caesar
King Lear
Macbeth
Othello
Twelfth Night
```

- If asked to print the last `3` lines, your code should output *“Twelfth Night, Othello, Macbeth”*.
- If asked to print the last `100` lines, your code should output *“Twelfth Night, Othello, Macbeth, King Lear, Julius Caesar, Hamlet, Cymbeline, Coriolanus, Antony and Cleopatra”*.
- If asked to print the last `0` lines, your could should print *nothing*.

### Stub

``` swift
import Foundation

func challenge27(file name: String, lines: Int) -> String {
    // your code goes here
    return ""
}

// test cases
assert(challenge27(file: "input.txt", lines: 3) == "Twelfth Night, Othello, Macbeth", "Challenge 27: Test #1 - failed")
assert(challenge27(file: "input.txt", lines: 100) == "Twelfth Night, Othello, Macbeth, King Lear, Julius Caesar, Hamlet, Cymbeline, Coriolanus, Antony and Cleopatra", "Challenge 27: Test #2 - failed")
assert(challenge27(file: "input.txt", lines: 0) == "", "Challenge 27: Test #3 - failed")
```

### Hints

> **NOTE**: Remember, read as few hints as you can to help you solve the challenge, and only read them if you’ve tried and failed.

1. Use the `contentsOfFile` initializer to pull in the text, then `components(separatedBy:)` to create an array of lines.
2. Arrays have a built-in `reverse()` method that flip them around in-place.
3. You need to print the last *N* lines, but of course you don’t want to read beyond the size of the array. Make sure you use the `min()` function to choose the lesser of the two.

### Solution 1

``` swift
import Foundation

func challenge27(file name: String, lines: Int) -> String {
    guard let data = try? String(contentsOfFile: name) else { return "" }
    let list = data.components(separatedBy: "\n").reversed()
    return list.prefix(min(lines, list.count)).joined(separator: ", ")
}

// test cases
assert(challenge27(file: "input.txt", lines: 3) == "Twelfth Night, Othello, Macbeth", "Challenge 27: Test #1 - failed")
assert(challenge27(file: "input.txt", lines: 100) == "Twelfth Night, Othello, Macbeth, King Lear, Julius Caesar, Hamlet, Cymbeline, Coriolanus, Antony and Cleopatra", "Challenge 27: Test #2 - failed")
assert(challenge27(file: "input.txt", lines: 0) == "", "Challenge 27: Test #3 - failed")
```

> **Time Complexity** (worst case): `O(n)`

repository: hauntarl/swift-cc

repo_name: hauntarl/swift-cc


text:
# Probably.jl
_Probabilistic data structures in Julia_

[![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://jakobnissen.github.io/Probably.jl/dev)
[![CI](https://github.com/jakobnissen/Probably.jl/workflows/CI/badge.svg)](https://github.com/jakobnissen/Probably.jl/actions?query=workflow%3ACI)
[![Codecov](https://codecov.io/gh/jakobnissen/Probably.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/jakobnissen/Probably.jl)

Probably.jl provides an implementation of common probabilistic data structures that are:
- Written in pure Julia
- Both fast and memory-efficient
- Good for default or casual use cases, easy to use in other projects
- Manipulated via functions with names from Julia's Base library

This package does __not__ attempt to:
- Provide a wide array of of functionality
- Provide structures 100% optimized for different use cases
- Gloss over the limitation of the data structures. Instead, you are expected to understand in broad strokes how the data structures work before you use them.

## Package features
Probably.jl currently includes the following data structures:
 - Bloom filter
 - Cuckoo filter
 - Count-min sketch
 - HyperLogLog

## Contributing
Found a bug? Have a good idea for performance improvements? Know some sweet probabilistic data structure this package needs?

Great, any feedback is very much appreciated! Just create an Issue here on GitHub or send me an email and we'll discuss it.

gha_language: Julia


text:
---
title: Basic React app
description: A basic React app that displays a list of WKND adventures and their details
version: Cloud Service
mini-toc-levels: 1
feature: Content Fragments, GraphQL API
topic: Headless, Content Management
role: Developer
level: Beginner
kt: 11134
thumbnail: KT-11134.jpg
index: no
hide: yes
hidefromtoc: yes
exl-id: 870be37f-68bb-4b0f-9918-e68b09be830e
---
# Basic React app

This [React](https://reactjs.org/) app demonstrates how to query content using AEM's GraphQL APIs using persisted queries. This application renders a filterable of WKND Adventures, and upon selecting an adventure, displays the adventures full details.

This code:

+ Connects to an AEM Publish service, and does not require authentication
+ Uses the WKND's persisted queries: `wknd-shared/adventures-all` and `wknd-shared/adventures-by-slug`

For a more indepth review of how this Next.js app is built, review the [example React app documentation](../example-apps/react-app.md).

gha_language: SCSS


text:
![LICENSE](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)
![Security Status](https://img.shields.io/security-headers?label=Security&url=https%3A%2F%2Fgithub.com&style=flat-square)
![Gluten Status](https://img.shields.io/badge/Gluten-Free-green.svg)
![Eco Status](https://img.shields.io/badge/ECO-Friendly-green.svg)

# Coming soon

_local server and sql usage to suppliy data for website, learning project_

This project is for learning porpuses only!

## Project features

- repetitive content is generated/rendered
- NodeJS
- file system for data storage
- some data taken and rendered from SQL

## Project pages structure

### Public pages

- home
- 404

### Protected pages

- admin/services
- admin/add-service
- admin/edit-service
- admin/service-deleted

## Authors

[Paulius B.](https://github.com/Scarab911)


text:
# SourceList

*Abstract*

## Subclasses

[SourceCodelist](SourceCodelist.md)

[TargetCodelist](TargetCodelist.md)

## Referenced By

[HybridCodelistMap](HybridCodelistMap.md) (as source)


text:
# CuteVR

#### Links
* [Documentation](https://cutevr.gitlab.io/CuteVR/index.html)
* [Changelog](CHANGELOG.md)
* [License](LICENSE.md)

## Introduction
Coming soon...

#### Motivation
Coming soon...

#### Features
Coming soon...

## Authors
* Marcus Meeßen — Initial work — [GitLab](https://gitlab.com/marsmee) / [GitHub](https://github.com/marsmee)

#### Acknowledgments
* This project was partially funded in 2018 by the German Federal Ministry of Education and Research (Bundesministerium
  für Bildung und Forschung, BMBF) within grant 033R126C.

## Status
[![pipeline status](https://gitlab.com/cutevr/CuteVR/badges/master/pipeline.svg)](https://gitlab.com/cutevr/CuteVR/commits/master)
[![pipeline status](https://gitlab.com/cutevr/CuteVR/badges/stage/pipeline.svg)](https://gitlab.com/cutevr/CuteVR/commits/master)

## Getting Started

### Prerequisites
* CMake 3.5.1 (3.9.x is recommended)
* GCC 5.4 (6.0 is recommended)
* Qt 5.5.0 Core and GUI
* SteamVR

###### Additional packages for examples
* ROSPublisher
  * ROS base
* SolarSystem
  * Qt 5.5.0 OpenGL
* ViveMonitoring
  * Qt 5.5.0 QML

###### Additional packages for building
* OpenVR SDK

### Building & Installing
Coming soon...

#### Running the Tests
Coming soon...

#### Versioning
Coming soon... [SemVer](http://semver.org/)

repository: marsmee/CuteVR

repo_name: marsmee/CuteVR


text:
 JUST PERFECT

One Step Closer To Being Perfect

### Overview
Canadians throw away an average of $854 per person each year of unused food. A key factor to this
problem is that shoppers do not know how much to buy when grocery shopping. Our web based application JustPerfect will provide the estimated measurement for each meal on a weekly basis, cutting down the excess food bought by consumers each day.

This document will walk you through the process of setting up and creating the application of Team 7.

### Members
* [J]eevan Bains
* [M]ike Hoang
* [A]ndrew Yang
* [A]ntonio Cao Shen (C)
* [N]irajan Manandhar

# Table of Contents

* [Install MySQL](#install-mysql)
* [Connect MySQL and PHP](#connect-mysql-and-php)
* [Deploy on Azure](#deploy-on-azure)
* [Fetch Recipe API](#fetch-recipe-api)
* [Social Login APIs](#social-login-apis)
* [Credit](#credit)

## Install MySQL

## Connect MySQL and PHP

## Deploy on Azure
 HERE

## Fetch Recipe API

## Social Login APIs

## Credit
Special thanks to  HTML5 UP, Code House for the templates and Spoonacular for the Recipe APIs.


text:
# Docker Compose Example Format

```yml
version: '3.2'

networks:
  compose-network:
    external:
      name: '<your-docker-network-name>'

services:
  app:
    image: '<your-existing-image>'
    volumes:
      - '</host/path/project/>:</container/path/project>'
    networks:
      compose-network:
        ipv4_address: '<you-docker-network-ip-address ex. 192.168.x.x>'
    ports:
      - '<host-port>:<container-port>'
    tty: true
    stdin_open: true
    restart: 'no'
    container_name: '<your-container-name>'
```

repository: LordDashMe/knowledge

gha_language: Dockerfile

repo_name: LordDashMe/knowledge


text:
# Getting Started

TensorFlow is a tool for machine learning. While it contains a wide range of
functionality, it is mainly designed for deep neural network models.

The fastest way to build a fully-featured model trained on your data is to use
TensorFlow's high-level API. In the following examples, we will use the
high-level API on the classic [Iris dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set).
We will train a model that predicts what species a flower is based on its
characteristics, and along the way get a quick introduction to the basic tasks
in TensorFlow using Estimators.

This tutorial is divided into the following parts:

  * @{$get_started/premade_estimators}, which shows you
    how to quickly setup prebuilt models to train on in-memory data.
  * @{$get_started/checkpoints}, which shows you how to save training progress,
    and resume where you left off.
  * @{$get_started/feature_columns}, which shows how an
    Estimator can handle a variety of input data types without changes to the
    model.
  * @{$get_started/datasets_quickstart}, which is a minimal introduction to
    the TensorFlow's input pipelines.
  * @{$get_started/custom_estimators}, which demonstrates how
    to build and train models you design yourself.

For more advanced users:

  * The @{$low_level_intro$Low Level Introduction} demonstrates how to use
    tensorflow outside of the Estimator framework, for debugging and
    experimentation.
  * The remainder of the @{$programmers_guide$Programmer's Guide} contains
    in-depth guides to various major components of TensorFlow.
  * The @{$tutorials$Tutorials} provide walkthroughs of a variety of
    TensorFlow models.

repository: PipelineAI/tensorflow

repo_name: PipelineAI/tensorflow


text:
# Bitcoin Script Debugger

The Bitcoin Script Debugger is a web-based IDE that allows to run and debug bitcoin scripts in a standalone environment.

![alt text](https://github.com/RolfZurbrugg/bitcoin-script-debugger/blob/master/doc/ide2.png "Screenshot of the IDE")

## Feature Overview

* Easy to use user interface
* Syntax highlighting
* Automatic code formatting
* Step-by-step debugging
* Predefined Script Variables for experimenting
* Check if a script is standard or not

## User Guide

The IDE is either in one of two modes: The Edit mode or Debug mode.

### Edit mode

While being in the Edit mode, you can edit both the input and output script. The IDE comes with an auto formatting feature that allows you to automatically format your script so that they look nicely and can be better read. To format your scripts simply click on the Auto Format button:

![alt text](https://github.com/RolfZurbrugg/bitcoin-script-debugger/blob/master/doc/btnAutoFormatScript.png "Auto Format button")

To enter the debug mode you can press the Run button which executes the script and shows the final stack after both scripts have been executed (you will still be able to step through the script though):

![alt text](https://github.com/RolfZurbrugg/bitcoin-script-debugger/blob/master/doc/btnRunScript.png "Run button")

Or you can start debugging your script from the beginning by simply pressing on the Step Forward button which execute the scripts step by step:

![alt text](https://github.com/RolfZurbrugg/bitcoin-script-debugger/blob/master/doc/btnStepForwardScript.png "Run button")

### Debug Mode

When you have entered the Debug mode, you cannot edit or format the scripts anymore. To do that you have to go back into the Edit mode. As long as you are in the Edit mode you can step back and forth through your script and inspect the current stack:

You can Step Forward with the Step Forward button as already mentiond before. The Step Backward button allows you to go back to the previous execution step:

![alt text](https://github.com/RolfZurbrugg/bitcoin-script-debugger/blob/master/doc/btnStepBackwardScript.png "Step Backward button")

Inside the script editors the Opcode that gets executed next when you press the Step Forward button is highlighted. This doesn't work for the Step Backward button though.

To go back into the Edit mode simply click on the Stop button:

![alt text](https://github.com/RolfZurbrugg/bitcoin-script-debugger/blob/master/doc/btnStopScript.png "Stop button")

### Script Variables

The Bitcoin Script Debugger includes some predefined variables to experiment with. You can see all of them in the right bottom pane of the IDE:

![alt text](https://github.com/RolfZurbrugg/bitcoin-script-debugger/blob/master/doc/variables.png "Variables").

To use them in your script simply write their corresponding name in curly braktes like so: `<sig_0> <pubK_0> OP_CHECKSIG`.

### Signing a Transaction

In order to use OP_CHECKSIG the scriptPubKey script must be present. After signing the transaction the scriptPubKey script can no longer be edited. A dummy transaction is created in the background and the specified private key from the drop down will be used, to sign the transaction. At this point the user has access to the script variable <sig_0>.

### Check if a script is standard

In the header of each editor pane is a Check Standard button. You can click this button to check if the given script is a standard script or not:

![alt text](https://github.com/RolfZurbrugg/bitcoin-script-debugger/blob/master/doc/btnCheckStandard2.png "Check Standard button")

## Technical Overview

### Architecture

The Bitcoin Script Debugger builts on top of the JavaScript Bitcore library from bitcore.io and is roughly composed of the following layers:

![alt text](https://github.com/RolfZurbrugg/bitcoin-script-debugger/blob/master/doc/architectur.png "Architectural Overview")

#### User Interface

The User Interface definition is implemented in the index.html file and is based on the popular CSS Framework Bootstrap 3. Additional styles and modifications of 3rd Party styles have been made in the css/app.css file.

#### Application Layer

The Application Layer is responsible for what is actually shown on the User Interface. It controls the appeareance and behaviour of the user controls and delegates actions down to the next layers like evaluation of the bitcoin scripts. Error handling is also done in the Application Layer.

#### Script Parser and Debug Layer

The bitcore library itself does not support debugging of scripts. The library itself can simple execute a script and return its final result. In order to be able to debug scripts a separate Script Parser is used together with a Debug Layer. The custom Script Parser allows for using custom variables and mapping of the opcodes to their corresponding positions in the text editor. The Debug Layer hooks itself into the bitcore interpreter and saves a copy of the actual stack after each executed step.

#### Bitcoin Script Interpreter

At the core of the IDE lays the Bitcoin Script Interpreter which is only a small part of the bitcore lib. More details about the bitcore lib itself can be found here: http://www.bitcore.io.

### Other used Libraries

#### CodeMirror

CodeMirror is a powerful text editor that is especially designed for coding. While CodeMirror supports a huge range of languages out of the box, Bitcoin Script or simply called Script is not one of them. So a custom mode (something like a language plugin) had to be implemented in order to support Script. This mode and the auto formatting feature has been implemented in the codeMirrorExtensions.js file. More details about CodeMirror can be found here: https://codemirror.net/.

#### jQuery

There is almost no JavaScript that works without jQuery. Neither does our Bitcoin Script Debugger. jQuery deals with a lot of cross browser compatibility issues and abstracts the interaction with the DOM structure. More details about jQuery can be found here: https://jquery.com/.

repository: RolfZurbrugg/bitcoin-script-debugger

repo_name: RolfZurbrugg/bitcoin-script-debugger


text:
---
title: the albums you havent heard
author: rlburns
layout: post
permalink: /2011/10/the-albums-you-havent-heard/
categories:
  - Uncategorized
---
When I began falling down the rabbit hole of weird, experimental music in 2007, I was quickly surprised at how many widely-known artists had ventured into this territory. Ranging from drone to noise, and ambient to freak folk, these artists have exposed popular audiences to music they would probably not ordinarily hear. I'm still often taken aback when I realize that many of these albums simply escaped most people. Without speculating too much on why this happens, here's a list of albums released by widely-known bands, but that break from their popular music to experiment a little. They're not ranked in any way. Let me know if you have any additions!

1. Bjork - Drawing Restraint 9
2. Sonic Youth - the SYR series (SYR 1: Anagrama, SYR 2: Slaapkamers Met Slagroom, SYR 3: Invito Al Cielo, SYR 4: Goodbye Twentieth Century, SYR 5: Musical Perspective, SYR 6: Koncertas Stan Brakhage Prisiminimui)
3. Phish - The Siket Disc
4. Miles Davis - In a Silent Way
5. Aphex Twin - Selected Ambient Works ('85-'92 & Volume 2)
6. The Velvet Underground - White Light/White Heat (OK, this one is a huge stretch, but it still requires a patient ear to fully appreciate)
7. John Lennon & Yoko Ono - The Wedding Album
8. The Flaming Lips - Zaireeka
9. Yves Klein - Monotone Symphony (He was an artist, not a musician, but still was an interesting musical intervention)


text:
---
layout: default
---

# 1996-01-24 - Re: The Collapse of Ideas in a Pop Culture

## Header Data

From: jim bell<EMAIL_ADDRESS>To: Simon Spero<EMAIL_ADDRESS>Message Hash: 8c385fc62a248fb24d03b105a57c81a6a082c388d0685d22b81006a09819d08d

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1996-01-24 04:26:54 UTC

Raw Date: Wed, 24 Jan 1996 12:26:54 +0800

## Raw message

```
{% raw  %}From: jim bell<EMAIL_ADDRESS>Date: Wed, 24 Jan 1996 12:26:54 +0800
To: Simon Spero<EMAIL_ADDRESS>Subject: Re: The Collapse of Ideas in a Pop Culture
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

At 10:50 AM 1/23/96 -0800, Simon Spero wrote:
>On Tue, 23 Jan 1996, Scott Staedeli wrote:
>
>>
>>    I _am_ a GEnXer, and I worshipped Jules Bergmann as a child. Some
>> of my first memories is pressing my nose up to the tv, watching Saturn
>> V's lifting off. If I ever win the lottery, I'm going to take the Saturn
that's
>
>Bollocks. If you can remember Saturn Vs taking off before reruns, you're
>too old!
>
>Simon (27th July 1969, nearly called Neil)

In 1975, I lived in a small suburb of Kansas City, and went with my
grandfather from Kansas City Airport on a chartered Boeing 747 to see the
Apollo part of the Apollo/Soyuz rocket "blast off". (the whole thing was
arranged my a local group of bigwigs, I think.)  ( I think it was a Saturn
V, but correct me if
I'm wrong.  I was young and impressionable.) First and last large rocket I
saw go in person; I was sincerely impressed; it was extremely LOUD and we
were kept MILES away on a grandstand.  (But we were the closest you could
get, as I understand it, as we were invited guests of the whole thing.)

Incidentally, flying on the same airplane from Kansas City were:

1.  Susan Ford, daughter of President Gerald Ford.
2.  Dr. Werner Von Braun.

ob crypto:  Uh, none, sorry.

{% endraw %}
```

## Thread

+ Return to [January 1996](/archive/1996/01)

+ Return to "[jim bell <jimbell@pacifier.com>](/authors/jim_bell_jimbell_at_pacifier_com_)"

+ 1996-01-24 (Wed, 24 Jan 1996 12:26:54 +0800) - Re: The Collapse of Ideas in a Pop Culture - _jim bell<EMAIL_ADDRESS>


text:
RailsCasts Theme
================

Port from original [Railscasts TextMate theme](http://railscasts.com/about).

Screenshots
-----------

![](https://raw.github.com/formaweb/railscasts-atom-theme/master/screenshots/preview.png)

Tips
----

You can download [Bitstream Vera Sans Mono](http://www.dafont.com/bitstream-vera-mono.font) font to get a perfect combination!

repository: formaweb/railscasts-atom-theme

repo_name: formaweb/railscasts-atom-theme


text:
# Signatures

> Request header sample is in JSON

```
Signature = url_encode(access_url+endpoint)

{
    "Authorization": "<ACCESS_TOKEN>",
    "Timestamp": "1361281946",
    "Nonce": "634968823463411609",
    "Signature": "2cFwCfkgRR7mlIOlcjTQXCUYpLmtlKJkCb8RUzIX0-k=",
    "SignatureMethod": "SHA-256"
}
```

Signature ciphers have to be generated before a request is sent. They are included in your request headers and act as a check for all requests sent to the API.

All signatures must be hashed in base64 before they are sent. The hashing method presented here will be used to hash the string combination which will also be encoded in base64 before it is sent.

Different purchase requests have different signature contents. The signatures themselves are ***Base64*** encoded versions of the encrypted string combinations in the hashing method of your choice.

As you'd notice from the request header on the right tab, the ***Signature*** contains a hash along with its ***Signature Method***.

The data for which the signature can be generated from for different requests is illustrated below. The http method for the request is one of either ***POST, GET etc.***

The ***url*** is the encoded url version of the access url and the endpoint used. An example is stated here for any request.

***https://{ACCESS_URL}/{WHATEVER_ENDPOINT_YOU_CHOOSE}***

You can check for the access url for testing and production [here](#endpoints)

## Basic Purchase Request

> Code Samples

```
signatureCipher = httpMethod + “&”+ url + “&” +timestamp + “&” + nonce + “&” + clientId + “&” + clientSecret + “&” + amount + “&” + authdata
```

The signature can be generated from the ***Base64*** encoding of the cipher on the right.

## OTP Validation Request

> Code Samples

```
signatureCipher = httpMethod + “&”+ url + “&” +timestamp + “&” + nonce + “&” + clientId + “&” + clientSecret + “&” + otp + “&” + authdata
```

The signature can be generated from the ***Base64*** encoding of the cipher on the right.

## Transaction Validation Request (VISA)

 > Code Samples

 ```
signatureCipher = httpMethod + “&”+ url + “&” +timestamp + “&” + nonce + “&” + clientId + “&” + clientSecret
 ```

 The signature can be generated from the ***Base64*** encoding of the cipher on the right.

## Card Enrollment Request

> Code Samples

```
signatureCipher = httpMethod + “&”+ url + “&” +timestamp + “&” + nonce + “&” + clientId + “&” + clientSecret
```

The signature can be generated from the ***Base64*** encoding of the cipher on the right.

repository: ayodejiAgboola/isw-docs-demo

repo_name: ayodejiAgboola/isw-docs-demo


text:
# LET Language part 2

## Quiz
### 1
With the grammer:
```
<BTree> ::= <number>
         |  (<BTree> <BTree>)
```
Write the derivation to show `(2 (3 4))` is a `BTree`.

**Answer**
```
Rule 1: <BTree> -> <number>
Rule 2: <BTree> -> (<BTree> <BTree>)
Rule 3: <number> -> a number
<BTree>
    Rule 2
(<BTree> <BTree>)
    Rule 1
(<number> <BTree>)
    Rule 3
(2 <BTree>)
    Rule 2
(2 (<BTree> <BTree>))
    Rule 1
(2 (<number> <BTree>))
    Rule 3
(2 (3 <BTree>))
    Rule 1
(2 (3 <number>))
    Rule 3
(2 (3 4))
```

### 2
We have the following encoding:
```racket
(define-datatype BTree BTree?
    (leaf-t
        (data number?))
    (node-t
        (left BTree?)
        (right BTree?)))
```

#### a
Write function `isNode` that returns true unless the tree is a leaf.

**Answer**
```racket
(define (isNode bt)
    (cases bt
        (leaf-t (n) #f)
        (node-t (lt rt) #t)))
```

#### b
Write `prettyPrint` that takes a tree and prints it out like `(2 (3 4))`
You can use `(number->string n)` and `(string-append str [str str ...])` functions.

**Answer:**
```racket
(define (prettyPrint bt)
    (cases bt
        (leaf-t (n)
            (number->string n))
        (node-t (lt rt)
            (string-append
                "("
                (prettyPrint lt)
                " "
                (prettyPrint rt)
                ")"))))
```

## Lecture
**So far:** we have a concrete and abstract syntax for ==The LET Language==.


text:
# ModArchive Batch Downloader

A simple command-line Python 3 script for downloading groups of modules from ModArchive.org. Original idea based on [this PHP script](http://pastebin.com/ygYukDUq).

repository: vincmg/ModArchive-Batch-Downloader

repo_name: vincmg/ModArchive-Batch-Downloader


text:
## What is it?

1. A simple stack-based virtual machine that runs C in the browser.

2. An interactive tutorial that covers C, how the VM works, and how the language is compiled, everything from the ground up.

![alt text](/gif/both.gif)

## Why?

7 years ago I was writing my very first line of code.

I knew I liked programming, but I didn't really know what I was doing.
What's going on?
Why do I have to write this?
What's happening under the hood?
I was frustrated and confused.
I've always hated learning things by heart without really understanding them.

For years I had wished someone could break programming down and teach it from the groud up, concepts first, details later.
If someone could answer my "why?" questions, everything would be much easier to learn.

With this project, I want to teach programming one step at a time, from the very ground up.

And no, it's not going to take forever.
I am not covering unnecessary details, those are easy to look up.

## Can I see it?

1. [Sandbox](https://vasyop.github.io/miniC-hosting)

2. Tutorial (for people with 0 programming experience or willing to learn C) :
    * [Part 1](https://vasyop.github.io/miniC-hosting/?0) - Introduction
    * [Part 2](https://vasyop.github.io/miniC-hosting/?1) - Expressions (part 1)
    * [Part 3](https://vasyop.github.io/miniC-hosting/?2) - Expressions (part 2)
    * [Part 4](https://vasyop.github.io/miniC-hosting/?3) - Variables and program structure

## Subscribe

Get [notified](https://github.us20.list-manage.com/subscribe/post?u=2790571880963241ec5dd7d11&id=0e2d1b34de) when new tutorials are released.

## Feedback

Join the discussion on our [subreddit](https://www.reddit.com/r/minic/).

## Support
Consider [supporting](https://github.com/vasyop/miniC-hosting/blob/master/support.md) the project.

## Documentation

### Virtual Instruction Set

### Missing language features

* only bool, int, char and pointers as data types and they all have the same size in memory

* no malloc, but operator new is working (like in C++),

* no static arrays and structs (dynamic arrays and pointer to structs work fine).

* no arrays of structs (arrays of pointers to structs works fine).

* no for and switch statements

* no preprocessor directives

* no bitwise operators

* no ++, --, ternary operators

* no union and no enum

* no global variables

* no function pointers

* no free / delete operator

* no function overloading

repository: aircom-inc/miniC-hosting

repo_name: aircom-inc/miniC-hosting


text:
## Explore Intel® Edge Insights Software
### What is Intel® Edge Insights Software
Industrial Edge Insights Software (EIS) from Intel is a scalable solution for the industrial sector addressing various manufacturing usages which include data collection, storage and analytics on a variety of hardware nodes that span across the factory floor.
### How Industrial Edge Insights Software Works
To understand how it works, let's first understand key components of this software.

**Configuration File (factory_pcbdemo.json)**
This file is the main configuration file for the entire work stream. It uses a standard JSON format. Using this file, a user can define the data ingestion, storage, triggers, and classifiers.

*Location:*~/IEdgeInsights/docker_setup/config/factory_pcbdemo.json

**Video Ingestion**
The Video Ingestion module in the EIS is a user defined function, which uses the Data Ingestion library to ingest data to InfluxDB and Image store

![](images/VideoIngestion.png)

*Location:*~/IEdgeInsights /VideoIngestion/

**Trigger**
This filters the incoming data stream, mainly to reduce the storage and computation requirements by only passing on frames of interest. All input frames are passed to the Trigger.  When it detects a frame of interest based on user defined functions, it activates a signal which causes that frame to be saved in the Image Store database, and the metadata for that frame in the InfluxDB database.

*Location:*~/IEdgeInsights /algos/dpm/triggers/

**Classifier**
The is a user defined algorithm that is run on each frame of interest. Kapacitor, an open source data processing engine, subscribes to the meta-data stream , and the classifier receives the meta-data from Kapacitor. The classifier pulls the frame from the Image Store, and saves the analysis results as metadata back into the InfluxDB database.

*Location:*~/IEdgeInsights /algos/dpm/classification/classifiers/

**visualizer**
      This is to view resulting output

*Location:*~/IEdgeInsights /tools/visualizer/

***By now we understood the components, Let's understand how data flows between these components.***

![](images/eis-overview.png)

**Step-1.a:**
The Video Ingestion module starts capturing frames from Basler camera /
RTSP camera (or video file) and sends the frames to the Trigger Algorithm.

**Step-1.b:**
The Trigger Algorithm will determine the relevant frames that are to go to
the Classifier. In the PCB demo use case, the Trigger Algorithm selects the images with the full PCB within view and send relavant frames to teh Video Ingestion.

**Step-2:**
The relevant frames from the Trigger Algorithm are stored into Image Store and the corresponding meta-data is stored in InfluxDB

**Step-3:**
Kapacitor subscribes to the Meta Data stream. All the streams in InfluxDB are subscribed as default by Kapacitor.

**Step-4:**
The Classifier UDF (User Defined Function) receives the Meta Data from Kapacitor. It then invokes the UDF classifier algorithm.

**Step-5:**
UDF Classifier Algorithm fetches the image frame from the Image Store and
generates the Classified Results with defect information, if any. Each frame
produces one set of Classified Results.

**Step-6:**
The Classifier UDF returns the classified results to Kapacitor.

**Step-7:**
The Kapacitor saves the Classified Results to InfluxDB. This behavior is enforced in the Kapacitor TICK script.

**Step-8:**
The Classified Results are received by Factory Control Application.

**Step-9:**
The Factory Control Application will turn on the alarm light if a defect is found in the part.

**Step-10:**
The Stream Manager subscribes to the Classified Results stream. The policy of stream export is set in the Stream Manager.

**Step-11:**
The Stream Manager uses the Data Bus Abstraction module interfaces to publish the Classified Results stream. The Data Bus Abstraction provides a publish-subscribe interface.

**Step-12:**
Data Bus Abstraction creates an OPC-UA Server, which exposes the Classified Results data as a string.

**Step-13:**
The Classified result is published in the OPC-UA message bus and available to external applications

**Step-14:**
The image handle of the actual frame is part of the Classified Results. The raw image can be retrieved through the data agent using the GetBlob() API.

**Step-15:**
The raw image frame is returned in response to the GetBlob() command.

**NOTE:** As an application developer, you do not need to worry about handling the data flow described above from data ingestion to classification. The included software stack using InfluxDB and Kapacitor handle the data movement and storage.

### Running Defect detection demo application
**Description**
Printed Circuits Boards(PCBs) are being inspected for quality control to check if any defects(missing component or components are short) are there with the PCBs. To find out the defects a good quality PCB will be compared against the defective ones and pin point the location of the defect as well.

Input to the application can be from a live stream or from a video file. Here video file (~/IEdgeinsights/docker_setup/test_videos/pcb_d2000.avi) is used for this demo.

**Build and Run Sample.**
To **build** the sample pcbdemo sample application execute the following commands.

```bash
cd ~/IEdgeinsights/tools/visualizer/
sudo make build
```

To **run** the sample application , execute the below command:

```bash
sudo make run CERT_PATH=${iei_install_dir}/cert-tool/Certificates/ HOST=localhost IMAGE_DIR=/opt/intel/iei/saved_images DISPLAY_IMG=true
```
**Pcb-Demo Output**
Once the application successfully runs. The output window will be poped up as below.
![](images/pcbdemo_result.png)

Now we understood the Intel® Edge Insights Software framework components and run pcbdemo application successfully.
Let's Deploy a Restricted Zone Notifier Reference implementation using Intel® Edge Insights Software framework in our next lab.

## Next Lab
[Deploying Restricted Zone Notifier using Edge Insights Software framework](./lab_restricted_zone_notifier.md)

repository: patrabax/Industrial-IoT-Workshop

repo_name: patrabax/Industrial-IoT-Workshop


text:
# Wonnet

A bash script to connect to wireless network via a CLI, for shell lovers. The output of "wonnet-development.sh" show processes that are happening in the script, instead "wonnet-client.sh" don't show a lot of this processes. This is the only difference.

## Test

* Download the repository
* Go to project directory
* On your terminal, run:

```sh
./wonnet-development.sh
```

* Let me know if you have any errors or problems

## Meta

Leopoldo Brines - [@leopoldobrines7](https://twitter.com/leopoldobrines7) -<EMAIL_ADDRESS>
Distributed under the MIT license.

repository: leobrines/wonnet

repo_name: leobrines/wonnet


text:
The Jupyter Notebooks in this directory are for planning and gathering the relevant plots and evidence to answer to the reviewers of Paper 1.
The links below are to static renderings of the notebooks via
[nbviewer.jupyter.org](http://nbviewer.jupyter.org/).
* ##[Non_dim_number_calculator.ipynb](http://nbviewer.jupyter.org/urls/bitbucket.org/canyonsubc/outputanalysisnotebooks/raw/tip/RevisionsPaper1/Non_dim_number_calculator.ipynb)

##License

These notebooks and files are copyright 2013-2018
by the UBC Canyons Contributors
and The University of British Columbia.

They are licensed under the Apache License, Version 2.0.
http://www.apache.org/licenses/LICENSE-2.0
Please see the LICENSE file for details of the license.

repository: UBC-MOAD/outputanalysisnotebooks

repo_name: UBC-MOAD/outputanalysisnotebooks


text:
# Pushbullet-PowerShell-Module

You may enter your Pushbullet API key at the top of the script or enter it manually each time.

This PowerShell module can be used to send notifications to any of your devices using the Pushbullet service. It includes three functions:

    Send-Pushbullet
    Get-PushbulletDevices
    Get-PushbulletChats

It can be used as part of scripts to send notifications of events:

    PS> Import-Module .\Pushbullet.psm1
    PS> Send-Pushbullet -APIKey "XXXXXX" -Title "Process Report" -Message "There are $(Get-Process | Measure | Select -ExpandProperty Count) processes running."

Result:

![](sample.jpg)

gha_language: PowerShell


text:
### An implementation of the DOM in CoffeeScript/JavaScript

Intended for use in NodeJS.

I haven't checked the actual DOM compliance, but everything you need is there:

* Full CSS3 support via [NWMatcher](https://github.com/dperini/nwmatcher/).
* A very tiny HTML parser.
* DOM-compliant event binding and triggering (bubbling, cancelling, etc).
* Coming soon: (optional) Mutation Events.

This is not a fork of [jsdom](https://github.com/tmpvar/jsdom).

It assumes the document is going to act like it would in a browser (e.g. it automatically gets a head and body).

No attempt has been made to support XML or Xpath or anything exotic.

Example:

	document = require('jldom').createDocument()

	document.body.innerHTML = "
Hello, World.
"

	document.toString()
		=== "
Hello, World.
"

	document.querySelector("div").toString()
		=== "
Hello, World.
"

I built this to generate server-side HTML from a NodeJS application. Benchmarks reveal that this is a waste of time.
I currently use it to unit test other javascript code that needs a reasonably well-behaved DOM to interact with.

Install:

	npm install jldom

Or:

	git clone git://github.com/jldailey/jldom.git
	cd jldom
	make

repository: jldailey/jldom

repo_name: jldailey/jldom


text:
# Stictis hypophylla Sherwood SPECIES

#### Status
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 6(2): 252 (1977)

#### Original name
Stictis hypophylla Sherwood

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone


text:
PHPUnitArrayAssertions
======================

[![MIT license](https://raw.githubusercontent.com/PhrozenByte/phpunit-array-asserts/master/.github/license.svg)](https://github.com/PhrozenByte/phpunit-array-asserts/blob/master/LICENSE)
[![Code coverage](https://raw.githubusercontent.com/PhrozenByte/phpunit-array-asserts/master/.github/coverage.svg)](https://github.com/PhrozenByte/phpunit-array-asserts)

[`PHPUnitArrayAssertions`](https://github.com/PhrozenByte/phpunit-array-asserts) is a small [PHPUnit](https://phpunit.de/) extension to improve testing of PHP arrays and array-like data. It introduces the [`AssociativeArray`](#constraint-associativearray), [`ArrayHasKeyWith`](#constraint-arrayhaskeywith), [`SequentialArray`](#constraint-sequentialarray), and [`ArrayHasItemWith`](#constraint-arrayhasitemwith) constraints. It is often used for API testing to assert whether an API result matches certain criteria - regarding both its structure, and the data.

This PHPUnit extension allows developers to test structure and data in single assertion, making test cases less repetitive and easier to understand. In some way it's an alternative to PHPUnit's `ArraySubset` constraint that was deprecated in PHPUnit 8 and removed in PHPUnit 9 - just way more powerful and less confusing. Refer to the ["Usage" section](#usage) and ["Example" section](#example) below for more info.

You want more PHPUnit constraints? Check out [`PHPUnitThrowableAssertions`](https://github.com/PhrozenByte/phpunit-throwable-asserts)! It introduces the `assertCallableThrows()` and `assertCallableThrowsNot()` assertions to improve testing of exceptions and PHP errors. It's more powerful and flexible than PHPUnit's core `expectException()` method.

Made with :heart: by [Daniel Rudolf](https://www.daniel-rudolf.de). `PHPUnitArrayAssertions` is free and open source software, released under the terms of the [MIT license](https://github.com/PhrozenByte/phpunit-array-asserts/blob/master/LICENSE).

**Table of contents:**

1. [Install](#install)
2. [Usage](#usage)
    1. [Constraint `AssociativeArray`](#constraint-associativearray)
    2. [Constraint `ArrayHasKeyWith`](#constraint-arrayhaskeywith)
    3. [Constraint `SequentialArray`](#constraint-sequentialarray)
    4. [Constraint `ArrayHasItemWith`](#constraint-arrayhasitemwith)
3. [Example](#example)

Install
-------

`PHPUnitArrayAssertions` is available on [Packagist.org](https://packagist.org/packages/phrozenbyte/phpunit-array-asserts) and can be installed using [Composer](https://getcomposer.org/):

```shell
composer require --dev phrozenbyte/phpunit-array-asserts
```

This PHPUnit extension was initially written for PHPUnit 8, but should work fine with any later PHPUnit version. If it doesn't, please don't hesitate to open a [new Issue on GitHub](https://github.com/PhrozenByte/phpunit-array-asserts/issues/new), or, even better, create a Pull Request with a proposed fix.

Usage
-----

There are three (basically equivalent) options to use `PHPUnitArrayAssertions`:

- By using the static [class `PhrozenByte\PHPUnitArrayAsserts\Assert`](https://github.com/PhrozenByte/phpunit-array-asserts/blob/master/src/Assert.php)
- By using the [trait `PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait`](https://github.com/PhrozenByte/phpunit-array-asserts/blob/master/src/ArrayAssertsTrait.php) in your test case
- By creating new [constraint instances](https://github.com/PhrozenByte/phpunit-array-asserts/tree/master/src/Constraint) (`PhrozenByte\PHPUnitArrayAsserts\Constraint\…`)

All options do the same, the only difference is that the static class and trait both throw `PHPUnit\Framework\InvalidArgumentException` exceptions for invalid parameters. Creating new constraint instances is useful for advanced assertions, e.g. together with `PHPUnit\Framework\Constraint\LogicalAnd`.

### Constraint `AssociativeArray`

The [`AssociativeArray` constraint](https://github.com/PhrozenByte/phpunit-array-asserts/blob/master/src/Constraint/AssociativeArray.php) asserts that a value is an associative array matching a given structure and that the array's items pass other constraints.

Any native array and `ArrayAccess` object is considered an associative array, no matter which keys they use. However, the array's items are applied to the matching constraint (parameter `$consotraints`). By default, missing items will fail the constraint (parameter `$allowMissing`, defaults to `false`). Additional items will be ignored by default (parameter `$allowAdditional`, defaults to `true`). If you want the constraint to fail when additional items exist, set this option to `true`, however, please note that this works for native arrays only. The expected keys and constraints to apply, as well as whether missing and/or additional items should fail the constraint, are passed in the constructor. Constraints can either be arbitrary `Constraint` instances (e.g. `PHPUnit\Framework\Constraint\StringContains`), or any static value, requiring exact matches of the values.

The `ArrayAssertsTrait` trait exposes two public methods for the `AssociativeArray` constraint: Use `ArrayAssertsTrait::assertAssociativeArray()` to perform an assertion, and `ArrayAssertsTrait::associativeArray()` to create a new instance of the `AssociativeArray` constraint.

**Usage:**

```php
// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait
ArrayAssertsTrait::assertAssociativeArray(
    array $constraints,            // an array with the expected keys and constraints to apply
    array|ArrayAccess $array,      // the associative array to check
    bool $allowMissing = false,    // whether missing items fail the constraint
    bool $allowAdditional = true,  // whether additional items fail the constraint
    string $message = ''           // additional information about the test
);

// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\AssociativeArray`
new AssociativeArray(
    array $constraints,
    bool $allowMissing = false,
    bool $allowAdditional = true
);
```

**Example:**

```php
$data = [
    'id'      => 42,
    'name'    => 'Arthur Dent',
    'options' => [ 'has_towel' => true, 'panic' => false ],
];

// asserts that `$data` is an associative array with exactly the keys:
//     - "id" with a numeric value,
//     - "name" with the value "Arthur Dent", and
//     - "options" with another associative array with the key "panic", whose value must be a boolean
$this->assertAssociativeArray([
    'id'      => $this->isType(IsType::TYPE_INT),
    'name'    => 'Arthur Dent',
    'options' => $this->associativeArray([ 'panic' => $this->isType(IsType::TYPE_BOOL) ], true)
], $data);
```

**Debugging:**

```php
$data = [
    'answer' => 21 /* half the truth */
];

$this->assertAssociativeArray([
    'answer' => 42
], $data);

// Will fail with the following message:
//
//     Failed asserting that associative array matches constraints.
//     +----------+-------+----------------------+
//     | Key      | Value | Constraint           |
//     +----------+-------+----------------------+
//     | 'answer' | 21    | Value is equal to 42 |
//     +----------+-------+----------------------+
//     [ ] Allow missing; [x] Allow additional
```

### Constraint `ArrayHasKeyWith`

The [`ArrayHasKeyWith` constraint](https://github.com/PhrozenByte/phpunit-array-asserts/blob/master/src/Constraint/ArrayHasKeyWith.php) asserts that an array has a given key and that its value passes another constraint.

Accepts both native arrays and `ArrayAccess` objects. The constraint (parameter `$constraint`) will fail if the key (parameter `$key`) doesn't exist in the array. The item's key, and the constraint the value must pass are passed in the constructor. The constraint can either be an arbitrary `Constraint` instance (e.g. `PHPUnit\Framework\Constraint\StringContains`), or any static value, requiring an exact match of the value.

The `ArrayAssertsTrait` trait exposes two public methods for the `ArrayHasKeyWith` constraint: Use `ArrayAssertsTrait::assertArrayHasKeyWith()` to perform an assertion, and `ArrayAssertsTrait::arrayHasKeyWith()` to create a new instance of the `ArrayHasKeyWith` constraint.

**Usage:**

```php
// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait
ArrayAssertsTrait::assertArrayHasKeyWith(
    string|int $key,              // the key of the item to check
    Constraint|mixed $constraint, // the constraint the item's value is applied to
    array|ArrayAccess $array,     // the array to check
    string $message = ''          // additional information about the test
);

// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\ArrayHasKeyWith`
new ArrayHasKeyWith(
    string|int $key,
    Constraint|mixed $constraint
);
```

**Example:**

```php
$data = [
    'id'      => 42,
    'name'    => 'Arthur Dent',
    'options' => [ 'has_towel' => true, 'panic' => false ],
];

// asserts that $data has the item `name` with the value "Arthur Dent"
$this->assertArrayHasKeyWith('name', 'Arthur Dent', $data);
```

**Debugging:**

```php
$data = [];

$this->assertArrayHasKeyWith('answer', 42, $data);

// Will fail with the following message:
//
//     Failed asserting that Array &0 () is an array that
//     has the key 'answer' whose value is equal to 42.
```

### Constraint `SequentialArray`

The [`SequentialArray` constraint](https://github.com/PhrozenByte/phpunit-array-asserts/blob/master/src/Constraint/SequentialArray.php) asserts that a value is like a sequential array, has a minimum and/or maximum number of items, and that all items pass another constraint.

Sequential arrays are defined as ordered lists with incrementing numeric keys starting from zero. This is especially true for native sequential arrays like `[ "foo", "bar" ]`. Empty arrays are considered valid, too. `Traversable` objects must have sequential keys to be considered valid. The expected minimum (parameter `$minItems`, defaults to `0`) and/or maximum (parameter `$maxItems`, defaults to `null`, meaning infinite) number of items, and the constraint to apply all items to (optional parameter `$constraint`), are passed in the constructor. The constraint can either be an arbitrary `Constraint` instance (e.g. `PHPUnit\Framework\Constraint\StringContains`), or any static value, requiring an exact match of the value. Requiring sequential keys can be disabled by setting parameter `$ignoreKeys` to `true` (defaults to `false`), causing the constraint to check just for the required number of items and whether they match the given constraint.

This constraint will fully traverse any `Traversable` object given. It expects `Traversable`s to be rewindable. For `NoRewindIterator` instances it assumes that the iterator is still in its initial state. `Generator`s will be fully exhausted; if the iterator has begun already, the object is considered invalid. If an `Iterator` is given, it will try to restore the object's pointer to its previous state. This will silently fail for `NoRewindIterator` instances. The behaviour for `Iterator`s with non-unique keys is undefined.

The `ArrayAssertsTrait` trait exposes two public methods for the `SequentialArray` constraint: Use `ArrayAssertsTrait::assertSequentialArray()` to perform an assertion, and `ArrayAssertsTrait::sequentialArray()` to create a new instance of the `SequentialArray` constraint.

**Usage:**

```php
// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait
ArrayAssertsTrait::assertSequentialArray(
    array|Traversable $array,            // the sequential array to check
    int $minItems,                       // required minimum number of items
    int $maxItems = null,                // required maximum number of items (pass null for infinite)
    Constraint|mixed $constraint = null, // optional constraint to apply all items to
    bool $ignoreKeys = false,            // whether to ignore non-sequential keys
    string $message = ''                 // additional information about the test
);

// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\SequentialArray`
new SequentialArray(
    int $minItems = 0,
    int $maxItems = null,
    Constraint|mixed $constraint = null,
    bool $ignoreKeys = false
);
```

**Example:**

```php
$data = [
    "The Hitchhiker's Guide to the Galaxy",
    "The Restaurant at the End of the Universe",
    "Life, the Universe and Everything",
    "So Long, and Thanks for All the Fish",
    "Mostly Harmless",
    "And Another Thing...",
];

// asserts that `$data` is a non-empty sequential array with non-empty items
$this->assertSequentialArray($data, 1, null, $this->logicalNot($this->isEmpty()));
```

**Debugging:**

```php
$data = [];

$this->assertSequentialArray($data, 4, null, $this->is(IsType::TYPE_STRING));

// Will fail with the following message:
//
//     Failed asserting that Array &0 () is is a sequential array
//     with ≥ 4 items matching the constraint "is of type "string"".
```

### Constraint `ArrayHasItemWith`

The [`ArrayHasItemWith` constraint](https://github.com/PhrozenByte/phpunit-array-asserts/blob/master/src/Constraint/ArrayHasItemWith.php) asserts that an array has a item at a given index and that its value passes another constraint.

Accepts both native arrays and `Traversable` objects. The constraint will fail if the array has less items than required. The index of the item to check (parameter `$index`), and the constraint its value must pass (parameter `$constraint`) are passed in the constructor. The constraint can either be an arbitrary `Constraint` instance (e.g. `PHPUnit\Framework\Constraint\StringContains`), or any static value, requiring an exact match of the value.

This constraint will fully traverse any `Traversable` object given. It expects `Traversable`s to be rewindable. For `NoRewindIterator` instances it assumes that the iterator is still in its initial state. `Generator`s will be fully exhausted; if the iterator has begun already, the object is considered invalid. If an `Iterator` is given, it will try to restore the object's pointer to its previous state. This will silently fail for `NoRewindIterator` instances. The behaviour for `Iterator`s with non-unique keys is undefined.

The `ArrayAssertsTrait` trait exposes two public methods for the `ArrayHasItemWith` constraint: Use `ArrayAssertsTrait::assertArrayHasItemWith()` to perform an assertion, and `ArrayAssertsTrait::arrayHasItemWith()` to create a new instance of the `ArrayHasItemWith` constraint.

**Usage:**

```php
// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait
ArrayAssertsTrait::assertArrayHasItemWith(
    int $index,                   // the index of the item to check
    Constraint|mixed $constraint, // the constraint the item's value is applied to
    array|Traversable $array,     // the array to check
    string $message = ''          // additional information about the test
);

// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\ArrayHasItemWith`
new ArrayHasItemWith(
    int $index,
    Constraint|mixed $constraint
);
```

**Example:**

```php
$data = [
    '1979-10-12' => "The Hitchhiker's Guide to the Galaxy",
    '1980-10-00' => "The Restaurant at the End of the Universe",
    '1982-08-00' => "Life, the Universe and Everything",
    '1984-11-09' => "So Long, and Thanks for All the Fish",
    '1992-00-00' => "Mostly Harmless",
    '2009-10-12' => "And Another Thing...",
];

// asserts that `$data` contains "Life, the Universe and Everything" as third item (i.e. at index 2)
$this->assertArrayHasItemWith(2, "Life, the Universe and Everything");
```

**Debugging:**

```php
$data = [];

$this->assertArrayHasItemWith(2, 'Arthur Dent', $data);

// Will fail with the following message:
//
//     Failed asserting that Array &0 () is an array that
//     has a value at index 2 which is equal to 'Arthur Dent'.
```

Example
-------

Here's a (more or less) real-world example of `PHPUnitArrayAssertions`. Check out the `testWithPHPUnitArrayAsserts()` method to see how a complex API response is tested. For a comparison with an implementation utilizing just PHPUnit's core features, check out the `testWithoutPHPUnitArrayAsserts()` method. Without `PHPUnitArrayAssertions` you end up having 17 lines of pretty repetitive code, with this PHPUnit extension you can test the response with 7 lines of easy to understand code.

```php
<?php
declare(strict_types=1);

namespace YourName\YourProject\Tests;

use PHPUnit\Framework\Constraint\IsType;
use PHPUnit\Framework\TestCase;
use PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait;

class MyTest extends TestCase
{
    use ArrayAssertsTrait;

    public function testWithPHPUnitArrayAsserts(): void
    {
        // 7 lines of easy to understand code to check the API response *with* PHPUnitArrayAsserts

        // implement your test, the result is stored in $responseData

        $responseData = [
            'users' => [
                [
                    'id'      => 42,
                    'name'    => 'Arthur Dent',
                    'options' => [ 'has_towel' => true, 'panic' => false ],
                ],
            ]
        ];

        $this->assertArrayHasKeyWith('users', $this->sequentialArray(1), $responseData);

        $this->assertAssociativeArray([
            'id'      => $this->isType(IsType::TYPE_INT),
            'name'    => 'Arthur Dent',
            'options' => $this->associativeArray([ 'panic' => $this->isType(IsType::TYPE_BOOL) ])
        ], $responseData['users'][0]);
    }

    public function testWithoutPHPUnitArrayAsserts(): void
    {
        // 17 lines of pretty repetitive code to check the API response *without* PHPUnitArrayAsserts

        // implement your test, the result is stored in $responseData

        $responseData = [
            'users' => [
                [
                    'id'      => 42,
                    'name'    => 'Arthur Dent',
                    'options' => [ 'has_towel' => true, 'panic' => false ],
                ],
            ]
        ];

        $this->assertArrayHasKey('users', $responseData);
        $this->assertIsArray($responseData['users']);
        $this->assertGreaterThanOrEqual(1, count($responseData['users'])); // won't work for Traversable

        $userData = $responseData['users'][0]; // we can't really rely on the existence of key "0" here :/

        $this->assertArrayHasKey('id', $userData);
        $this->assertIsInt($userData['id']);

        $this->assertArrayHasKey('name', $userData);
        $this->assertSame('Arthur Dent', $userData['name']);

        $this->assertArrayHasKey('options', $userData);
        $this->assertIsArray($userData['options']);

        $this->assertArrayHasKey('panic', $userData['options']);
        $this->assertIsBool($userData['options']['panic']);
    }
}
```

repository: PhrozenByte/phpunit-array-asserts

repo_name: PhrozenByte/phpunit-array-asserts