text:
# \<RubberSlider/\>

![Example usage](https://user-images.githubusercontent.com/38357771/82850378-02b46c00-9eb1-11ea-9b7c-5f8334484f6e.gif)

## Installation

```shell
$ npm i @shwilliam/react-rubber-slider
$ npm i @reach/slider d3
```

## Usage

```jsx
import React, {useState} from 'react'
import RubberSlider from '@shwilliam/react-rubber-slider'
import<EMAIL_ADDRESS>
export const App = () => {
  const [value, setValue] = useState(0.5)

  return <RubberSlider width={250} value={value} onChange={setValue} />
}
```

[![@shwilliam/react-rubber-slider demo](https://codesandbox.io/static/img/play-codesandbox.svg)](https://codesandbox.io/s/gifted-shannon-qed9g?fontsize=14&hidenavigation=1&theme=dark)

## Development

To start local development, simply install npm dependencies (`npm i`) and run `npm run build:watch` to watch ts files in `src/`. Built files can be found in `dist/`.

## Demo

To run the demo, ensure you have run the build script and have a `dist` dir in your project root. Then run `npm run demo:setup` to copy these to the demo and `npm run demo` to start it locally.

## Contributing

This project is open to and encourages contributions! Feel free to discuss any bug fixes/features in the [issues](https://github.com/shwilliam/react-rubber-slider/issues). If you wish to work on this project:

1. Fork [this project](https://github.com/shwilliam/react-rubber-slider)
2. Create a branch (`git checkout -b new-branch`)
3. Commit your changes (`git commit -am 'add new feature'`)
4. Push to the branch (`git push origin new-branch`)
5. [Submit a pull request!](https://github.com/shwilliam/react-rubber-slider/pull/new/master)

repository: TrendingTechnology/react-rubber-slider

repo_name: TrendingTechnology/react-rubber-slider


text:
# Smart Basic Scripts for BL652

Here we present smart basic scripts which describe the operation of BL652 module. There are two scripts. Depending on positioning mode the relevant script is launhed.

## adscan.advert.display

This script runs in Remote positioning mode. it outputs advertisement reports to uart (including RSS reading).

## sAnchor

sAnchor runs in Self-positioning mode. It periodically sends advertisements which include Anchor identification.

## $autorun$

Runs in Tag0 type. It only transmits advertisement reports every 100 ms.

license: MIT

repository: Standa-R/BlePositioningSystem

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: Standa-R/BlePositioningSystem


text:
# pp_loc

Decent error reporting (for example, in a parser, a compiler, ...) typically
involves collecting *locations*, in order to indicate to the user the position
of an error in the source file.

This library provides support to additionally quote and highlight the input
fragment the input that corresponds to a location (or a set of locations).

This is the same code as in the OCaml compiler implementation (as of version
4.08), but extracted as a standalone library.

## Examples

Single-line errors: the offending line is printed back, and the error location
is highlighted using carets.

```
2 | let x = 1 + 1 +. 2 in ()
            ^^^^^
```

Multi-line error: the lines that span the location are printed, where the input
outside of the error location is replaced by ".".

```
2 | ......(1 + 1
3 |  * 3)...
```

## Documentation

https://armael.github.io/pp_loc/pp_loc/

gha_language: OCaml

gha_license_id: MIT


text:
[![Build Status](https://semaphoreci.com/api/v1/projects/c1127eeb-9c13-44dd-baeb-155ce4a54493/425379/badge.svg)](https://semaphoreci.com/fegoa89/date-manager)
# DateManager

Parse, validate, manipulate, and display dates.

# Start

DateManager is a gem for convert/parse/compare two strings into date a DateTime object and manipulate them .
For handle different dates format, I did this gem based on the most used formats in different countries (https://en.wikipedia.org/wiki/Date_format_by_country#Listing), from where I can divide it in three basic types :

- MDY - Month/Day/Year mm/dd/yyyy
- DMY - Day/Month/Year dd/mm/yyyy
- YMD - Year/Month/Day yyyy/mm/dd

# Using DateManager

Create an instance:

    $ @dates = DateManager.new('2012/02/02', '2012/02/03')

The standard string input is the YMD format .

You can set any other string input format (Like day - month - year) passing the date format as a third parameter like :

    $ @dates = DateManager.new('02/03/2015', '03/03/2015', 'DMY')

or

    $ @dates = DateManager.new('12/30/2015', '12/31/2015', 'MDY')

If the format is given as a DMY ( for example) and it does not contains a third parameter that indicates that the strings given are build on this format, the first date and the last date wont be possible to get set .
You can use a '.' , '-' or '/' as a component separator for separate the different components of the dates, it will be translated into '/'.

After a succesfull creation of an object, keep in mind the date range you are passing. The first date (first string given) should be older than the second date (second string given). If not it does not have sense (you can test it calling the method '#valid_date_range?' . The purpose of this gem is play between the dates of two dates :) )

# Methods

## start_date
Returns the start_date object :

    $ @dates = DateManager.new('02/03/2015', '03/03/2015', 'DMY')
    $ @dates.start_date
    $ #<DateTime: 2015-03-02T00:00:00+00:00 ((2457084j,0s,0n),+0s,2299161j)>

## finish_date
Returns the finish_date object :

    $ @dates = DateManager.new('02/03/2015', '03/03/2015', 'DMY')
    $ @dates.finish_date
    $ #<DateTime: 2015-03-03T00:00:00+00:00 ((2457085j,0s,0n),+0s,2299161j)>

## format
Returns the date format :

    $ @dates = DateManager.new('02/03/2015', '03/03/2015', 'DMY')
    $ @dates.format
    $ DMY

## valid_date_range?

Compares if the first string given is a date older than the second string given .

    $ @dates = DateManager.new('02/03/2015', '03/03/2015', 'DMY')
    $ @dates.valid_date_range?
    $ true

## days_between_dates

Gives back the quantity of days between these dates

    $ @dates = DateManager.new('02/03/2015', '03/03/2015', 'DMY')
    $ @dates.days_between_dates
    $ 1

## months_between_dates

Gives back the quantity of months between these dates

    $ @dates = DateManager.new('02/02/2015', '03/03/2015', 'DMY')
    $ @dates.months_between_dates
    $ 1

## years_between_dates

Gives back the quantity of years between these dates

    $ @dates = DateManager.new('03/03/2014', '03/03/2015', 'DMY')
    $ @dates.years_between_dates
    $ 1

## start_date_leap_year?

Returns true or false depending if the start_date object is a leap year or not
    $ @dates = DateManager.new('03/03/2014', '03/03/2015', 'DMY')
    $ @dates.start_date_leap_year?
    $ false

## finish_date_leap_year?

Returns true or false depending if the finish_date object is a leap year or not

Gives back the quantity of years between these dates

    $ @dates = DateManager.new('03/03/2014', '03/03/2016', 'DMY')
    $ @dates.finish_date_leap_year?
    $ true

## differences_between_dates

Returns a hash containing the quantity of years / months / days between the dates

    $ @dates = DateManager.new('03/03/2014', '03/03/2016', 'DMY')
    $ @dates.differences_between_dates
    $ {:years=>2, :months=>24, :days=>731}

## readable_days_between_dates(language = {})

Returns a string with quantity of days in between. Only Spanish and English are supported.

    $ @dates = DateManager.new('02/02/2015', '03/03/2015', 'DMY')
    $ @dates.readable_days_between_dates
    $ 29 days

## readable_months_between_dates(language = {})

Returns a string with the quantity of months in between. Only Spanish and English are supported.

    $ @dates = DateManager.new('02/02/2015', '03/04/2015', 'DMY')
    $ @dates.readable_months_between_dates
    $ 2 months

## human_readable_format

Returns a string with start_date and finish_date object in a human readable way that contains the day in a ordinal format. Only Spanish and English are supported.

    $ @dates = DateManager.new('2012/02/01', '2012/02/03')
    $ @dates.human_readable_format
    $ "First date : Wednesday, 1st of February 2012 - Second date : Friday, 3rd of February 2012"

## working_days

Return quantity of working days between dates

    $ @dates = DateManager.new('2012/02/01', '2012/02/03')
    $ @dates.working_days
    $ 3

## total_weekend_days

Return quantity of saturdays / sundays between dates

    $ @dates = DateManager.new('2015/01/30', '2015/02/13')
    $ @dates.total_weekend_days
    $ 4

# Installation

Add this line to your application's Gemfile:

    gem 'date_manager'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install date_manager

# Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
---
title: Ariadne 0.19
---

Ariadne 0.19 is now out!

Ariadne 0.19 is a feature release that brings improvements for GraphQL inputs and enums. It also includes improvements to the Apollo Federation implementation contributed by the community.

<!--truncate-->

## Input handling improvements

Ariadne now provides an `InputType` class which can be used to setup custom Python representation of GraphQL input types and mappings between input's fields and original Python directory with values:

```python
# Store input field's values under custom dict keys
InputType(
    "InputName",
    out_names={
        "isClosed": "is_closed",
        "isActive": "requires_activation",
    },
)
```

```python
@dataclass
class UserInput:
    name: str
    email: str
    requires_activation: Optional[bool] = None

InputType(
    "UserInput",
    # Logic for converting input's data to Python repr is customizable
    lambda data: UserInput(**data),
    {"isActive": "requires_activation"},
)
```

## Enum handling improvements

Ariadne already provides an `EnumType` class which can be used to assign custom Python values to GraphQL enums:

```python
class TaskPriority(enum.IntEnum):
    VERY_LOW = 0
    LOW = 1
    STANDARD = 2
    HIGH = 3
    URGENT = 4

EnumType("TaskPriority", TaskPriority)
```

`make_executable_schema` now accepts `Enum`s directly and attempts to associate them with their GraphQL counterparts on their name. In above case if there's already an enum in GraphQL schema named `TaskPriority`, `TaskPriority` can be passed to schema directly.

`EnumType` still remains useful in situations when enum's names are different between Python and GraphQL schema, and when enum's Python values are set using `dict`.

## Federation improvements

Our community has contributed few improvements to Ariadne's `contrib.federation` package, providing utilities for writing Apollo Federation subgraphs.

Thanks to Alexis Rhote's contributions, `make_federated_schema` now supports `convert_names_case` just like how `make_executable_schema` does.

Dan Lepadatu has contributed a support for `@interfaceObject` directive.

Dan Ring has contributed an improvements to Ariadne's federated schema processing logic, making it more tight and less error prone.

We would also like to give a shout out to Dariusz Kuc for keeping an eye on Ariadne's Federation support, and to Patrick Arminio for contributing template for federalable [Ariadne Fast API service](https://github.com/mirumee/subgraph-template-ariadne-fastapi).

## CHANGELOG

- Added `InputType` for setting Python representations of GraphQL Input types
- Added support for passing `Enum` types directly to `make_executable_schema`
- Added `convert_names_case` option to `make_federated_schema`.
- Added support for the `@interfaceObject` directive in Apollo Federation.
- Fixed federation support for directives without surrounding whitespace.

repository: mirumee/ariadne-website

gha_language: JavaScript

repo_name: mirumee/ariadne-website


text:
# atom-box

[![Latest Stable Version](https://poser.pugx.org/gaurav57/atom-box/v/stable)](https://packagist.org/packages/gaurav57/atom-box)
[![Total Downloads](https://poser.pugx.org/gaurav57/atom-box/downloads)](https://packagist.org/packages/gaurav57/atom-box)
[![Latest Unstable Version](https://poser.pugx.org/gaurav57/atom-box/v/unstable)](https://packagist.org/packages/gaurav57/atom-box)
[![License](https://poser.pugx.org/gaurav57/atom-box/license)](https://packagist.org/packages/gaurav57/atom-box)

A light and beautiful custom Popup without using bootstrap.

Note: Don't use it... It is currently in development phase.


text:
# musicbrainz-search-api

##Description
API to search for Artists and Releases from the MusicBrainz API.

##Tools/Technologies
- SQL Server 2016 (Developer Edition)
- Visual Studio 2015
- WebAPI
- Entity Framework
- Ninject (IoC)

##Notes
The application runs on IIS. I only used the built-in IIS server of Visual Studio to test my code.
I tried to separate the layers as much as I can. If I have more time, I would separate the API calls
to MusicBrainz to its own service layer, or even on a separate project, so it can be reusable.

Same as with my frontend assessment, I was not able to add unit tests to this project. I had to juggle
creation of this project, with my current work. :)

The SQL Server scripts are located in MusicBrainzArtistSearch/SQL/MusicBrainzArtistDB.sql. You can run
this in one go.

##Instructions

The API can pretty much do what was required in the documentation. It has the following endpoints:

>> /artist - returns all the artist currently stored in the database

>> /artist/search/search_criteria - returns all the artist stored in the database that matched the search string

>> /artist/search/search_criteria/page_number/page_size - returns all the artist stored in the database that matched the search string and applies pagination rule as required

>> /artist/artist_id/releases - requests information from MusicBrainz and returns all the releases of the specified artist (albums, singles, ep, compilation, etc)

>> /artist/artist_id/albums - requests information from MusicBrainz and returns only the album release of the specified artist


text:
---
layout: pub
type: inproceedings
title: Identifying Generic Noun Phrases
author:
- Nils Reiter
- Anette Frank
year: 2010
booktitle: Proceedings of the 48th Annual Meeting of the Association for Computational Linguistics
address: Uppsala, Sweden
publisher: Association for Computational Linguistics
pages: 40-49
month: July
lang: en
link: http://www.aclweb.org/anthology/P10-1005
downloads:
- desc: PDF
  url: http://www.aclweb.org/anthology/P10-1005.pdf
---

### Abstract

This paper presents a supervised approach for identifying generic noun phrases in context. Generic statements express rule-like knowledge about kinds or events. Therefore, their identification is important for the automatic construction of knowledge bases. In particular, the distinction between generic and non-generic statements is crucial for the correct encoding of generic and instance-level information. Generic expressions have been studied extensively in formal semantics. Building on this work, we explore a corpus-based learning approach for identifying generic NPs, using selections of linguistically motivated features. Our results perform well above the baseline and existing prior work.


text:
---
name: "\U0001F4AC Request For Comment (RFC)"
about: Feature discussion
title: ''
labels: rfc
assignees: ''

---

<!--- Provide a detailed summary of the issue here -->

## 🔦 Context

<!--- How has this issue affected you? What are you trying to accomplish? -->

<!--- Providing context helps us come up with a solution that is most useful in the real world -->

## 💻 Examples

<!-- Examples help us understand the requested feature better -->

repository: maplibre/mbtileserver-rs

branch_name: refs/heads/main

gha_language: Rust

gha_license_id: NOASSERTION

repo_name: maplibre/mbtileserver-rs


text:
---
type: rule
title: Do you make awesome documentation?
uri: awesome-documentation
authors:
  - title: Adam Cogan
    url: https://ssw.com.au/people/adam-cogan
  - title: Damian Brady
    url: https://ssw.com.au/people/damian-brady
  - title: Eric Phan
    url: https://ssw.com.au/people/eric-phan
  - title: Ulysses Maclaren
    url: https://ssw.com.au/people/ulysses-maclaren
  - title: Adam Stephensen
    url: https://ssw.com.au/people/adam-stephensen
  - title: Matt Goldman
    url: https://ssw.com.au/people/matt-goldman
  - title: Piers Sinclair
    url: https://ssw.com.au/people/piers-sinclair
related:
  - reference-do-you-use-the-correct-symbols-when-documenting-instructions
  - reference-do-you-use-the-right-order-of-instructions
  - do-you-highlight-actions-correctly-in-your-document
  - do-you-make-numbers-more-readable
  - do-you-include-version-numbers-in-your-file
  - do-you-refer-to-the-reader-and-author-consistently-throughout-your-document
  - tiny-do-you-use-active-phrases-no-zombies-please
  - user-journey-mapping
  - package-audit-log
  - technical-debt
redirects:
  - do-you-review-the-documentation
  - do-you-make-awesome-documentation
created: 2012-03-16T08:01:26.000Z
archivedreason: null
guid: d9a17cdf-0f7c-43dc-91a1-7b8fcc29467d
---

There are a few styles of documentation:

<!--endintro-->

### ❌ Bad example – Old School

::: bad
![Figure: Bad example - The dinosaur’s method of documentation](old-documentation.png)
:::

The old school way is document first – lots of planning and lots of heavy documentation created upfront before even a single line of code is written.

This is the method most familiar to teams who are comfortable with Waterfall and have possibly never heard of Agile. Documentation can normally be characterized by:

* Heavy, long documents
* Sequence Diagrams
* UML

This is a well-established way to do documentation, but it has several problems:

* Gets out of date quickly
* High maintenance overhead
* Needs a business analyst

::: bad
![Figure: Bad example - Documentation can take the form of Sequence Diagrams](enterprisearchitect1.jpg)
:::

::: bad
![Figure: Bad example - Use Case Diagrams are even worse!](EnterpriseArchitectUseCases.jpg)
:::

There may be exceptions – some situations benefit from this kind of documentation; for example, it may be necessary to support a business case – although a well-defined spec is a better document to support a business case.

::: greybox
 **More info:** [Rules to Better Specification Reviews](/rules-to-better-specification-reviews)
:::

**Tip:** Documentation should be as minimal as possible. If your circumstances require this style of documentation, start by limiting it to just enough to cover your first couple of Sprints. And recognize that by going down this path you make a commitment to keeping it up-to-date.

### ✅ Good example – The 8 Important Documents

This style of documentation is used by modern teams who are Agile only.

**In the repository (for developers):**

**1. README.md** – Gives an overview of the project and provides links to the rest of the documentation. It is important for the README.md to show a high-level architecture diagram that illustrates the overarching solution.

**2. _docs\Instructions-Compile.md** – Instructions on how to build and run the project (AKA the F5 experience).

**3. _docs\Instructions-Deployment.md** – Explains how to deploy the solution, including any additional processes (e.g. DevOps)

**4. _docs\Business.md** – Explains the purpose of the application, including the problem, goals and statement of intent.

**5. _docs\Technologies-and-Architecture.md** – Provides a technical overview of the solution.
* A link to an [architecture diagram](https://www.ssw.com.au/rules/architecture-diagram) which outlines a high-level overview of the project.
* Links to any lower level architecture diagrams of the system e.g. [Azure resources diagram (auto generated)](https://www.ssw.com.au/rules/azure-resources-diagram)
* Coding patterns followed (e.g. [Clean Architecture](https://rules.ssw.com.au/rules-to-better-clean-architecture))
* 3rd party libraries used
* 3rd party services used
* A link to all [package-audit-logs](/package-audit-log)

**6. _docs\Alternative-Solutions-Considered.md** – explains other options that were discounted. For example
  * We chose to use a code-centric .NET solution over a low code solution because we did not want to be locked into any specific vendor e.g. Dynamics, Outsystems.
  * We chose to use Angular over React because 5/6 developers on the project were more familiar with Angular.
  * We chose to use Azure over on-premises to avoid procurement of costly servers.
  * Note: If you decide after the fact that the chosen solution is wrong, this should be explained. Include what led to the current circumstances and if there is a planned change.

**7. _docs\Definition-of-Done.md** - Ensures that your team [maintains a high level of quality with a Definition of Done](/definition-of-done)

**8. _docs\Definition-of-Ready.md** – Ensures that all your PBIs are well defined to an agreed standard before adding them to a sprint (see [https://rules.ssw.com.au/have-a-definition-of-ready](/have-a-definition-of-ready))

Keeping these documents in the repository means that you ensure that any documentation the developers need to work on or run the code is where they need it - with the code.

It also means that when a developer makes a change to the code that needs an update to the documentation, the documentation changes can be checked in along with the code in the same commit.

**Exposing documentation through a Wiki (for developers and other stakeholders):**

Documents to be read or edited by the Product Owner (or other members of the Scrum team) should be exposed through a Wiki. The advantage of this approach is that the writing experience in the Wiki is more friendly for non-developers. The Wiki should be sourced from the repo **docs\\** folder to ensure documentation is kept up-to-date. There are several options for creating a Wiki:

Azure DevOps wiki options:
* [Wiki edited via the repo](https://docs.microsoft.com/en-us/azure/devops/project/wiki/publish-repo-to-wiki?view=azure-devops&tabs=browser) (recommended)
* [Wiki edited via the portal](https://docs.microsoft.com/en-us/azure/devops/project/wiki/wiki-create-repo?view=azure-devops&tabs=browser)
* An alternative Wiki platform (e.g. [Confluence](https://www.atlassian.com/software/confluence))

GitHub wiki options:
* [Markdown files edited via the repo](https://docs.github.com/en/github/managing-files-in-a-repository/editing-files-in-your-repository) (recommended)
* The [GitHub repo Wiki](https://docs.github.com/en/communities/documenting-your-project-with-wikis/about-wikis)
* An alternative Wiki platform (e.g. [Confluence](https://www.atlassian.com/software/confluence))

**Tip:** You can publish your documentation from the repo using [GitHub Pages](https://pages.github.com)

**Tip:** All of your documents (in your Wiki and your repository) should be [written in Markdown](/using-github-and-markdown-to-store-you-content).

::: bad
![Figure: Bad example - Github project without any documentation or instructions](documentation__level2__bad-example-gh.png)
:::

::: bad
![Figure: Bad example - Azure DevOps project without any documentation or instructions](azuredevops-bad.png)
:::

![Figure: OK example - Github project with README instructions on how to compile and run the project (but still has a TODO)](documentation__level2__good-example-1-gh.png)

::: good
![Figure: Good example - Azure DevOps project with README instructions on how to compile and run the project](azuredevops-good.png)
:::

::: good
![Figure: Good example - Github project with Wiki instructions for product owners, stakeholders, or public consumption (Source: https://github.com/christoment/Northwind/wiki)](documentation__level2__good-example-2-gh.png)
:::

::: good
![Figure: Good example - Azure DevOps project with Wiki instructions for product owners, stakeholders, or public consumption](azuredevops-wiki-good.png)
:::

**Tip:** Use your documentation for onboarding developers

::: bad
![Figure: Bad example - No documentation, go and sit with another developer](sit-dev-bad.png)
:::

::: good
![Figure: Good example - Developer onboarding can be self-guided by good documentation, and offers a structure for feedback and improvement if the developer hits any issues](documentation\_\_level2\_\_onboarding-pbi-3.png)
:::

**Tip:** Keep your documentation as minimal as possible - automate the F5 experience and deployment process (documents 2 and 3) using PowerShell scripts. Then your documents can just say "run these scripts"

### The rest of the jigsaw

**Update your Acceptance Criteria** - If you use a policy that requires commits to be linked to PBIs, then you understand that the PBI is now the documentation. If requirements change (based on a conversation with the Product Owner of course) then the PBI should be updated.

When updating the Acceptance Criteria, ~~strike through~~ the altered Acceptance Criteria, and add the new ones. Get the PO to confirm your understanding.

::: greybox
Example:

~~Enter search text, click ‘Google’, and see the results populate below.~~
[Updated] Enter search text and automatically see the results populate below.
:::

This should be added to the [Definition of Done](/definition-of-done).

### Technical Debt

**What's "Technical Debt"?**

![Technical Debt](Debt.jpg)

During a project, when you add functionality, you have a choice:

* One way is quick but messy - it will make further changes harder in the future (i.e. quick and dirty).

* The other way is cleaner – it will make changes easier to do in the future but will take longer to put in place.

'Technical Debt' is a metaphor to help us think about this problem. In this metaphor (often mentioned during Scrum software projects), doing things the quick and dirty way gives us a 'technical debt', which will have to be fixed later. Like financial debt, the technical debt incurs interest payments - in the form of the extra effort that we must do in future development.

We can choose to continue paying the interest, or we can pay the debt in full by redoing the piece of work in a cleaner way. Learn about [the importance of paying back technical debt.](https://www.ssw.com.au/rules/technical-debt/)

The same principle is true with documentation. Using the 'old school' method will leave you with a build-up of documentation that you will need to keep up to date as the project evolves.

**Warning:** If you want to follow Scrum and have zero technical debt, then you must throw away all documentation at the end of each sprint. If you do want to keep it, make sure you add it to your [definition of done](/definition-of-done) to keep it updated.

gha_language: TSQL


text:
# Releasing the module

Run a `release_prep` job with the branch set to `main` and `module_version` set to the module version that will be released

> You can access the `release_prep` job via the `Actions` tab at the repository home page

The `release_prep` job will run the `pdk release prep` command, push its changes up to the `release_prep` branch on the repo, and then generate a PR against `main` for review. Follow the instructions in the PR body to properly update the `CHANGELOG.md` file.

Once the release prep PR's been merged to `main`, run a `release` job with the branch set to `main`. The `release` job will tag the module at the current `metadata.json` version, push the tag upstream, then build and publish the module to the Forge.

gha_language: Ruby


text:
---
title: Azure Regions
---

## Overview

Microsoft provides the following pages with information about their regions and data center locations:

* https://azure.microsoft.com/en-us/global-infrastructure/regions/ - Pretty map of all regions
* https://azure.microsoft.com/en-us/global-infrastructure/locations/ - Actual list of data center locations

Picking the right region is important because you want:

* A nearby location to minimize network latency
* A location that minimizes costs

Each region has different costs - which can make the trade-off between goal #1 and #2 kind of interesting.

## Pricing Differences

The site below provides a nice comparison of compute costs across regions:

* https://azureprice.net/Region

As of August 26, 2019, these prices were as follows:

![Bar Char of Pricing by Region](assets/azure-pricing-by-region.png)

The table below contains specific information for the North American locations:

| Region name | Location | Region ID | Average price per vm hour |
|-------------|----------|-----------|---------------------------|
| West Central US  | Wyoming     | westcentralus  | 0.45 |
| East US 2        | Virginia    | eastus2        | 0.54 |
| West US 2        | Washington  | westus2        | 0.54 |
| East US          | Virginia    | eastus         | 0.59 |
| North Central US | Illinois    | northcentralus | 0.60 |
| Central US       | Iowa        | centralus      | 0.63 |
| Canada East      | Quebec City | canadaeast     | 0.63 |
| South Central US | Texas       | southcentralus | 0.64 |
| Canada Central   | Toronto     | canadacentral  | 0.65 |
| West US          | California  | westus         | 0.66 |

Wyoming is the cheapest, but it also twice the distance from Cincinnati as Illinois.  East US 2 (Virginia) looks like a good trade-off of price and location.  If we assume that network traffic goes through Cincinnati to get to the cloud this makes sense.  If we instead assume that stores will connect directly to the cloud, then maybe Wyoming would be a good option.

repository: bodhi-root/public-wiki

repo_name: bodhi-root/public-wiki


text:
---
layout: post
title: Milwaukee Maker Faire
---

![Pictured are some members of the team at Make Faire Milwaukee.](/images/makerfaire.JPG)

Thank you [Maker Faire Milwaukee](https://milwaukee.makerfaire.com) for allowing the team to have a Show and Tell booth at the 2018 Maker Faire!

From their website:
>Maker Faire is a gathering of fascinating, curious people who enjoy learning and who love sharing what they can do. From engineers to artists to scientists to crafters, Maker Faire is a venue for these "makers" to show hobbies, experiments, projects.
We call it the Greatest Show (& Tell) on Earth - a family-friendly showcase of invention, creativity, and resourcefulness.

The event is co-hosted by the [Betty Brinn Children’s Museum](https://www.bbcmkids.org/).

It is estimated that just under 40,000 individuals attended this year’s event at the Wisconsin State Fair Park, five miles from Marquette’s campus. We were fortunate enough to be right near the entrance as well!

The team spoke with guests of all ages and discussed the project goal of being able to support In-Situ Resource Utilization on Mars and the role that our robot will play in the process. When speaking with K-12 students we relayed our enthusiasm in the project and encouraged them to seek out their own personal STEM interests.

We showcased a 2017-2018 senior design project named Arnold, an autonomous snowplow robot. This robot is undoubtedly an attention grabber which allowed us to talk to event-goers about Marquette senior design successes and how we intend to continue this trend in the NASA Robotic Mining Competition.

Dean Koumoutsos, Electrical Lead


text:
# Watermark Docker Base Image

This is the base image for all of Watermark's Docker images. It installs
the lowest common denominator of tools and libraries needed for all
other images. It is based on the official `centos` repository's centos7
branch. It installs essential build libraries and a handful of common
tools (e.g. vim, curl, etc.)

repository: watermarkchurch/docker-image-base

repo_name: watermarkchurch/docker-image-base


text:
<!-- vim-markdown-toc GFM -->

* [Install (Raspberry Pi)](#install-raspberry-pi)
    * [Install `Berryconda3`](#install-berryconda3)
    * [Create Conda UI development environment](#create-conda-ui-development-environment)
    * [Install asyncserial:](#install-asyncserial)
    * [Clone `esp32-pump-driver`](#clone-esp32-pump-driver)
    * [Launch Jupyter notebook](#launch-jupyter-notebook)
* [Known issues](#known-issues)
    * [Jupyter Lab fails to build labextension for IPython widget](#jupyter-lab-fails-to-build-labextension-for-ipython-widget)

<!-- vim-markdown-toc -->

# Install (Raspberry Pi)

## Install `Berryconda3`

Download and install `Berryconda3`: https://github.com/jjhelmus/berryconda#quick-start

## Create Conda UI development environment

Start a terminal and run the following:

```sh
source activate
conda create -n esp32-pump -c conda-forge -c sci-bots nodejs astroid ecdsa isort lazy-object-proxy mccabe pylint pyserial typing websocket-client pyserial six jupyter notebook jupyterlab jupytext autopep8 ipywidgets pyaes
source activate esp32-pump
pip install mpy-repl-tool
python -m there.jupyter-setup
conda config --env --append channels conda-forge
```

## Install asyncserial:
```
source activate esp32-pump
cd ~
pip install trollius "ipython>=7"
git clone https://github.com/sci-bots/asyncserial
cd asyncserial
pip install .
cd ..
```

## Clone `esp32-pump-driver`

```
source activate esp32-pump
cd ~
git clone https://github.com/sci-bots/esp32-pump-driver
```

## Launch Jupyter notebook

```
source activate esp32-pump
cd ~/esp32-pump-driver
jupyter notebook
```

# Known issues

## Jupyter Lab fails to build labextension for IPython widget

Use `jupyter notebook` instead!


text:
# Exercise #1

1. Using the short declaration operator, **ASSIGN** these **VALUES** to **VARIABLES** with the **IDENTIFIERS** “x” and “y” and “z”
    1. 42
    2. “James Bond”
    3. true
2. Now print the values stored in those variables using
    1. a single print statement
    2. multiple print statements

# Exercise #2
1. Use var to **DECLARE** three **VARIABLES**. The variables should have package level scope. Do not assign **VALUES** to the variables. Use the following **IDENTIFIERS** for the variables and make sure the variables are of the following TYPE (meaning they can store VALUES of that **TYPE**).
    1. identifier “x” type int
    2. identifier “y” type string
    3. identifier “z” type bool
2. In func main
    1. print out the values for each identifier
    2. The compiler assigned values to the variables. What are these values called? Answer: zero value

# Exercise #3
Using the code from the previous exercise,
1. At the package level scope, assign the following values to the three variables
    1. for x assign 42
    2. for y assign “James Bond”
    3. for z assign true
2. In func main
    1. use fmt.Sprintf to print all of the VALUES to one single string. ASSIGN the returned value of TYPE string using the short declaration operator to a VARIABLE with the IDENTIFIER “s”
    2. print out the value stored by variable “s”

# Exercise #4
For this exercise
1. Create your own type. Have the underlying type be an int.
2. Create a **VARIABLE** of your new **TYPE** with the **IDENTIFIER** “x” using the “VAR” keyword
3. In func main
    1. print out the value of the variable “x”
    2. print out the type of the variable “x”
    3. assign 42 to the **VARIABLE** “x” using the “=” **OPERATOR**
    4. print out the value of the variable “x”

# Exercise #5
Building on the code from the previous example
1. At the package level scope, using the “var” keyword, create a VARIABLE with the IDENTIFIER “y”. The variable should be of the UNDERLYING TYPE of your custom TYPE “x”
    1. eg:

    type hotdog int

    var x hotdog

    var y int
2. In func main
    1. this should already be done
        1. print out the value of the variable “x”
        2. print out the type of the variable “x”
        3. assign your own VALUE to the VARIABLE “x” using the “=” OPERATOR
        4. print out the value of the variable “x”
    2. now do this
        1. now use CONVERSION to convert the TYPE of the VALUE stored in “x” to the UNDERLYING TYPE
            1. then use the “=” operator to ASSIGN that value to “y”
            2. print out the value stored in “y”
            3. print out the type of “y”

# Exercise #6
1. Take this quiz: https://goo.gl/forms/dfwmTuYTe5ox8nyt1 (There is not code for this).

repository: lhbelfanti/goal

repo_name: lhbelfanti/goal


text:
SSX
===

SSX is SSH on colorful xterm.

Description
-----------

SSX uses consistent colors for the same hostname, so that it is easier to navigate accross different windows with different remote shells. No color configuration is required: colors selection is based on the hash of the hostname string.

Usage
-----
Just replace the ssh command with ssx, it uses the same syntax:
```
$ ssx.rb [ssh options] user@host [command]
```

repository: mickeyil/ssx

repo_name: mickeyil/ssx


text:
---
title: "Consumer theory for cheap information - Simulations (discrete sampling case)"
date: "2021-10-06T00:00:00Z"
---

This simulation illustrates some of the main results of "Consumer theory for cheap information." This code simulates the standard case where information is only consumed in discrete samples.

To see the simulations used in the paper---i.e. the infinitely divisible case, click [here](../info-consumer-theory-continuous).

If you’d like to experiment yourself, the original Jupyter notebook can be downloaded [here](files/info-consumer-theory-discrete.ipynb) (Right click -> “Save Link As”).

# Code setup

First, we need to import a number of standard Python packages:

```python
import numpy as np                   # Basic array stuff
import scipy.optimize as optim       # For finding function mins
from scipy.stats import multinomial  # Multinomial probability computation
import matplotlib.pyplot as plt      # Plotting
from matplotlib import rc
from tabulate import tabulate        # For nicer printing of some data
import math
import time
```

# Model

A decision maker must take one of finitely many actions $a\in A$ facing an uncertain state of the world, $\theta$, that is one of finitely many possible states. She has a state-dependent payoff function, $u(a,\theta)$ and chooses her action to maximize expected payoff. Her prior is given by $p\in\Delta\Theta$.

Prior to acting, she may purchase information about the state and update her prior based on that information. As standard, define an information as a *Blackwell experiment*, that is, a collection of state-dependent distributions, $F(x\ |\ \theta)$ over some realization space, X:

$$
\mathcal{E} \equiv
\{X, \langle F(\cdot\ |\ \theta)\rangle_{\theta\in\Theta}\}
$$

(In a fully formal treatment, the definition would also include a σ-algebra. For the purposes of this paper, we can ignore such measure-theoretic complications).

After observing a realization from an information source, the decision maker can update with Bayes rule:

$$
p'_\theta(x) = \frac{p_\theta f(x\ | \ \theta)}
           {\sum_{\theta'\in\Theta}p_{\theta'}f(x\ |\ \theta')}
$$

To avoid trivialities, assume that no realization perfectly rules in or out any subset of the states, that is, if realization has positive probability (density) under one state, it must have positive probability under all states. (In technical terms, assume the $F(\cdot\ |\ \theta)$ are all mutually absolutely continuous so the Radon-Nikodym derivatives, $dF(\cdot\ |\ \theta')/dF(\cdot\ |\ \theta)$ all exist.) For notational simplicity in this illustration, I'll assume each state-dependent distribution has finitely many possible realizations and thus pmf given by, $f$.

We can the define an *amount* of information by a number of conditionally independent samples from such a source.

For illustration, consider a two-state world, $\theta\in\{H,L\}$. An information source might be a coin that is fairly waited in the $L$ state, and biased 70% to heads in the $H$ state. Then samples from this source would simply be the number of coin flips. In an experimental setting, samples would be literal samples under some experimental design.

The DM has a collection of information sources $\mathcal{E}_i,\ldots, \mathcal{E}_I$ from each of which she can purchase an arbitrary number of samples, $\mathbf{n}=[n_i]$, at some cost $[c_i]$ each.

The goal is to characterize the substitutability of different information sources under the normal Bayesian (ex ante) information value---that is, the expected payoff gain from acting after observing a realization from information source $\mathcal{E}$:

$$
V(\mathcal{E}) \equiv \sum_{x\in R} \max_a \{\sum_\theta p'_\theta(x) u(a,\theta)\} f(x) - \max_a \{\sum_\theta p_\theta u(a,\theta)\}
$$
where $f(x)\equiv \sum_\theta p_\theta f(x\ |\ \theta)$ is the unconditional realization probability for the given source. (NB: the paper works with expected *loss* rather than expected value. This doesn't affect the ordinal ranking of experiments, and thus has no effect on the budget-constrained model).

Information value is typically a very poorly behaved function, so I approach the problem with an asymptotic approach using large deviations methods.

Throughout this notebook, I'll be working with a 3 state decision problem.

```python
numstates = 3
```

# Composite information sources and information values

## Defining information sources

In order to simulate information values, we need a way to define Blackwell experiments in a way amenable to computation: Define an information source as a $|\Theta|\times|X|$ matrix, so each row of the matrix lists the probability of each realization in that state. I will typically use Q to denote such a matrix.

The following code specifies a pair of information sources in this manner. By default, it will use a pair of experiments that produces relatively nice plots (including Fig. 3 in the paper). If those lines are removed/commented, the code will generate a random pair of information sources.

```python
Qperfect = np.eye(numstates)   # Perfect information source

## Generate random experiments for testing
def rand_source(numstates, numrealizations):
    # generate a random array with the appropriate dimension
    Q = np.random.rand(numstates, numrealizations)
    # normalize so each row sums to 1
    for state in range(numstates):
        Q[state, :] = Q[state, :] / np.sum(Q[state, :])
    return Q

# Q1 = rand_source(numstates, 3)
# Q2 = rand_source(numstates, 3)

## The following are Blackwell ordered but have interior solutions
# Q1 = np.array([[0.50, 0.50],
#                [0.60, 0.40],
#                [0.65, 0.35]])
# Q2 = np.array([[0.10, 0.35, 0.55],
#                [0.35, 0.30, 0.35],
#                [0.10, 0.05, 0.85]])

Q1 = np.array([[0.07, 0.18, 0.75],
               [0.45, 0.19, 0.36],
               [0.45, 0.05, 0.50]])
Q2 = np.array([[0.42, 0.58],
               [0.63, 0.37],
               [0.03, 0.97]])

# state labels. Will use for nice output tables
states = []
for stateidx in range(Q1.shape[0]):
    states.append(["State {i}".format(i=stateidx)])

print("Conditional probability of each realization:\n")

# Output table and print
table1 = np.append(states, Q1, axis=1)
realizations1 = ["Q1"]
for realization in range(Q1.shape[1]):
    realizations1.append("X1 =" + " " + str(realization))
print(tabulate(table1, headers=realizations1)+"\n")

table2 = np.append(states, Q2, axis=1)
realizations2 = ["Q2"]
for realization in range(Q2.shape[1]):
    realizations2.append("X2 =" + " " + str(realization))
print(tabulate(table2, headers=realizations2))
```

    Conditional probability of each realization:

    Q1         X1 = 0    X1 = 1    X1 = 2
    -------  --------  --------  --------
    State 0      0.07      0.18      0.75
    State 1      0.45      0.19      0.36
    State 2      0.45      0.05      0.5

    Q2         X2 = 0    X2 = 1
    -------  --------  --------
    State 0      0.42      0.58
    State 1      0.63      0.37
    State 2      0.03      0.97

### Testing Blackwell ordering (optional)

In the above code block, there is a (commented) example of a Blackwell-ordered pair of experiments that illustrates that interior solutions may be optimal even with Blackwell-ordered experiments. Thus we will need to test if a test Blackwell dominates another by determining whether a valid garbling matrix exists. We can do this with a simple linear algebra exercise: For each column (realization) of $Q_2$, premultiply by $(Q_1^T Q_1)^{-1}Q_1^T$. This operation will find the weight matrix, $G$ such that $Q_1 G$ is as close as possible to $Q_2$. We then only need check that $G$ is a valid garbling matrix (is row stochastic) and that $Q_1 G=Q_2$.

```python
def garbling_matrix(Q1, Q2):
    numstates = Q1.shape[0]
    numrealizations1 = Q1.shape[1]
    numrealizations2 = Q2.shape[1]
    projectionmatrix = np.linalg.inv(Q1.T @ Q1) @ Q1.T
    garbling = np.empty([numrealizations1, numrealizations2])
    for r2 in range(numrealizations2):
        garbling[:, r2] = projectionmatrix @ Q2[:, r2]
    return garbling

def check_stochastic(garbling):
    if ~np.all(garbling > -1E-6):
        return False
    if np.all(abs(sum(garbling.T) - 1) < 1E-6):
        return True
    return False

def check_BD(Q1, Q2):
    garbling = garbling_matrix(Q1, Q2)
    # first check if the matrix is a valid garbling
    if check_stochastic(garbling):
        # then check if Q2 is the garbled Q1
        if np.all(abs((Q1 @ garbling) - Q2) < 1E-6):
            return True
    # if either check fails, return false
    return False
```

```python
check_BD(Q1,Q2)
```

    False

```python
check_BD(Q2,Q1)
```

    False

## Composite experiments

Now, we need to be able to quickly compute the matrix for composite experiments. First, we need to be able to compute the matrix for $n$ i.i.d. samples from 1 experiment.

Since the total number of realizations of each type is a sufficient statistic for the entire vector of realizations, we can simplify things by first computing all of the partitions of $n$ with $|X|$ components (all possible realization sums), the use a multinomial distribution.

The output matrix will be $|\Theta|\times$(number of ways to sum $|X|$ postive integers to add up to $n$)

```python
# Compute appropriate partitions (returns a generator)
def partitions(n, numrealizations):
    if numrealizations == 1:
        if n >= 0:
            yield (n,)
        return
    for i in range(n+1):
        for result in partitions(n-i, numrealizations-1):
            yield (i,) + result

# Compute matrix for the n-sample source
def n_samples(Q, n):
    numstates = Q.shape[0]
    numrealizations = Q.shape[1]
    if n == 0:                   # return trivial experiment if 0 samples
        return np.ones((numstates, 1))
    QnT = []                     # transpose of Qn
    for outcome in partitions(n, numrealizations):
        outcomeprobs = []        # column of state-dep outcome probs
        for state_idx in range(numstates):
            # create a multinomial with the given outcome probs
            multinom = multinomial(n, Q[state_idx, :])
            outcomeprobs.append(multinom.pmf(outcome))
        QnT.append(outcomeprobs)
    Qn = np.array(QnT).T         # convert to array and transpose
    return Qn

n = 3
realizations1 = [str(n) + " samples of Q1"]
for outcome in partitions(n, Q1.shape[1]):
    realizations1.append(outcome)
table = np.append(states, n_samples(Q1, n), axis=1)
print("conditional probabilities of each sample combination:\n")
print(tabulate(table, headers=realizations1))
```

    conditional probabilities of each sample combination:

    3 samples of Q1      (0, 0, 3)    (0, 1, 2)    (0, 2, 1)    (0, 3, 0)    (1, 0, 2)    (1, 1, 1)    (1, 2, 0)    (2, 0, 1)    (2, 1, 0)    (3, 0, 0)
    -----------------  -----------  -----------  -----------  -----------  -----------  -----------  -----------  -----------  -----------  -----------
    State 0               0.421875     0.30375      0.0729       0.005832     0.118125      0.0567      0.006804     0.011025     0.002646     0.000343
    State 1               0.046656     0.073872     0.038988     0.006859     0.17496       0.18468     0.048735     0.2187       0.115425     0.091125
    State 2               0.125        0.0375       0.00375      0.000125     0.3375        0.0675      0.003375     0.30375      0.030375     0.091125

Second, we need to be able to composite two *distinct* information sources. If info source $\mathcal{E}_1$ and $\mathcal{E}_2$ have $|X_1|$ and $|X_2|$ possible realizations respectively, then the composite source consisting of 1 sample from each has $|X_1|\times|X_2|$ outcomes. We can get a matrix of all possible combination probabilities by simply by listing out each element of the outer product of the rows of each matrix:

```python
def composite_source(Q1, Q2):
    numstates = Q1.shape[0]
    numrealizations = Q1.shape[1] * Q2.shape[1]
    Qcomp = np.empty((numstates, numrealizations))  # initialize output
    for state in range(numstates):
        # compute all possible combination probs with an outer product
        Qcomp[state, :] = \
            np.reshape(np.outer(Q1[state, :], Q2[state, :]),
                       (numrealizations))           # reshape to vect.
    return Qcomp

Q12comp = composite_source(Q1, Q2)
realizations12 = ["1 from each"]
for x1idx in range(Q1.shape[1]):
    for x2idx in range(Q2.shape[1]):
        realizations12.append("X1={i1}, X2={i2}".format(i1=x1idx, i2=x2idx))
table = np.append(states, Q12comp, axis=1)
print("Conditional probabilties of each combination of realizations from Q1 and Q2:\n")
print(tabulate(table, headers=realizations12))
```

    Conditional probabilties of each combination of realizations from Q1 and Q2:

    1 from each      X1=0, X2=0    X1=0, X2=1    X1=1, X2=0    X1=1, X2=1    X1=2, X2=0    X1=2, X2=1
    -------------  ------------  ------------  ------------  ------------  ------------  ------------
    State 0              0.0294        0.0406        0.0756        0.1044        0.315         0.435
    State 1              0.2835        0.1665        0.1197        0.0703        0.2268        0.1332
    State 2              0.0135        0.4365        0.0015        0.0485        0.015         0.485

## Value of information

In order to compute information value, we must now define a state-dependent utility function and a prior belief. I'll code the utility function as a $|A|\times|\Theta|$ matrix of payoffs where $U_{a\theta}=u(a,\theta)$. The prior can simply be coded as a vector of belief probabilities.

```python
# example payoff matrix (payoff 1 only if choose the correct state
# plus an insurance action that always gives a low payoff)
#U = np.eye(numstates)
U = np.array([[1, 0, 0],
              [0, 1, 0],
              [0, 0, 1]])
# example prior vector (diffuse prior)
P = np.ones(numstates) / numstates
```

Information value is typically a fairly tricky thing to compute. In order to maximize computational efficiency, I vectorize the problem where possible. For a given information matrix, $Q$, and payoff matrix $U$, we can write the value *with* information as

$$ W(Q) = \max_D\{\text{tr}(QDU\pi)\}$$

where $\pi$ is a matrix who's diagonal elements are the prior probabilities and $D$ is a $|X|\times|A|$ matrix specifying the probability of taking each action after each realization (this is a linear program: $D$ generically is all zeros and ones since each realization generically has a unique optimal response.

([Leshno, 1992](https://cpb-us-w2.wpmucdn.com/campuspress.yale.edu/dist/3/352/files/2013/01/LeshnoSpector92.pdf) uses this formulation to provide an elementary proof of Blackwell's theorem for the finite-action/finite-state case.)

The value *of* information would then be $W(Q)$ minus the payoff from acting with no information. Such a subtraction is a monotone transformation, so it won't affect the ordinal properties I'm interested in.

In order to evaluate how close a bundle is to perfect information, I will sometimes use the ratio of the full-information gap (the difference between the value of a perfect signal and $W(Q)$, relative to the full-info value. This will be a percentage that approaches zero as the amount of samples increases.

None of these approximation would be particularly useful if they require so many samples as to be indistinguishable from a perfect source anyways. I will use thus use this relative info-gap as an ad hoc measure how useful the approximation is. That is, the relavent approximations are useful if they are accurate, even when the relative info-gap is large.

```python
def info_value(Q, U, P):
    numrealizations = Q.shape[1]

    Upi = U @ np.diag(P)
    # compute (actions x realizations) matrix of payoff of each action
    # times unconditional prob of each realization
    Ua = Upi @ Q
    # choose best action for each message then sum across messages
    valuewithinfo = sum(np.amax(Ua, axis=0))
    return valuewithinfo

# value of info for the examples above
print(tabulate([["Expected value of acting after observing Q1:",
                 info_value(Q1, U, P)]]))
```

    --------------------------------------------  --------
    Expected value of acting after observing Q1:  0.463333
    --------------------------------------------  --------

# Generalized precision

In the paper, I show that two information sources are exchangeable with ratios of respective precision-like indices of each experiment. In order to define this precision, we must first take a brief detour into large deviations theory.

I approach the problem of approximating information values by approximating the probability of a "mistake" (taking a suboptimal action in a given state). The normal form of Bayes's rule is a bit messy, so instead of working with probabilities, I work with log-likelihood ratios, where Bayes rule becomes a sum:

$$
\log\bigg(\frac{p'_{\theta}(x)}{p'_{\theta'}(x)}\bigg) =
\log\bigg(\frac{p_\theta}{p_{\theta'}}\bigg) +
\log\bigg(\frac{f(x\ |\ \theta)}{f(x\ |\ \theta)}\bigg)
$$

And, of course, we have no shortage of asymptotic results for approximating sums of many independent distributions.

For a given pair of states, define the (Chernoff, 1952, Moscarini and Smith, 2002) efficiency index of an experiment, $\mathcal{E}_1$, as the minimized value of the moment generating function (MGF) of the distribitution of log-likelihood ratios (LLR):

$$
\rho_1 \equiv \min_t \sum_r f(x\ |\ \theta)^t f(x\ |\ \theta')^{1-t}
$$
(Define $\tau_1$ as the minimizer)

Note that the expected value of the distribution of the above mgf is the negative Kullback-Leibler divergence,  $-D(F(\cdot\ |\ \theta')\ ||\  F(\cdot\ |\ \theta))$.

Note that because MGF of an indpendent sum is the product of MGFs, we have that $n$ samples from $\mathcal{E}_1$ will have efficiency index $\rho_1^n$.

Furthermore, because the minimum of a sum will be bigger than the sum of minima, we have that the efficiency index of a composite is more than the sum of its parts:

$$
\rho_{12} \geq \rho_1\rho_2
$$

Now, we can define the *precision* for a given state pair of a test by $\beta \equiv -\log(\rho)$. I call this a precision because, for Gaussian tests, it is, up to a multiplicative constant, the same as classical precision ($1/\sigma^2$).

This measure has a number of properties that you might expect for something called a precision

1. For any non-trivial experiment, $\beta>0$
2. $n$ samples from the same experiment has precision $n\beta$
3. Blackwell dominant experiments have higher precision

Intuitively, you can think of the precision as measuring how well an information source can distinguish between a given pair of states.

Because the efficiency index of a composite is weakly higher than the product of the individual efficiency index, a composite experiment is weakly less precise, for a given state, than the sum of it's parts.

```python
# the following returns the full list of state-pair precisions
# and their respective MGF minimizers
def precisions(Q):
    numstates = Q.shape[0]
    # compute the efficiency index for each state
    betalist = []
    taulist = []
    for state1 in range(numstates):
        for state2 in range(state1+1, numstates):
            # Define the llr mgf for the given dichtomy
            def llrmgf(t):
                Qstate1t = Q[state1, :]**t
                Qstate2t = Q[state2, :]**(1-t)
                return np.sum(Qstate1t * Qstate2t)
            # Compute index for the dichotomy
            optimizer = optim.minimize(llrmgf, 0.5)
            rho = optimizer.fun
            tau = optimizer.x[0]
            betalist.append(-np.log(rho))
            taulist.append(tau)
    return betalist, taulist

beta1list, tau1list = precisions(Q1)
beta2list, tau2list = precisions(Q2)
table = np.array([beta1list, beta2list]).T
print(tabulate(table,
               headers=["Q1 Precisions", "Q2 Precisions"]))
```

      Q1 Precisions    Q2 Precisions
    ---------------  ---------------
          0.126584         0.0226118
          0.123481         0.152613
          0.0288732        0.314685

```python
beta12list, tau12list = precisions(composite_source(Q1, Q2))
table = np.array([beta12list, [beta1list[i]+beta2list[i]
                               for i in range(len(beta1list))]]).T
print(tabulate(table,
               headers=["composite precisions", "sum of parts"]))
```

      composite precisions    sum of parts
    ----------------------  --------------
                  0.149026        0.149196
                  0.271436        0.276094
                  0.343391        0.343559

Now, it might seem that composites are always worse than the sum of their parts since, for any state pair, the composite is always less precise than the sum of its parts. But the value of information depends generically on a source's ability to distinguish any state from any other. Moscarini and Smith, 2002, showed that, for large sample sizes, the only state pair that matters is the pair hardest to tell apart---i.e. the pair with the least precision (highest efficiency index).

Thus complementarity often arises when experiments differ in the pair of states they most struggle to distinguish:

```python
beta1 = min(beta1list)
beta2 = min(beta2list)
beta12 = min(beta12list)
print(tabulate([[beta12, beta1+beta2]],
               headers=["min precision of composite", "sum of min precisions"]))
```

      min precision of composite    sum of min precisions
    ----------------------------  -----------------------
                        0.149026                 0.051485

In this particular example, we can see that it is in fact the composite has a *higher* least precision than the sum of least precisions of its parts.

# Plotting iso-precision curves

In particular, at large samples, two bundles of samples will perform equally if they have equal least precision. Information value at large samples is ordinally equivalent to

$$
v(n_1, n_2) \simeq (n_1+n_2)\beta_r
$$

where $\beta_r$ is the least precision dichotomy for a bundle that is composed of $r$ fraction of samples from $n_1$. Furthermore, we can breakdown $\beta_r$ into *marginal* precisions:

$$
\beta_\omega=\omega\beta_{r 1}+(1-r)\beta_{r 2}
$$

where $\beta_{r i}$ is $-\log M_i(\tau_r)$, is the negative log of the LLR MGF for the composite's worst-case state pair, evaluated at the composite's minimizer. We can then write

$$
v(n_1, n_2) \simeq n_1\beta_{r 1} + n_2\beta_{r 2}
$$

Heuristically, then it seems like the MRS between two samples at any bundle with $r$ fraction from $\mathcal{E}_1$ must then be the ratio of the component precisions. (For small subsititutions, relative to total sample size, the fraction of samples from each source doesn't change much, so the component precisions don't change much.)

Additionally, since the value is a min of a sums of precisions, there will be kinks when the least-precision state pair changes.

Of course, in a discrete sample setting there is no true MRS. In the appendix of the paper, I discuss a the formal notion of subsitutability in this setting, but for the purpose of interpretting things here, it works well enough to just pretend samples are divisible.

First, note that the component precisions only depend on the fraction of the bundle from each source (info value is homothetic). First, I compute the component precision for a given composite factor $r$.

```python
# return the component precision for each test at the r composite factor
def comp_precision(Q1, Q2, r):
    numstates = Q1.shape[0]
    # loop over pairs of states
    rho = 0
    for state1 in range(numstates):
        for state2 in range(state1+1, numstates):
            # Define the Hellinger transform for the given dichotomy
            def llrmgf1(t):
                Q1state1_t = Q1[state1, :]**t
                Q1state2_t = Q1[state2, :]**(1-t)
                return np.sum(Q1state1_t*Q1state2_t)

            def llrmgf2(t):
                Q2state1_t = Q2[state1, :]**t
                Q2state2_t = Q2[state2, :]**(1-t)
                return np.sum(Q2state1_t*Q2state2_t)

            def compllrmgf(t):
                return llrmgf1(t)**r * llrmgf2(t)**(1-r)

            # Compute efficiency index for the dichotomy
            optimizer = optim.minimize(compllrmgf, 0.5)
            rhopair = optimizer.fun
            taupair = optimizer.x
            # if new rho is worse (higher), store it
            if rho < rhopair:
                rho = rhopair
                # Store component rhos
                rho1w = llrmgf1(taupair)
                rho2w = llrmgf2(taupair)
    return -np.log(rho1w), -np.log(rho2w)

# return total precision for a composite factor w
def total_precision(Q1, Q2, w):
    beta1w, beta2w = comp_precision(Q1, Q2, w)
    return w*beta1w + (1-w)*beta2w
```

We can then compute points on an indifference curve by using the differential equation defined by the MRS ($dn_2/dn_1$) of iso-precision (note that precision can be computed at "fractional" samples even for discretely sampled experiments):

$$
\text{MRS}(r) = \frac{\beta_{r 1}}{\beta_{r 2}}
$$

In all the plots that follow, the reference point is the lower right corner bundle consisting entirely of samples from $\mathcal{E}_1$.

```python
def iso_least_precision(n1, n2, Q1, Q2):
    # step size for sample proportions.
    dr = 0.0005
    rstart = n1 / (n1+n2)
    startprecision = (n1+n2) * total_precision(Q1, Q2, rstart)   # precision of initial sample bundle
    # find iso-precision point on each ray from the origin
    n1points, n2points = [], []
    for r in np.arange(0,1+dr,dr):
        N = startprecision / total_precision(Q1, Q2, r)
        n1points.append(r*N)
        n2points.append((1-r)*N)
    return n1points, n2points

n1starts = [40, 100, 160]
#n1starts = [15]
n1pointsapprox, n2pointsapprox = [], []
for n1 in n1starts:
    #n1points, n2points = mrs_approx(n1start)
    n1points, n2points = iso_least_precision(n1, 0, Q1, Q2)
    n1pointsapprox.append(n1points)
    n2pointsapprox.append(n2points)
```

```python
fig = plt.figure(figsize=(12, 4), dpi=1000)
ax = fig.add_subplot(1,1,1)
ax.set_xlim((0, 160))
ax.set_ylim((0, 50))
ax.set_xlabel('Number of samples from Experiment 1')
ax.set_ylabel('Number of samples from Experiment 2')
for i in range(len(n1pointsapprox)):
    ax.plot(n1pointsapprox[i], n2pointsapprox[i], 'k')
```

![png](output_40_0.png)

We similarly compute the iso-precision lines for a given precision level for a given dichotomy:

```python
def iso_precision(precision, state1, state2, Q1, Q2):
    dr = 0.0005
    numstates = Q1.shape[0]
    # restrict both tests to the dichotomy of interest
    Q1d = Q1[[state1,state2],:]
    Q2d = Q2[[state1,state2],:]
    n1points, n2points = [], []
    for r in np.arange(0,1+dr,dr):
        N = precision / total_precision(Q1d, Q2d, r)
        n1points.append(r*N)
        n2points.append((1-r)*N)
    return n1points, n2points

numdichotomies = int((numstates * (numstates-1))/2)
# empty matrix for n2 points for each iso-precision line
isoprecn1points = []
isoprecn2points = []
dichotomyidx = 0     # index for dichotomy of current iteration
startprecision = n1starts[0]*total_precision(Q1, Q2, 1)
for state1 in range(numstates):
    for state2 in range(state1+1, numstates):
        n1points, n2points = iso_precision(startprecision, state1, state2, Q1, Q2)
        isoprecn1points.append(n1points)
        isoprecn2points.append(n2points)
        dichotomyidx += 1
```

```python
fig = plt.figure(figsize=(6,3), dpi=1000)
ax = fig.add_subplot(1,1,1)
#ax.set_xlim((0, 50))
#ax.set_ylim((0, 25))
ax.set_xlabel('Number of samples from Experiment 1')
ax.set_ylabel('Number of samples from Experiment 2')
for dichotomy in range(numdichotomies):
    ax.plot(isoprecn1points[dichotomy], isoprecn2points[dichotomy], '--k');
    ax.plot(n1pointsapprox[0], n2pointsapprox[0], 'k');
```

![png](output_43_0.png)

Samples are discrete so we can't compute exact indifference curves. Instead, we'll plot the locus of sample bundles that perform *just* better than some initial starting bundle (that is, the lower edge of the upper contour set).

To find all such points, it will be useful to be able to first find the $\mathcal{E}_1$ corner bundle that does just better than some given bundle.

```python
def just_better_corner(n1,n2):
    Q1n = n_samples(Q1, n1)
    Q2n = n_samples(Q2, n2)
    Qcomp = composite_source(Q1n, Q2n)
    startval = info_value(Qcomp, U, P)    # value of initial sample bundle
    # First find the n1 corner just better
    # We'll use this as our starting point
    n1running = n1
    currentval = 0
    # do a quick and dirty midpoint method
    # double sample size until something does better
    while currentval < startval:
        n1running = 2*n1running
        Q1n = n_samples(Q1, n1running)
        currentval = info_value(Q1n, U, P)
    n1upper = n1running
    n1lower = (1/2)*n1running
    # find number of times we can halve the distance
    numsplits = int(math.log(n1upper-n1lower, 2))
    # split 1 less than the max, so we should get very close
    for split in range(numsplits-1):
        n1mid = int((n1upper-n1lower)/2)
        Q1n = n_samples(Q1, n1mid)
        currentval = info_value(Q1n, U, P)
        if currentval > startval:
            n1upper = n1mid
        else:
            n1lower = n1mid

    #reset currentval then count up from n1lower by 1
    currentval = 0
    # add 1 until something does just better
    n1running = n1lower
    while currentval < startval:
        n1running = n1running + 1
        Q1n = n_samples(Q1, n1running)
        currentval = info_value(Q1n, U, P)

    return n1running
```

Now we can trace out the lower edge of the upper contour set.

```python
def inclusive_range(start, end, step):
    i = start
    while i < end:
        yield i
        i += step
    yield end

def ucs_true(n1, n2):
    #step = int((n1+n2)//20) + 1  # Use a coarse step for faster computation
    step = 1   # use a step size of 1 for exact, but slow, computation
    Q1n = n_samples(Q1, n1)
    Q2n = n_samples(Q2, n2)
    Qcomp = composite_source(Q1n, Q2n)
    startval = info_value(Qcomp, U, P)    # value of initial sample bundle
    # First find the n1 corner just better
    # We'll use this as our starting point
    if n2 > 0:
        n1start = just_better_corner(n1, n2)
    else: n1start = n1
    # Trace out the lower extent of the UCS
    n2 = 0      # start with no samples from Q2
    n1pointstrue = [n1start]
    n2pointstrue = [0]
    for n1loss in inclusive_range(1, n1start, step):
        n1 = n1start - n1loss
        n1pointstrue.append(n1)
        Q1n = n_samples(Q1, n1)
        # find minimum samples from Q2 to make better off
        currentval = 0
        while currentval < startval:
            n2 = n2 + 1
            Q2n = n_samples(Q2, n2)
            Qcomp = composite_source(Q1n, Q2n)
            currentval = info_value(Qcomp, U, P)
        n2pointstrue.append(n2)
        n2 = n2 - 1     # decr. n2 just to be sure later
    return n1pointstrue, n2pointstrue
```

```python
n1pointstrue, n2pointstrue = [], []
for n1 in n1starts:
    n1points, n2points = ucs_true(n1, 0)
    n1pointstrue.append(n1points)
    n2pointstrue.append(n2points)
```

And then plot the true upper contour set boundary against the iso-least-precision lines.

```python
fig = plt.figure(figsize=(7,4.2), dpi=1000)
# set matching font
fontProperties = {'family':'serif','serif':['Times'],
    'weight' : 'normal', 'size' : 12}
rc('text', usetex=True)
rc('font',**fontProperties)
ax = fig.add_subplot(1,1,1)
ax.set_xlim((0, 100))
ax.set_ylim((0, 60))
ax.set_xlabel('Number of samples from Experiment 1')
ax.set_ylabel('Number of samples from Experiment 2')
for i in range(len(n1pointstrue)):
    ax.plot(n1pointstrue[i], n2pointstrue[i], '--k',
            n1pointsapprox[i], n2pointsapprox[i], 'k');
#plt.savefig('figdiscrete.pdf', format='pdf', dpi=1000, bbox_inches='tight', pad_inches=0)
```

![png](output_50_0.png)

# Income expansion paths

Now we want to plot some income expansion paths. First, we'll compute the true demand for a variety of income levels, then plot the UC sets for those demand points, against their iso-precision lines.

In order to reduce the computational complexity of finding demand, we can restrict the search to a region around the maxi-min precision proportions. First, we find all kinks/corners by finding points where the slope of the iso-precision line falls in magnitude.

```python
# compute mrs by composite factor, find kinks
mrs = []
dr = 0.01
rgrid = np.arange(0, 1, dr)
kinks = [0, 1]
for r in rgrid:
    beta1r, beta2r = comp_precision(Q1, Q2, r)
    mrs.append(beta1r / beta2r)
    if r > dr and mrs[-1] < mrs[-2] - 0.001:    # mrs only falls at kink points
        kinks.append(r)

print(tabulate([["Kinks at composite factors:"] + kinks]))
```

    ---------------------------  -  -  ----
    Kinks at composite factors:  0  1  0.75
    ---------------------------  -  -  ----

Given a selection of sample proportions (the kinks and corners), for a given set of prices, we can find the one with best least precision per dollar. We can then search for the optimal sample bundle in the region around this point. Provided the search region is large enough, we will find the true optimal bundle.

```python
def demand(Y, c1, c2, kinks, epsilon):
    # first find maxi-min precision per dollar
    ppd0 = 0
    for r in kinks:
        ppd1 = total_precision(Q1, Q2, r) / (r*c1 + (1-r)*c2)
        if ppd1 > ppd0:
            ppd0 = ppd1
            rstar = r
    # maxi-min precision bundle under budget Y is
    N = Y / (rstar*c1 + (1-rstar)*c2)
    n1star, n2star = rstar*N, (1-rstar)*N
    # Candidate bundles are the feasible bundles with n1 within epsilon
    # of the maxi-min precision bundle (n1star, n2star) and are affordable
    value = 0
    n1Lbar = max(0,int(n1star-epsilon))            # lowest n1 can't be negative
    n1Ubar = min(int(n1star+epsilon), int(Y/c1))   # biggest n1 must be affordable
    for n1 in range(n1Lbar, n1Ubar+1):
        n2 = int((Y - (c1*n1)) / c2)   # highest affordable n2
        # compute value bundle
        Q1n = n_samples(Q1, n1)
        Q2n = n_samples(Q2, n2)
        Qcomp = composite_source(Q1n, Q2n)
        checkvalue = info_value(Qcomp, U, P)
        # check if value is higher than previous best and store if so
        if checkvalue > value:
            value = checkvalue
            n1best, n2best = n1, n2
    if n1best == n1Lbar:
        print('corner warning L')
    elif n1best == n1Ubar:
        print('corner warning U')

    return n1best, n2best
```

For default example, based on the previous plots of the UCS boundary vs the iso-least-precision curves, it seems that for price ratios not too close to the cutoffs between kinks and corners, the optimal bundle should always have $n_1$ well within about 30 samples. So we'll use that as our search range. Setting $\epsilon$ to some large number will guarantee that the true demand is found, but at high computational costs. (Higher budgets might takes days)

```python
epsilon = 100

# prices
c1, c2 = 2, 1
budgets = [5, 20, 40, 60, 80, 100, 150, 200, 300, 400]
#budgets = [10,20,30]
# Also compute the maxi-min precision ratio
ppds = [total_precision(Q1, Q2, r) / (r*c1 + (1-r)*c2) for r in kinks]
rstar = kinks[ppds.index(max(ppds))]
```

```python
n1demand, n2demand = [], []
for Y in budgets:
    n1, n2 = demand(Y, c1, c2, kinks, epsilon)
    n1demand.append(n1)
    n2demand.append(n2)
```

```python
fig = plt.figure(figsize=(7,4.2), dpi=1000)
# set matching font
fontProperties = {'family':'serif','serif':['Times'],
    'weight' : 'normal', 'size' : 12}
rc('text', usetex=True)
rc('font',**fontProperties)
ax = fig.add_subplot(1,1,1)
ax.set_xlim((0, 100))
ax.set_ylim((0, 60))
ax.set_xlabel('Number of samples from Experiment 1')
ax.set_ylabel('Number of samples from Experiment 2')
ax.plot(n1demand, n2demand, '.-k');

n1rstar = np.arange(0,100,0.01)
rstarRay = n1rstar*(1-rstar)/rstar
ax.plot(n1rstar, rstarRay, '--k');
```

![png](output_60_0.png)

Now compute upper contour sets for some of the points on the income expansion path.

```python
n1ucs, n2ucs = [], []
for i in [2, 5, 6]:
    n1points, n2points = ucs_true(n1demand[i],n2demand[i])
    n1ucs.append(n1points)
    n2ucs.append(n2points)
```

Now we want some iso-precision lines to go with the upper contour sets. We'll get a nicer looking plot if we compute the iso-precision lines through one of the corner bundles on upper contour set boundary.

```python
n1corners = []
for i in range(len(n1ucs)):
    # first entry in uCS plot is the n1 corner
    n1corners.append(n1ucs[i][0])

# compute the iso-precision lines
n1isoprec, n2isoprec = [], []
for n1 in n1corners:
    #n1points, n2points = mrs_approx(n1start)
    n1points, n2points = iso_least_precision(n1, 0, Q1, Q2)
    n1isoprec.append(n1points)
    n2isoprec.append(n2points)
```

The above code can take a *very* long time to compute. The following code will save/load the results for use later.

```python
import pickle
#with open('savedvars.pkl','wb') as f:
#    pickle.dump([n1demand,n2demand,n1ucs,n2ucs,n1isoprec,n2isoprec], f)
```

```python
with open('savedvars.pkl','rb') as f:
    n1demand,n2demand,n1ucs,n2ucs,n1isoprec,n2isoprec = pickle.load(f)
```

Finally, plot everything.

```python
fig = plt.figure(figsize=(7,4), dpi=1000)
# set matching font
fontProperties = {'family':'serif','serif':['Times'],
    'weight' : 'normal', 'size' : 12}
rc('text', usetex=True)
rc('font',**fontProperties)
ax = fig.add_subplot(1,1,1)
ax.set_xlim((0, 100))
ax.set_ylim((0, 60))
ax.set_xlabel('Number of samples from Experiment 1')
ax.set_ylabel('Number of samples from Experiment 2')
for i in range(len(n1ucs)):
    ax.plot(n1ucs[i], n2ucs[i], '--k',
            n1isoprec[i], n2isoprec[i], 'k');
ax.plot(n1demand, n2demand, '.-k');

# plot ray of maxi-min precision ratio
n1rstar = np.arange(0,100,0.01)
rstarRay = n1rstar*(1-rstar)/rstar
ax.plot(n1rstar, rstarRay, '--k');

rstarlower = rstarRay - 5
rstarupper = rstarRay + 11
ax.plot(n1rstar, rstarlower, ':k', linewidth=1.5);
ax.plot(n1rstar, rstarupper, ':k', linewidth=1.5);

plt.savefig('figincomeexpansiondiscrete.pdf', format='pdf', dpi=1000, bbox_inches='tight', pad_inches=0, transparent=True)
```

![png](output_69_0.png)

repository: ggbaker/personalSite

repo_name: ggbaker/personalSite


text:
#as2-lib

AS2 is a transport protocol specified in [RFC 4130](http://www.ietf.org/rfc/rfc4130.txt).
This library is a fork of [OpenAS2](http://sourceforge.net/projects/openas2/) which did not
release updates since 2010. I than split the project into a common library part (this project)
and a [server part](https://github.com/phax/as2-server) which contains a stand alone server. This project also contains a simple AS2 client which can be used to send messages to other AS2 servers.

This project is used in my following other projects:
  * **[as2-server](https://github.com/phax/as2-server)** - a stand alone AS2 server operating on a socket layer.
  * **[as2-peppol-client](https://github.com/phax/as2-peppol-client)** - a stand alone AS2 client that is capable of sending [PEPPOL](www.peppol.eu) compliant e-Procurement documents.
  * **[as2-peppol-servlet](https://github.com/phax/as2-peppol-servlet)** - integration into the Servlet specifications and for use with the [PEPPOL](www.peppol.eu) transport infrastructure including SBDH (Standard Business Document Header) handling.
  * **[as2-peppol-server](https://github.com/phax/as2-peppol-server)** - a stand alone Servlet based server to receive [PEPPOL](www.peppol.eu) AS2 messages.

This project is licensed under the FreeBSD License.

#Maven usage
Add the following to your pom.xml to use this artifact:
```
<dependency>
  <groupId>com.helger</groupId>
  <artifactId>as2-lib</artifactId>
  <version>1.1.0</version>
</dependency>
```

#Package structure
This library manages the package `com.helger.as2lib` and all sub-packages:

  * com.helger.as2lib.cert - contains the certificate factory
  * com.helger.as2lib.client - contains the AS2 client for sending messages
  * com.helger.as2lib.crypto - contains the BouncyCastle crypto code for signing, verification, encryption and decryption of messages
  * com.helger.as2lib.disposition - contains code to handle content disposition
  * com.helger.as2lib.exception - contains basic exception classes
  * com.helger.as2lib.message - contains the main message and MDN classes
  * com.helger.as2lib.params - generic code that allows for parameterization of certain message related configuration items
  * com.helger.as2lib.partner - contains the partner, partnership and factory code
  * com.helger.as2lib.processor - contains the basic building blocks for processing of messages
  * com.helger.as2lib.processor.module - contains the basic classes for "active" modules (modules that can be started and stopped)
  * com.helger.as2lib.processor.receiver - module for receiving messages
  * com.helger.as2lib.processor.receiver.net - module for receiving messages from Sockets
  * com.helger.as2lib.processor.resender - module for re-sending messages
  * com.helger.as2lib.processor.sender - module for sending messages
  * com.helger.as2lib.processor.storage - module for storing messages
  * com.helger.as2lib.util - contains utility classes used in several places in this library or in derived projects
  * com.helger.as2lib.util.cert - utility classes for certificate handling
  * com.helger.as2lib.util.http - utility classes for HTTP connection handling
  * com.helger.as2lib.util.javamail - utility classes for javax.mail handling

---

On Twitter: Follow @philiphelger


text:
![Legion Logo (Red)](./docs/logo-red.png "Legion Framework")

[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/legion-starter-pack/Lobby#)

legion-starter-pack
===================

Start with this [overview of the Legion load testing
framework](http://lane-webperformance.github.io/legion-starter-pack/).

What is this package?
---------------------

This is a "batteries included" npm package based on the latest stable
versions of the Legion libraries and example test cases.

You can use this package to learn from the examples or as a starting point for
your own test case development.

If you want to call Legion programmatically (i.e. not using the default main
method), or if you're just curious, you might want to look at the
[Legion Framework API](https://github.com/lane-webperformance/legion).

To Run the Examples . . .
-------------------------

	npm install
	node ./examples.js/001_simple.js

Or run any of the other examples. We hope to have a large number of examples
numbered by complexity, so you can start small and work your way up.

Some of the examples may have additional requirements. For example, the
Selenium WebDriver example won't work unless you have a working environment
for Selenium WebDriver.

To write your own test case . . .
--------------------------------

. . . just edit `testcase.js` and run:

	node testcase.js

This will run the test case with only one concurrent user. To run with many
users (say, 50), try:

	node testcase.js -n 50

If you need to write a test case that's similar to one of the examples, consider
copying the example onto test case.js and using it that way.

repository: lane-webperformance/legion-starter-pack

repo_name: lane-webperformance/legion-starter-pack


text:
# CNL
A library of tools for use with complex numbers & other math utilities I need

## Why
I made this library to help me learn about Complex Numbers and design a library to aid in the more tedious tasks

## Usage
To install this libaray locally, clone this repo, then run the following
```sh
# Windows
py3 setup.py develop

# Linux
sudo python3 setup.py develop
```

Using the `develop` mode instead of `install` will allow you to make edits to the code in this repo, and have the library automatically update.

This library can now be used via a normal import statement:
```python
import cnl
```

## TODO
I would like to add the ability to tell if a number is prime and reduce radicals

## Contributors
* William Meathrel
* Evan Pratten

repository: wm-c/CNL

gha_language: Python

repo_name: wm-c/CNL


text:
---
layout: post
published: false
---
Specially with code bases you're unfamiliar with, it's quite hard to determine which code is handling a given event. You grep through the code randomly searching for the needle in the haystack. It's not the most efficient way as you can see.

Before continuing, I just expect your website works reasonably well without JS; at least search crawlers should be able to index it properly.
Let me advice JS as an enhancement to the user experience, not the be-all-end-all of your site.

The basic principle here is: the browser reacts on user interface events by calling the default event handler or a custom handler we have defined via JS. The browser therefore knows those events you defined in code. So…

## Let's query the browser

Chrome comes with
getEventListeners($('#year').get(0))

(pic)

But I must say, this output was pretty cryptic to my standards.

### Enter jQuery
jQuery is the _de facto_ standard for DOM manipulation and the base for other libraries.
It has a very handy:

$._data($('#year').get(0), "events");

(pic)

## Finding the element

The problem lies in finding the right element. Proposals:

- select the element with the browser inspector, then go to Event Handlers. We might be lucky.
(pic)

- idk

- Label your elements that interact with JS properly. Adding a class with the `js-` prefix will help you identify clearly that element has a JS interaction. You'll never use js- classes for styling. Feel free to name it as you want, but mentioning its interaction in the name is usually a win. I.e: js-open-modal, js-toggle-dropdown, js-submit-xhr

license: Unlicense

gha_language: CSS

gha_license_id: Unlicense


text:
# Guard::Konacha [![Build Status](https://travis-ci.org/alexgb/guard-konacha.png)](https://travis-ci.org/alexgb/guard-konacha)

Automatically run your [Konacha](https://github.com/jfirebaugh/konacha) tests through [Guard](https://github.com/guard/guard/).

## Install

Install the gem:

    $ gem install guard-konacha

Or add to your Gemfile:

    gem 'guard-konacha'

## Usage

Add guard definitions to your `Guardfile`

    guard :konacha do
      watch(%r{^app/assets/javascripts/(.*)\.js(\.coffee)?$}) { |m| "#{m[1]}_spec.js" }
      watch(%r{^spec/javascripts/.+_spec(\.js|\.js\.coffee)$})
    end

## Configuration

If your specs live outside of `spec/javascripts` then tell Konacha where to find them.

    guard :konacha, :spec_dir => 'spec/front-end' do
      # ...
    end

If you want to use [capybara-webkit](https://github.com/thoughtbot/capybara-webkit) instead of the default selenium
driver:

    require 'capybara-webkit'
    guard :konacha, :driver => :webkit do
      # ...
    end

Or use [Poltergeist](https://github.com/jonleighton/poltergeist):

    require 'capybara/poltergeist'
    guard :konacha, :driver => :poltergeist do
      # ...
    end

If you are running konacha:serve on a different host or port than the
default `localhost` and `3500`, the configuration settings `:host` and `:port` will help you there.

## Development

This is a work in progress and could use some help.

## Contributors

[https://github.com/alexgb/guard-konacha/graphs/contributors](https://github.com/alexgb/guard-konacha/graphs/contributors)


text:
## Guidelines

### General

-   If space allows, and there are no more than 7 options in total, consider using [checkboxes](#/components/Checkbox) instead.
-   Keep option labels as short as possible in order to limit width to a minimum.
-   When an option is selected, it should be removed from the options list.

### Options Sorting

-   Always put the most common items at the top of the list. If no option is more common than the others, use alphanumeric or chronological order.

### Label

-   In most cases, you should include a label to identify the component.

---

## Related Components

[Single Select](#/components/SingleSelect)

[Checkbox](#/components/Checkbox)

repository: cestradamiranda/react-vapor

gha_language: TypeScript

repo_name: cestradamiranda/react-vapor


text:
---
sidebar_position: 6
---

# Building Cluster Images Using exec and scp Commands

By default, `sealos run xx` only runs the command and copies the file on the first master node. When you want to run the command or copy files on specific nodes or all nodes, you can use the `sealos exec` or `sealos scp` commands when building the cluster image.

- sealos exec: Connects to one or more nodes and runs any shell command;
- sealos scp: Connects to one or more nodes and copies local files to remote nodes.

Although you can directly use these commands on the host, this article mainly describes how to use these two commands when building the cluster image using sealos build.

## sealos exec Example

Below is an example of building an openebs cluster image. Before installing openebs maystor, some initialization operations need to be performed on the node, you can use sealos exec to achieve this.

First, create a base directory for building.

```shell
$ mkdir ~/cloud-images
```

Create a `charts` directory to store the kubernetes nginx helm charts file.

```shell
$ cd cloud-images
```

Create a file named `Kubefile` for image building:

```shell
$ cat Kubefile
FROM scratch
COPY manifests manifests
COPY registry registry
COPY opt opt
COPY mayastor.sh mayastor.sh
CMD ["bash mayastor.sh"]
```

Create a script file named `mayastor.sh`, the shell command after sealos exec will be executed on all nodes (create hugepage, load kernel modules on all nodes), but other commands will only run on the master node.

```shell
$ cat mayastor.sh
#!/usr/bin/env bash
set -e

sealos exec "
echo vm.nr_hugepages = 1024 | sudo tee -a /etc/sysctl.d/mayastor.conf
sysctl -p
sudo modprobe -- nbd
sudo modprobe -- nvmet
sudo modprobe -- nvmet_rdma
sudo modprobe -- nvme_fabrics
sudo modprobe -- nvme_tcp
sudo modprobe -- nvme_rdma
sudo modprobe -- nvme_loop
cat <<EOF | sudo tee /etc/modules-load.d/mayastor.conf
nbd
nvmet
nvmet_rdma
nvme_fabrics
nvme_tcp
nvme_rdma
nvme_loop
EOF"

cp opt/kubectl-mayastor /usr/local/bin
kubectl label node --overwrite --all openebs.io/engine=mayastor
kubectl apply -k ./manifests/mayastor/
```

Now, the charts directory is as follows:

```shell
.
├── Kubefile
├── manifests
├── mayastor.sh
└── opt
```

Now everything is ready, you can start building the cluster image.

```shell
sealos build -t labring/openebs-mayastor:v1.0.4 .
```

When you run the cluster image, sealos will run the mayastor.sh script on the master node, but the shell command of sealos exec will run on all nodes. Finally, sealos will install openebs maystor storage on the master node.

```
sealos run labring/openebs-mayastor:v1.0.4
```

## sealos scp Example

The following example copies the bin file to all nodes.

Create a file named `Kubefile` for image building:

```shell
FROM scratch
COPY manifests manifests
COPY registry registry
COPY opt opt
CMD ["seal

os scp opt/ /opt/cni/bin/","kubectl apply -f manifests/kube-flannel.yml"]
```

The opt file is as follows:

```
$ ls opt/
bandwidth  bridge  dhcp  firewall  host-device  host-local  ipvlan  loopback  macvlan  portmap  ptp  sbr  static  tuning  vlan  vrf
```

Now everything is ready, you can start building the cluster image.

```shell
sealos build -t labring/flannel:v0.19.0 .
```

When you run the cluster image, sealos will copy the opt bin file to all nodes, then install flannel on the master node.

```
sealos run labring/flannel:v0.19.0
```

repository: cuisongliu/sealos

gha_language: Go

repo_name: cuisongliu/sealos


text:
[![Build Status](https://drone.io/github.com/Keats/kCalculator/status.png)](https://drone.io/github.com/Keats/kCalculator/latest)
# Leangains calories calculator
Simple tool to calculate calories and macro needed on rest and workout days depending on some choices:
  - calories cycle percentage
  - protein quantity
  - carbs and fat split

# Dev setup
If you want to run the app yourself, you can follow the steps below.
```bash
  npm install
  npm install -g grunt-cli
  npm install -g bower
  bower install
  grunt dev
```

# Nest
Improve the design, put the style directory as a submodule for easy reuse (snowflake repo)

repository: dwiangger/kCalculator

repo_name: dwiangger/kCalculator


text:
# Snapshots configuration

* [Local vs cloud storage](#local-vs-cloud-storage)
* [Storage method](#storage-method)
* [Storage credentials](#storage-credentials)
* [Storage container](#storage-container)
* [Backup interval](#backup-interval)
* [Backup retention](#backup-retention)

---

> See also the snapshot-specific [cap tasks](./REF-cap-tasks.md).

### Local vs Cloud Storage

Keeping backups on the local filesystem, while simpler to configure, does not make for a good disaster recovery scenario. To this end, Evolution now supports snapshots to a variety of cloud storage providers via [Apache Libcloud](https://libcloud.readthedocs.io/en/latest/).

A commented out default configuration (for local storage) can be found in your ansible group vars (`lib/ansible/group_vars/all` within your project):

```yml
# snapshots__method: local
# snapshots__credentials: ~
# snapshots__container: /home/deploy/backup/production.example.com
# snapshots__interval: 1d
# snapshots__retention: { hours: ~, days: 1, weeks: 1, months: 1, years: 1 }
# snapshots__retention_lag: true
```

To enable backups, uncomment _at least one_ of the above variables and reprovision your production remote. This will install the backup script and set up a cron job to run it regularly.

> Note: The script is run every hour, but new backups are created and old backups removed only as often as your configured `interval`.

Each backup consists of a sql dump of your database and a copy of your wordpress uploads directory, rolled into a gzipped tar archive.

### Storage Method

The default is to backup to the local filesystem, but you can use [any storage provider supported by libcloud](https://libcloud.readthedocs.io/en/latest/storage/supported_providers.html#supported-methods-storage). Just plug in the given provider's constant (case insensitive):

```yml
# Rackspace Cloud Files
snapshots__method: cloudfiles
# Google Cloud Storage
snapshots__method: google_storage
# Amazon Simple Storage Service
snapshots__method: s3
```

### Storage Credentials

For all methods but local storage, you _must_ supply authentication credentials for your cloud provider. You can do so with positional or named parameters, [as documented in the libcloud API](https://libcloud.readthedocs.io/en/latest/storage/api.html#libcloud.storage.base.StorageDriver):

```yml
# S3
snapshots__credentials:
  - "My AWS api key"
  - "My AWS secret key"
# Rackspace
snapshots__credentials:
  key: "My Rackspace username"
  secret: "My Rackspace api key"
```

### Storage Container

For local storage, the `container` serves as a path to the directory in which all backups are stored. For all other storage methods, it serves as [a container in libcloud's terminology](https://libcloud.readthedocs.io/en/latest/storage/index.html#terminology), wherein backups are stored as objects within the given container.

Typically, you would want to create a container (an S3 bucket, for example) in advance and then plug it into your group vars. That said, the backup script **will attempt to create the container if it does not already exist**. This may or may not succeed, depending on user permissions.

```yml
# Defaults to "$stage.$domain"...
snapshots__container: "local.example.com"
# Use the below named S3 bucket
snapshots__container: "My.S3.bucket.name"
```

### Backup interval

Evolution supports snapshot backups as often as _once an hour_, but the default is a more conservative _once a day_.

The interval should be a number followed by a letter indicating the unit of time, in hours, days, weeks, months or years:

```yml
# Every eight hours
snapshots__interval: 8h
# Every two days
snapshots__interval: 2d
# Every three weeks
snapshots__interval: 3w
# Every four months
snapshots__interval: 4m
# Every year
snapshots__interval: 1y
```

### Backup retention

Evolution supports a retention policy for your backups, loosely based on the [grandfather-father-son scheme](https://en.wikipedia.org/wiki/Backup_rotation_scheme#Grandfather-father-son_backup). This allows you to keep a variety of older and newer backups, without filling up your storage.

```yml
snapshots__retention:
  hours: ~
  days: 1
  weeks: 1
  months: 1
  years: 1
snapshots__retention_lag: true
```

The default retention policy (above) preserves one yearly, one monthly, one weekly, and one daily backup. The rest would be pruned over time, as more recent backups are created.

> Note: Retention can be _deliberately kept one interval unit back from the current time_ with the `retention_lag` variable, in order to retain a backup of each period. (This is turned _on_ by default!)
>
> For example, with the default interval of once a day, you would create a new backup on Sunday (the start of a new week) and be left with a "yearly" (from January 1st), a "monthly" (from the 1st of the current month), a previous "weekly" (from the previous Sunday), and _possibly_ a previous daily from Saturday.
>
> This happens because the retention calculation would believe it is still Saturday (back one "interval" day), in order to preserve the previous weekly backup. **Turning off the retention lag** would cause the previous Sunday's "weekly" to be removed, leaving you with just the yearly, monthly, and today.

This is best illustrated by running the backup script with the `--simulate` flag, which will display all backups that _would have been_ created and deleted for **one year ago from the current date and time**. (For brevity, only the retained backups are shown below.)

repository: evolution/wordpress

repo_name: evolution/wordpress


text:
---
layout: default
---

# 1995-08-22 - Why 64 bit keys?

## Header Data

From<EMAIL_ADDRESS>To<EMAIL_ADDRESS>Message Hash: 3678a51bd3d53f863e7bac5366711e4b0ddb7fe4cd6258704a2301a2d761e861

Message ID<EMAIL_ADDRESS>Reply To: _N/A_

UTC Datetime: 1995-08-22 00:18:13 UTC

Raw Date: Mon, 21 Aug 95 17:18:13 PDT

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>Date: Mon, 21 Aug 95 17:18:13 PDT
To<EMAIL_ADDRESS>Subject: Why 64 bit keys?
Message-ID<EMAIL_ADDRESS>MIME-Version: 1.0
Content-Type: text/plain

-----BEGIN PGP SIGNED MESSAGE-----

>Date: Sat, 19 Aug 1995 15:13:35 -0400
>From<EMAIL_ADDRESS>(Lucky Green)
>Subject: Re: 64 bit keys breakable by the NSA or just some random key length?

>I think the obvious conclusion would be because 64bits is crackable
>if need be and if you have the resources the goverment has. Not for
>routine monitoring of undesirables, but for those special cases
>where they don't want to expose their activities by requesting a
>warrant.

I think it's much more important to the powers that be (and that
eavesdrop) that a key of up to 64 bits includes DES, which means
that lots of system designers will use DES instead of (say) 3DES,
IDEA, or Blowfish.  It's virtually certain that NSA and others have
built keysearch machines for DES.  This gives NSA, et. al., a way
around the key escrow scheme when they want it.  Better yet, NSA
can tell the FBI and BATF and such agencies where to find the
technical papers on how to build one, without releasing any
highly-classified information--those agencies can hire someone to
build them one.  This also keeps NSA from having to dirty its hands
with law-enforcement surveilance.

Of course, it will be interesting to see whether pressure is
applied to keep people from offering "nonstandard" ciphers,
especially things like Blowfish and SEAL, which have key scheduling
algorithms that need a lot of memory and time. It's really only
practical to build keysearch machines for very commonly used
ciphers, and even then, it may be complicated. (For example,
imagine a DES variant whose key schedule required several
exponentiations modulo some 1024-bit prime.)

>- -- Lucky Green<EMAIL_ADDRESS>>   PGP encrypted mail preferred.

   --John Kelsey<EMAIL_ADDRESS> PGP 2.6 fingerprint = 4FE2 F421 100F BB0A 03D1 FE06 A435 7E36

-----BEGIN PGP SIGNATURE-----
Version: 2.6.2

iQCVAwUBMDgfl0Hx57Ag8goBAQFa0gP/azECjB06onhSYTvLjkM2I7y2tOpC2BaB
RACVMQn+Z5kVGaDM47eIM1TlRnIMlnEucuLryvqR3fMDCt6g90oDXe3rziWJedbH
PxXYqgkPu1MmRfep+JWrtQ4wWsXxbPa10spTDFa8vKlGDcoohWU0W5ypgr454tlh
KKPaC345vqQ=
=td/F
-----END PGP SIGNATURE-----

{% endraw %}
```

## Thread

+ Return to [August 1995](/archive/1995/08)

+ Return to "[JMKELSEY@delphi.com](/authors/jmkelsey_at_delphi_com)"

+ 1995-08-22 (Mon, 21 Aug 95 17:18:13 PDT) - Why 64 bit keys? -<EMAIL_ADDRESS>


text:
---
layout: post
title: Icehouse-Trove configuration using Mysql
date: 2014-10-11 13:07:33.000000000 +07:00
type: post
published: true
status: publish
categories:
- Tech
- News
tags:
- Icehouse
- Trove
meta:
  _publicize_pending: '1'
  _oembed_ec6ecc3490de9b1592d20960a4d0bc99: "{{unknown}}"
  _rest_api_published: '1'
  _rest_api_client_id: "-1"
  _wpas_skip_facebook: '1'
  _wpas_skip_google_plus: '1'
  _wpas_skip_twitter: '1'
  _wpas_skip_linkedin: '1'
  _wpas_skip_tumblr: '1'
  _wpas_skip_path: '1'
  _oembed_4eaed1c20a0d27412d4559fa1e82fb7e: "{{unknown}}"
  _oembed_17a922fa83b9690fa8a0689fde67c41b: "{{unknown}}"
  _oembed_ed4e45b1fd729e638effe1e89509216d: "{{unknown}}"
  _oembed_363f5a30450550939ae72e36aadd5358: "{{unknown}}"
  _oembed_5f80291c11c1f6b4dca134874fa9b93a: "{{unknown}}"
  _oembed_d8c2683daed5d910e9d988bcdf995dc8: "{{unknown}}"
author:
  login: vnstack
  email<EMAIL_ADDRESS>  display_name: vietstack
  first_name: Viet
  last_name: Stack
---

" I'm working with Database-As-A-Service project (Trove) of Openstack, I followed docs at docs.openstack.org. After getting failed 2-3 times, I have decided to try with another guide. I goodle-ed and realised that there is no working tutorial on the Internet. So now I am writing this article to provide step-by-step installation guide to get Openstack Trove working (at least It was working in my LAB :lol:) "

Link:

https://github.com/d0m0reg00dthing/Openstack-Icehouse-Trove

gha_language: HTML