text:
# @composi/create-refs

CreateRefs creates a cache for DOM elements. Because it uses a WeakMap internally for caching, the references to DOM elements are available for garbage collection when they are removed from the DOM. The cache is read-only, so you can not use a reference to try and change the node, such as changing an element'e class, etc.

CreateRefs is not for caching JavaScript data objects. For that check out `@composi/datastore`.

## Install

`CreateRefs` is already installed in any project created with `@composi/create-composi-app`. All you need to do is import it into your project:

```
import { CreateRefs } from '@composi/create-refs'
```

## New Instance

Make an instance of CreateRefs:

```javascript
const refs = new CreateRefs()
```
## Add a Node to Cache

To cache a node you need a refence to a node and a key. Keys are just a descriptive string. Each reference should have a unique key.

```javascript
refs.set('input', document.querySelector('input'))
```

## Get a Node from Cache

You can retreive a node from the cache by using the key you provided when you first cached it.

```javascript
// Set focus on a cache input element:
refs.get('input').focus()

// Get the input's value:
const value = refs.get('input').value
```

## Test if Node is Cached

You can test if a cache contais a node by passing its key to the `has` method:

```javascript
if (refs.has('input')) {
  console.log(`Input value is: ${refs.get('input').value}.`)
}
```

## Remove Node from Cache

You can remove a cached node. You use CreateRef's `delete` method and the key for the reference to delete:

```javascript
if (refs.has('input') {
  refs.delete('input')
})
```
Deleting a cached element reference does not affect the element in the DOM.

## Usage

To use CreateRefs with @composi/core you create an empty cache and then add a reference to a DOM element from witin an `onmount` handler:

```javascript
import { h, render } from '@composi/core'
import { CreateRefs } from '@composi/create-refs'

// Create a cache for DOM references:
const refs = new CreateRefs()

// Define a component:
function List({data}) {
  // Because this function is the handler for onmount,
  // which is registered on the input below,
  // it gets based a reference to the input when it is created.
  function buttonRef(input) {
    // Cache the input using the key 'input':
    refs.set('input', input)
  }
  // Access the cached input to get its value:
  function addItem() {
    const value = refs.get('input').value
    if (value) {
      // Add to list...
    }
  }
  return (
    <div>
      <p>
        <input type='text' onmount={buttonRef}/>
        <button onclick={addItem}>Add</button>
      </p>
      <ul>
        { /** define list item stuff here... */}
      </ul>
    </div>
  )
}
```

## CreateRefs vs Object

Using CreateRefs is not the same as simply storing a reference on an element on an object.s. For example, you could create an object called `refs` and store references to DOM elements on its:

```javascript
const refs = {}
refs.input = document.querySelector('input')
refs.input.focus()
const value = refs.input.value
// etc.
```
The problem with the above code is that if the input is part of a component that is rendered conditional, when the component is removed from the DOM, the object `refs` retains the reference to the input element, creating a memory leak. Using CreateRefs to store references to elements avoids this problem because its references are stored in a WeakMap. This allows the references to be garbage collected when the elements they point to no longer exist.

repository: composi/create-refs

repo_name: composi/create-refs


text:
# ROS reporter
A review of systems (ROS) is a gathering of targeted medical information such as symptoms from a patient. Reimbursement models push doctors to ask more and more particular sets of questions, consuming precious in-encounter time. In the interest of time, issues that are medically relevant or important to the patient may not be addressed6, creating an incomplete picture from which the doctor assesses and plans treatment.

The ROS Reporter is an interactive web application will allow the patient to submit responses in privacy and comfort outside the encounter, either at home before a visit or while waiting at the office. Some clinics and offices distribute ROS forms, either by paper or electronically to patients when they arrive at reception or by a nurse. These questionnaires have several deficiencies:

- They feel irrelevant. The patient answers in the negative for row after row of questions that are not related to the purpose of the visit. The forms are one-size-fits all.
- They are often tedious and inefficient. Paper questionnaires are often poorly designed and require manual entry into the EHR. Electronic questionnaires are often time consuming as they ask many sequential questions with negative responses.
- The data collected is insufficient. The doctor or nurse asks the relevant questions again, with multiple follow-up questions such as frequency, severity, and timing.

### Goals
- Improve communication between the patient and care team
- Improve the fidelity and relevance of information from the patient, by recording events and pains closer to relevant time and place (point of pain)
- Provide designs that minimize survey fatigue and maximize the collection of relevant data.
- Lower stress on the patient and improve the fidelity of data during transfers of care
- Provide language and accessibility support

### Components
- Web interface to identify symptoms and collect relevant info (onset, intensity, location, etc.). The questionnaire is responsive and intelligent, focusing on systems and lines of questions relevant to the patient’s conditions.
- Receipt for the patient in both plain English and medical language for sharing, easy reference, printing, etc.
- FHIR resources enumerating the captured conditions using standard coding schema. This is a first step in importing the data into a health record.

### Estimated Level of Effort
Design: 4 weeks, 1.0FTE
Development v1.0: 6 weeks, 1.0FTE

repository: goinvo/openPRO

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: goinvo/openPRO


text:
static-api
==========

A node module that reads a JSON file and generates a static folder structure that matches
the JSON to allow data end points for simple apps without the hassle of setting up your own server.

Inspired by the [Jekyll](http://jekyllrb.com/) approach to static website hosting. You can maintian your
'database' offline then run this script and push the changes to your live site.

## How to use

### The json file

Create a .json file that strucuture matches your desired API.

`my-api.json`

````json
{
    "artists": {
        "0123": {
            "id": "0123",
            "name": "alt-J",
            "albums": {
                "456": {
                    "id": "456",
                    "name": "An Awesome Wave",
                    "tracks": {
                        "1": {
                            "name": "intro",
                            "length": "2:37"
                        },
                        "2": {
                            "name": "Interlude I",
                            "length": "1:12"
                        }
                    }
                }
            }
        },
        "0743": {
            "id": "0743",
            "name": "The Antlers",
            "albums": {
                "457": {
                    "id": "457",
                    "name": "Burst Apart",
                    "tracks": {
                        "1": {
                            "name": "I Don't Want Love",
                            "length": "3:19"
                        }
                    }
                }
            }
        }
    }
}
````
### The code

#### Using command line

install static-api using npm

````
npm install static-api -g
````
Run in the command line like so
````
static-api -f example/data -j example/example.json
````

Where -f is the folder you would like the api to saved to and -j the path to the JSON file containing the structure

#### Using a node app

Include 'static-api' as a dependency in your package.json and create a
file a js file similar to the code below.

````js
var baseData = require('./my-api.json'), //load your json file
    path = require('path'),
    staticApi = require('static-api'); //load the module

var dataFolder = path.join(__dirname, 'data/');

new staticApi({
    outputFolder: dataFolder, //where the data will be stored
    object: baseData //the object to create the file structure from
});
````

### The result

After running the js file in the command line using: node myapp.js

This should result in a simlar structure to the following
````
/data/
...../my-api.json
...../artists/
............./artists.json
............./0123/
................../0123.json
................../albums/
........................./albums.json
........................./456/
............................./456.json
............................./tracks/
..................................../tracks.json
..................................../1/
....................................../1.json
..................................../2/
....................................../2.json
............./0743/
....etc..
````

So now if you hit the following URL from your application /data/artists/0123/albums/456/456.json you will get the following:
````json
{"id":"456","name":"An Awesome Wave","tracks":{"1":{"name":"intro","length":"2:37"},"2":{"name":"Interlude I","length":"1:12"}}}
````

You can now quickly produce a static API that you can use with your simple JavaScript app allowing you
to focus on doing what you do best: *creating awesome web apps or producing amazing prototypes.*

license: MIT

repository: benhughes/static-api

gha_language: JavaScript

repo_name: benhughes/static-api


text:
description: A simple tutorial on how to get started on evolving neural networks with Neataptic
authors: Thomas Wagenaar
keywords: evolution, machine-learning, neural-network, neuro-evolution, neat

Neuro-evolution is something that is fairly underused in the machine learning
community. It is quite interesting to see new architectures develop for
complicated problems. In this guide I will tell you how to set up a simple
supervised neuro-evolution process. If you want to do an unsupervised
neuro-evolution process, head over to the [NEAT](../neat.md) page.

### The training set
You always have to supply a training set for supervised learning. First of all,
you should normalize your data. That means you have to convert all your input and
output data to values within a range of `0` to `1`. If you are unsure how to do
this, visit the [Normalization](normalization.md) tutorial. Each training sample
in your training set should be an object that looks as follows:

```javascript
{ input: [], output: [] }
```

So an example of a training set would be (XOR):

```javascript
var myTrainingSet = [
  { input: [0,0], output: [0] },
  { input: [0,1], output: [1] },
  { input: [1,0], output: [1] },
  { input: [1,1], output: [0] }
];
```

### The network architecture
You can start off with _any_ architecture. You can even use the evolution process
to optimize already trained networks. However, I advise you to start with an empty
network, as originally described in the [NEAT](http://nn.cs.utexas.edu/downloads/papers/stanley.ec02.pdf)
 paper. The constructor of an empty network is as follows:

```javascript
var myNetwork = new Network(inputSize, outputSize);
```

So for the training set I made above, the network can be constructed as follows:

```javascript
var myNetwork = new Network(2, 1); // 2 inputs, 1 output
```

Now we have our network. We don't have to tinker around anymore; the evolution
process will do that _for_ us.

### Evolving the network
Be warned: there are _a lot_ of options involved in the evolution of a process.
It's a matter of trial and error before you reach options that work really well.
Please note that most options are optional, as default values have been configured.

Please note that the `evolve` function is an `async` function, so you need to wrap
it in an async function to call `await`.

The evolve function is as follows:

```javascript
yourNetwork.evolve(yourData, yourOptions);
```

Check out the evolution options [here](../architecture/network.md) and [here](../neat.md). I'm going to use the following options to evolve the network:

* `mutation: methods.mutation.FFW` - I want to solve a feed forward problem, so I supply all feed forward mutation methods. More info [here](../methods/mutation.md).
* `equal: true` - During the crossover process, parent networks will be equal. This allows the spawning of new network architectures more easily.
* `popsize: 100` - The default population size is 50, but 100 worked better for me.
* `elitism: 10` - I want to keep the fittest 10% of the population to the next generation without breeding them.
* `log: 10` - I want to log the status every 10 iterations.
* `error: 0.03` - I want the evolution process when the error is below 0.03;
* `iterations: 1000` - I want the evolution process to stop after 1000 iterations if the target error hasn't been reached yet.
* `mutationRate: 0.5` - I want to increase the mutation rate to surpass possible local optima.

So let's put it all together:

```javascript
await myNetwork.evolve(myTrainingSet, {
  mutation: methods.mutation.FFW,
  equal: true,
  popsize: 100,
  elitism: 10,
  log: 10,
  error: 0.03,
  iterations: 1000,
  mutationRate: 0.5
});

// results: {error: 0.0009000000000000001, generations: 255, time: 1078}
// please note that there is a hard local optima that has to be beaten
```

Now let us check if it _actually_ works:

```javascript
myNetwork.activate([0,0]); // [0]
myNetwork.activate([0,1]); // [1]
myNetwork.activate([1,0]); // [1]
myNetwork.activate([1,1]); // [0]
```

Notice how precise the results are. That is because the evolution process makes
full use of the diverse activation functions. It actually uses the [Activation.STEP](../methods/activation.md)
function to get a binary `0` and `1` output.

### Help
If you need more help, feel free to create an issue [here](https://github.com/wagenaartje/neataptic/issues)!

repository: childish-zamboni/bleepr

gha_license_id: MIT

repo_name: childish-zamboni/bleepr


text:
---
layout: post
title: "Lessons from releasing an album using AWS Lambda and Kinesis"
description: ""
category: post
tags: []
---

> Some of the most capable engineers I know are scared of AWS systems like Lambda and Kinesis. They are ‘magical’, use GUIs and are difficult to debug. I hope that this post-mortem, which runs through the challenges, can help people feel more comfortable using these tools when needed.

# Isn’t releasing an album a solved problem?

It’s 2016\. You may think music labels have a way to deliver you digital music. But, outside of iTunes, Spotify and Amazon, you can’t really buy an album by a major artist and get a bunch of audio files. What if an artist wants another option?

A few weeks ago, I was tasked with building an integrations system that could support delivering an email with link to a zip file to customers who buy an album online. Scale was a big concern but a 5 minute wait time for the email was not an issue. That said, there was a complex set of requirements:

*   Each purchase (“Order”) should translate into exactly one email for the user. (Note: The email system can dedupe these using an ID)
*   Music is delivered via a link to a zip file. The zip file is generated in an external system.
*   The system will only receive ‘valid’ orders that will not error in the zip file or email system due to invalid data.
*   During times of high traffic, the system should not fall down but slowing down is OK.
*   The system should not require ongoing maintenance.
*   The system should use Node/Javascript since the team has no familiarity with Ruby or Python.
*   The system must be built in under **5 working days**. (LOL music industry)

# Principals of an event driven AWS integrations system

Using AWS is truly another universe. Systems like Lambda, SNS and Kinesis are similar to systems you may have built or encountered as an engineer. Sadly, experience with similar systems is not enough. Being an ‘ecosystem’, AWS requires a lot of specific ecosystem knowledge. An example of ecosystem knowledge that has no real basis in logic is that SNS and Kinesis can trigger Lambda workers but SQS cannot.

I can’t list all that specific knowledge here, but I’ve found that keeping a few high level principals in mind helps when fumbling around with the miraiad of AWS services.

## 1\. Events should be replay-able

Replayability is key for a new system that could encounter unanticipated errors in production. Early on we knew this would be a requirement and so we wrote all code with replayablitly in mind.

For our album delivery system, ‘replayability’ means that we can execute a ‘cleanup’ script to re-run a selection of “Orders” through the system. The actual code for each worker is designed to handle a ‘rerun’ event. As the system runs, it updates a record in DynamoDb. That allows us to replay an order that has a Zip URL but errored sending the email —  it won’t generate a Zip URL, but will try to send the email again.

## 2\. Be a team player

With the power of an infinitely scaleable AWS system in your hands, it is easy to forget about your less powerful friends. Part of the job of a good integrations system is to make sure all systems stay up (and if they go down, that you can recover). If your system puts unanticipated traffic on another system — and that system goes down — you fail.

For this system, we rely on two external APIs with unknown traffic constraints. We need to understand those constraints and build a system that can throttle to ensure they stay up.

## 3\. Log all the things

Integration systems are very, VERY hard to understand. If you aren’t getting the result you expect, did you misconfigure something in the UI or did a worker error? If something is slow, what part of the system slow?

I highly recommend spending some time creating a CloudWatch dashboard for your project. Below is a screenshot of the one for this project. Note that each column corresponds to an individual service. The columns are ordered to match how order the data moves through the system (Ingester -> Kinesis…)

![](https://cdn-images-1.medium.com/max/1200/1*0yxLWdDSnUT3HdGly_UgIA.png)

# v0.1: Lambda + SNS

The first version of the system was based on one I had worked on at Citi Bike. We built a high throughput system for processing events from the Citi Bike system. The AWS setup went something like this:

> [Queue] > [ElasticBeanstalk app inside VPC] > SNS > Lambda [fork] Multiple SNS > Multiple Lambda (storage, tracking, sending to other systems)

This setup works great if you are going into Amazon infrastructure — but not out. If one system exceeds their provisioned load, the others will either throttle (dynamoDb) or scale up (Lambda, SNS) to meet demand.

For this music project. We did not need to be in a VPC, were not handling as many events and did not need to do as many things with each event. We could be a bit more lightweight:

> [Database of orders] > [Lambda fetching at 5 min interval] > SNS > Lambda that fetches Zip URL + sends email.

SNS ensures ‘at least once’ delivery but we unique in our external systems (noted above). The lambda workers can error gracefully when encountering duplicate events from SNS. No need to double check since the external systems provide those guarantees.

**Sounds like this will work! But lets try to break it.**

First lets check the exact throughput of all our systems. For inbound, the client believed that they could get 1,000 orders a minute or more during initial launch. Earlier, we had been informed that scale was not a problem for the email and zip url system. But, we decide to contact them directly to get exact numbers. The email system is fine but, we are informed that the zip url system can handle a maximum of 10 concurrent requests.

Generating each Zip url takes 3 consecutive API calls per url generated. In our initial tests, those consecutive calls take about 2 seconds total. That gives us a safe maximum of 5 concurrent lambda workers. Given that 2 second execution time, 1,000 orders a minute would translate into ~33 concurrent workers. UH OH!

SNS messages cannot be throttled and missed messages are dropped so, how can we throttle this system so that the Zip URL system does not go down?

# v0.2 Lambda + Kinesis

Throttling SNS is sadly, impossible. We could throttle the number of notifications we send in the first place, but then we would be building a queue. We need to look at other solutions and potentially rebuild the system.

My initial plan was to create system like Resque (where we could have a queue with a fixed number of workers) but using Amazon SQS. While investigating SQS, I stumbled on [a stack overflow post](/r/?url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F34678691%2Fhow-to-process-sqs-queue-with-lambda-function-not-via-scheduled-events) by Eric Hammond. Since SQS cannot drive lambda functions, he suggested using Kinesis to get the same result.

Unlike SQS, Kinesis streams can drive AWS Lambda functions. Kinesis streams let you specify how many AWS Lambda functions can be run in parallel (we used one worker per partition). So, we created a Kinesis with 5 partitions and that gave us 5 max concurrent lambda workers. But, there were some other issues we need to deal with.

For our purposes, the key difference between Kinesis-to-Lambda and SNS-to-Lambda is how the system handles errors.

*   SNS sends a notification to Lambda and does not retry if the lambda worker fails
*   Kinesis will retry failures as long as the data is still in Kinesis
*   Kinesis will [throttle if there are lots of failures](/r/?url=https%3A%2F%2Fforums.aws.amazon.com%2Fthread.jspa%3FmessageID%3D685885).

Our solution to those problems was to simply make sure that the lambda workers never errored, but instead saved everything to DynamoDb along the way. This way, we could have a separate worker that would find all ‘errored’ orders and retry them in a separate process.

## Launch Problems

Two interesting errors collaborated to make for a rocky launch. We received valid orders in countries that, due to music rights issues, we could not actually send a zip url. Earlier in the process, we had encountered and handled errors in the Zip URL system. The system would catch the error, flag the order as ‘errored’ and move on to the next order. However, the node library we used for interacting with the Zip URL generation service did not call the error callback. Instead threw a parse error which caused the lambda worker to error, and then caused Kinesis to retry the order infinitely. Then, since it continued to error, caused throttling across our whole system.

We were able to see these events in our metrics and had clear logs from our Lambda workers. The fix was quite simple once we directed our attention to solving it. We deployed the fix and then re-ran previous orders to ensure nothing was missed.

# ideas for v0.3

One of the most exciting technologies out right now is definitely API Gateway. That said, it isn’t something I felt I could learn and use within the time frame of this project. However, it does meet many of the requirements for the project such as replayability and throttling so might be an interesting exploration.

repository: zamiang/zamiang-dot-com

gha_language: CSS

repo_name: zamiang/zamiang-dot-com


text:
# docker-hhvm
Docker image of HHVM.

## Memcached Session Support
You can enable the `memcached` session handler at runtime by either using a Docker `--link` to a container running Memcached, or you can supply a list of servers in an environment variable. When HHVM starts, the settings will be written to `/etc/hhvm/php.ini` to enable Memcached based session storage. (If neither is used, standard file-based session storage remains the default.)

### Linked Docker Containers
You may link a Memcached container using the name `memcached`.
```bash
docker run -d --name foobar memcached
docker run -d --link foobar:memcached hhvm
```
### Environment variable
You may pass the `MEMCACHED` environment variable which should contain a list of Memcached hosts and ports.
```bash
docker run -d -e "MEMCACHED=<IP_ADDRESS>:11211,<IP_ADDRESS>:11211" hhvm
```

## CA Certificates
You can mount a volume to `/usr/local/share/ca-certificates` that contains any certificate authorities you wish to accept as trusted. Debian's `update-ca-certificates` is run before HHVM executes.

repository: appertly/docker-hhvm

repo_name: appertly/docker-hhvm


text:
---
layout: post
rel_link:  "7_1_38_patch1"
title:  "CMSSW_7_1_38_patch1"
date:   2019-04-11 15:45:28
categories: cmssw
relmajor: 7
relminor: 1
relsubminor: 38
relpatch: _patch1
---

# CMSSW_7_1_38_patch1
#### Changes since CMSSW_7_1_38:
[compare to previous](https://github.com/cms-sw/cmssw/compare/CMSSW_7_1_38...CMSSW_7_1_38_patch1)

1. [26359](http://github.com/cms-sw/cmssw/pull/26359){:target="_blank"}  from **@kpedro88**: Filter for semi-visible jet signal production [71X] `generators`  created: 2019-04-04 15:01:15 merged: 2019-04-06 17:07:42

#### CMSDIST Changes between Tags REL/CMSSW_7_1_38/slc6_amd64_gcc481 and REL/CMSSW_7_1_38_patch1/slc6_amd64_gcc481:
[compare to previous](https://github.com/cms-sw/cmsdist/compare/REL/CMSSW_7_1_38/slc6_amd64_gcc481...REL/CMSSW_7_1_38_patch1/slc6_amd64_gcc481)

repository: cms-sw/ReleaseNotes

repo_name: cms-sw/ReleaseNotes


text:
# Breaking Change Information

Details and migration information regarding breaking changes will be provided here after the 1.0 release.
Preview changes will be less detailed due to low usage.

## Preview Breaking Change Summary

### 0.8.0

* `UnmanagedMemory` can no longer be un-disposed by calling its `Grow` method.

### 0.7.0

* Renamed several instructions to match the published WebAssembly specification.
  This project started over a year before the final specification was released so some of the names it used became out of date.
* `ElementType` member `AnyFunction` has been renamed to `FunctionReference` to align with the spec.
* `Function` member `Type` was changed from a public field to a property.
* The `Type` and `ValueType` types were renamed to `WebAssemblyType` and `WebAssemblyValueType`, respectively, to avoid conflicts with the popular `System` namespace.
* .NET Standard 2.0 is now the only build produced.
  This means .NET Framework consumers must be 4.7.2 or higher.
  Infrastructure is still in place to support builds as old as .NET 4.5 and .NET Standard 1.1 if a compelling use case arises, but this may eventually be removed otherwise.

### 0.5.0

* `WebAssembly.Table`'s `Type` property was renamed to `Definition` to better reflect its purpose.
  This will likely be renamed again during the big 1.0 final restructuring.

### 0.4.0

* Most types associated with compilation, including the `Compile` class itself, have been moved to the `WebAssembly.Runtime` namespace.
* Importing was changed from compile time (using raw `MethodInfo`) to instantiation time (using delegates).
* The `ModuleName` and `FieldName` properties of `RuntimeImport` have been removed in favor of a more JavaScript-like dictionary-of-dictionaries-of-imports at instantiation time.

repository: Jacarte/dotnet-webassembly

repo_name: Jacarte/dotnet-webassembly


text:
# Component life cycle

There is a default life cycle for javascript conponents. The documentation of that can be found at [https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Using_the_lifecycle_callbacks](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#Using_the_lifecycle_callbacks)

## Callbacks in lively

Lively does some things differently in order to enable live development. So here is a table of the callbacks in lively, what their original name is and when they are called.

| callback in lively | callback original | what it does |
|---|---|----|
| onAttachedCallback() | connectedCallback() | invoked, when the element is appended to a document-connected component. That will also happen each time the element is moved. |
| onDetachedCallback() | disconnectedCallback() | Invoked each time the custom element is disconnected from the document's DOM |
| adoptedCallback() | adoptedCallback() | Invoked each time the custom element is moved to a new document. |
| attributeChangedCallback() | attributeChangedCallback() | invoked, when one of the observed Attributes is changed. For this to work, the custom element's class must implement ```static get observedAttributes() { return [<attribute 1>, ..., <attribute n>] }```

## How I think we could use it

I think the attributeChangedCallback is interesting.

In the tab view: an element within a tab view could observe the style.display value and when it is set to "none" stop animations and so on.

To enforce a life cycle on our own we could create new attributes and listen to them in a sort of super class. Here a (probably not good) example of how something like that could look like:

```javascipt

class Diagram extends Morph {
  async initialize() {}

  static get observedAttributes() {
    return {["attached", "visible"]}
  }

  attributeChangedCallback() {
    let changedAttribute = //TODO
    let value = this[changedAttribute]

    if (changedAttribute === "visible") {
      if (value == true) {
        this.onVisible()
      } else {
        this.onInvisible()
      }
    } else if (changedAttribute === "attached") {
      if (value == true) {
        this.onAttached()
      } else {
        this.onDetached()
      }
    }
  }

  onVisible() {
    //subclass responsibility
  }

  onInvisible() {
    //subclass responsibility
  }

  onAttached() {
    //subclass responsibility
  }

  onDetached() {
    //subclass responsibility
  }

}

```

Note: making attached with this is a bad idea as the attachedCallback already exists!


text:
## 0.4.2

### New Queries

* Added a new medium-precision query, `cpp/comma-before-misleading-indentation`, which detects instances of whitespace that have readability issues.

### Minor Analysis Improvements

* The "Unterminated variadic call" (`cpp/unterminated-variadic-call`) query has been tuned to produce fewer false positive results.
* Fixed false positives from the "Unused static function" (`cpp/unused-static-function`) query in files that had errors during compilation.

repository: github/codeql

branch_name: refs/heads/main

gha_language: CodeQL

repo_name: github/codeql


text:
# Changelog
All notable changes to this project will be documented in this file.

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

## [4.2.1] - 2020-04-06
### Fixed
- Fixed rules' reorder to avoid order collisions by updating `auth0-source-control-extension-tools`

## [4.2.0] - 2020-03-28
- When importing SAML database connections, support client name in the `options.idpinitiated.client_id` property.
- When exporting SAML database connections, convert client ID to client name.

## [4.1.0] - 2020-03-28
- When exporting a mailgun email provider, a placholder api key will be included in the export..

## [4.0.3] - 2020-03-18
- Programmatic usage will not complain about args. #215

## [4.0.2] - 2020-02-28
- Included Deploy CLI version number in User-Agent header.
- If no command line arguments are passed, the usage statement will be printed.

## [4.0.1] - 2020-02-05
### Fixed
- Fixed import and export errors when roles and hooks are not available
### Updated
- Update `auth0-source-control-extension-tools`

## [4.0.0] - 2020-01-29
### Added
- Add support for Hooks and Hook Secrets
- Update `auth0`, `auth0-extension-tools`, `auth0-source-control-extension-tools`, and `js-yaml`

## [3.6.7] - 2020-01-08
### Fixed
- Fixed a crash when no roles are present in a tenant during an export

## [3.6.5] - 2019-12-19
### Added
- Add readonly flag `remove_stale_idp_attributes`

## [3.6.4] - 2019-12-04
### Updated
- Update `https-proxy-agent` and `js-yaml`

## [3.6.3] - 2019-11-04
### Added
- Add `AUTH0_API_MAX_RETRIES` support

## [3.6.2] - 2019-10-18
### Fixed
- Fix mapping for passwordless email connection template

## [3.6.1] - 2019-09-27
### Removed
- Removed `--verbose` option

## [3.6.0] - 2019-08-26
### Updated
- Update `auth0-extension-tools`
### Fixed
- Clear empty descriptions on roles

## [3.5.0] - 2019-08-14
### Added
- Ability to exclude connections and databases (AUTH0_EXCLUDED_CONNECTIONS & AUTH0_EXCLUDED_DATABASES)
### Fixed
- Excludes for yaml import

## [3.4.0] - 2019-07-15
### Added
- Load email template for passwordless email connection from external html file #124
- Load custom_login_page template for client from external html file #138

## [3.3.2] - 2019-07-11
### Updated
- pin minor version of<EMAIL_ADDRESS>
## [3.3.1] - 2019-06-13
### Fixed
- `allowed_clients`, `allowed_logout_urls`, `allowed_origins` and `callbacks` properties of the `client` can no longer be exported as `null`

## [3.3.0] - 2019-04-22
### Added
- Support for roles and permissions export and import

## [3.2.0] - 2019-04-12
### Changed
- Secrets (`rules configs` and databases `options.configuration`) can no longer be exported

## [3.1.3] - 2019-04-03
### Added
- Clearing empty tenant flags on `import`

## [3.1.2] - 2019-03-22
### Added
- Consistent property sorting for yaml dump #108 #61 #82

## [3.1.1] - 2019-03-15
### Fixed
- Exit status code on error #107

## [3.1.0] - 2019-03-14
### Added
- `AUTH0_EXCLUDED_CLIENTS` option has been added to the config. Works similar to `AUTH0_EXCLUDED_RULES` and `AUTH0_EXCLUDED_RESOURCE_SERVERS`. #102

## [3.0.2] - 2019-03-12
### Fixed
- Remove empty `flags` property from tenant settings #104

## [3.0.1] - 2019-03-04
### Fixed
- fix readonly `flags.enable_sso`

## [3.0.0] - 2019-03-04
### Added
Options added to the config:
- `INCLUDED_PROPS` - enables export of properties that are excluded by default (e.g. `client_secret`)
- `EXCLUDED_PROPS` - provides ability to exclude any unwanted properties from exported objects

### Changed
- `--strip` option has been removed from `export` command. Now **IDs will be stripped by default**. `AUTH0_EXPORT_IDENTIFIERS: true` or `--export_ids` can be used to override.

## [2.3.3] - 2019-03-04
### Fixed
- backport readonly `flags.enable_sso`

## [2.3.2] - 2019-03-02
### Changed
- set `enable_sso` and `sandbox_version` as readonly properties
- alias `export = dump` and `import = deploy` for programmatic usage

## [2.3.1] - 2019-02-27
### Changed
- convert non-integer `session_lifetime` to minutes #95
- update `auth0-source-control-extension-tools`
  - Fix email provider export
  - Process empty arrays of databases

## [2.3.0] - 2019-02-21
### Changed
- Empty arrays in the `tenant.yaml` (`clients: []`) will now lead to deleting all relevant records from the tenant. #89
- Update environment variable explanation in READMEs. #90
- Sanitize file and folder names. #92

## [2.2.5] - 2019-02-04
### Changed
- Fix for using the wrong proxy reference. #80

## [2.2.4] - 2019-01-17
### Changed
- Fix various schema validation issues. auth0-extensions/auth0-source-control-extension-tools PRs #52 thru #57

### Added
- Added 'name' prop to pages examples #76

## [2.2.0] - 2018-11-28
### Changed
- Update package dependency which contains security vulnerabilities.


text:
# Longest Increasing Subsequence

https://practice.geeksforgeeks.org/problems/longest-increasing-subsequence-1587115620/1

Given an array of integers, find the length of the longest (strictly) increasing subsequence from the given array.

Example 1:

Input:
N = 16
A[]={0,8,4,12,2,10,6,14,1,9,5
     13,3,11,7,15}
Output: 6
Explanation:Longest increasing subsequence
0 2 6 9 13 15, which has length 6
Example 2:

Input:
N = 6
A[] = {5,8,3,7,9,1}
Output: 3
Explanation:Longest increasing subsequence
5 7 9, with length 3
Your Task:
Complete the function longestSubsequence() which takes the input array and its size as input parameters and returns the length of the longest increasing subsequence.

Expected Time Complexity : O( N*log(N) )
Expected Auxiliary Space: O(N)

Constraints:
1 ≤ N ≤ 10^5
0 ≤ A[i] ≤ 10^6

**Solution :**

https://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/

repository: aadhityasw/Competitive-Programs

repo_name: aadhityasw/Competitive-Programs


text:
# SQLcl Scripts and Notes

While SQLcl ships with a bash script 'sql', I have found it more reliable to create a custom script.

Sometimes the stock sql script finds the Oracle Java installation rather than my local java installaion, even when the local one is first in the PATH.

Ironically SQLcl will not work with the Java found in any current installations of Oracle, as SQLcl requires Java 1.8+

## Java Command Line

This is the default command line for a local Java found in PATH:

```java
java -Djava.awt.headless=true -Dapple.awt.UIElement=true -Xss10M -Djava.net.useSystemProxies=true -client -cp /usr/share/sqlcl/lib/extensions/*:/usr/share/sqlcl/lib/oracle.sqldeveloper.sqlcl.jar: oracle.dbtools.raptor.scriptrunner.cmdline.SqlCli
```

## Security

I have been experimenting with haveged, /dev/random and /dev/urandom and how it can delay java logins.
(google this if unfamiliar with it)

To avoid possible delays in due to current state of these, I added the following to the command as I am not so concerned about Oracle security on this test box

```java
-Djava.security.egd=file:/dev/./urandom -Dsecurerandom.source=file:/dev/./urandom
```
The system I am working on never has any real data, and I am the only user.

The use of /dev/urandom is not really recommended for production use.

## Complete command

```java
java -Djava.security.egd=file:/dev/./urandom -Dsecurerandom.source=file:/dev/./urandom -Djava.awt.headless=true -Dapple.awt.UIElement=true -Xss10M -Djava.net.useSystemProxies=true -client -cp /usr/share/sqlcl/lib/extensions/*:/usr/share/sqlcl/lib/oracle.sqldeveloper.sqlcl.jar: oracle.dbtools.raptor.scriptrunner.cmdline.SqlCli
```

## Bash Script sqlcl

```bash
#!/bin/bash

: 'COMMENT' <<-COMMENT

I have been experimenting with haveged, /dev/random and /dev/urandom and how it can delay java logins.
To avoid possible delays in due to current state of these, /dev/urandom specified on cmdline as I am not so concerned about Oracle security on this test box
ie. There is never any real data in any of the databases and no one but me has access

COMMENT

SQLCL_HOME='/usr/share/sqlcl'

java -Djava.security.egd=file:/dev/./urandom -Dsecurerandom.source=file:/dev/./urandom -Djava.awt.headless=true -Dapple.awt.UIElement=true -Xss10M -Djava.net.useSystemProxies=true -client -cp ${SQLCL_HOME}/lib/extensions/*:${SQLCL_HOME}/lib/oracle.sqldeveloper.sqlcl.jar: oracle.dbtools.raptor.scriptrunner.cmdline.SqlCli "$@"
```

repository: jkstill/SQLcl

gha_language: Shell

repo_name: jkstill/SQLcl


text:
# ShareX Media Server

_ShareX Media Server_ is an app made to support sharing images, files, and text snippets from [ShareX](https://getsharex.com/), built using [Laravel](https://laravel.com/), [Livewire](https://laravel-livewire.com/), and [TailwindCSS](https://tailwindcss.com/).

> Files and Text snippets are not yet supported, but will be supported in the near future.

## Table of Content

- [Prerequisites](#prerequisites)
- [Installing ShareX Media Server](#prerequisites)
  - [Installing Laravel](#installing-laravel)
  - [Setting up queue workers](#setting-up-queue-workers)
  - [Setting up application assets](#setting-up-application-assets)
  - [Default login credentials](#default-login-credentials)
- [Setting up ShareX](#setting-up-sharex)
  - [Creating an API token](#creating-an-api-token)
  - [Custom ShareX Uploader](#custom-sharex-uploader)
- [Changelog](#changelog)
- [Contributing](#contributing)
- [License](#License)

## Prerequisites

- Apache2 / Nginx
- [Yarn](https://yarnpkg.com/)
- [Composer](https://getcomposer.org/)
- Node >= v10.15
- PHP >= v7.3
  - BCMath PHP Extension
  - Ctype PHP Extension
  - JSON PHP Extension
  - Mbstring PHP Extension
  - OpenSSL PHP Extension
  - PDO PHP Extension
  - Tokenizer PHP Extension
  - XML PHP Extension
  - GD PHP Extension

## Installing ShareX Media Server

### Installing Laravel

The app utilizes [Composer](https://getcomposer.org/) for installing the PHP dependencies, and [Yarn](https://yarnpkg.com/) for installing the node dependencies, to get started you'll first need to clone down the repository.

    git clone https://github.com/Senither/ShareX-Media-Server.git .

Next go into the `ShareX-Media-Server` folder, first we'll setup the PHP side of the project, to do this install all the dependencies using [Composer](https://getcomposer.org/)

    composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev

Then rename and setup your environment variables by renaming the `.env.example` file to `.env` and adding in your settings.

Next we'll need a unique application key, Laravels artisan helper makes this super easy, just run:

    php artisan key:generate

We're now ready to migrate our database, this will create all the tables required for the application.

    php artisan migrate

Next we'll need to make sure that the application can read all the required files, and write to the places where files will be generated later when the app is in-use, the easiest way to do this is by setting the storage and bootstrap cache directories to permission level 777.

    chmod -R 777 storage
    chmod -R 777 bootstrap/cache

Now we'll need to setup our cronjobs for the application, this will allow the app to run tasks like the cleanup task outside of the users request, so we can ensure files are deleted when they should be, this can be done by setting up a cronjob to run the `artisan schedule:run` command, start by opening the crontab file.

    crontab -e

Next, add a new cron command at the bottom of the file that runs every minute.

    * * * * * php /path/to/your/ShareX-Media-Server/artisan schedule:run

### Setting up queue workers

Next, we'll need to set up a supervisor to run and manage our queues, the queues are used for generating thumbnails, and processing other tasks that would otherwise take awhile to be completed, start by installing the supervisor package:

    sudo apt-get install supervisor

> You can skip this step if you have set the `QUEUE_CONNECTION` environment variable in the `.env` file to `sync`, setting it to `sync` will run the tasks that would otherwise have been queued right as they're called.

Supervisor configuration files are typically stored in the `/etc/supervisor/conf.d` directory. Within this directory, you may create any number of configuration files that instruct supervisor how your processes should be monitored. For example, let's create a `media-server-worker.conf` file that starts and monitors a `queue:work` process:

```ini
[program:media-server-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path/to/your/ShareX-Media-Server/artisan queue:work --sleep=3 --tries=5
autostart=true
autorestart=true
user=<username>
numprocs=2
redirect_stderr=true
stdout_logfile=/path/to/your/ShareX-Media-Server/worker.log
stopwaitsecs=3600
```

In this example, the `numprocs` directive will instruct Supervisor to run two `queue:work` processes and monitor all of them, automatically restarting them if they fail, you should be fine with a single process if the site is being hosted for a small number of people. You should replace the `<username>` with the username of the account that should run the queued jobs.

Once the configuration file has been created, you may update the Supervisor configuration and start the processes using the following commands:

```
sudo supervisorctl reread

sudo supervisorctl update

sudo supervisorctl start media-server-worker:*
```

The entire server side should now be setup and ready to be used!

### Setting up application assets

Next we'll need to build all of the front-end resources so users can view and use the website, this can be done using [Yarn](https://yarnpkg.com/).

    yarn install

This will install all the node modules required to build our assets, if Yarn is not installed you can use `npm install` instead, after all the node modules are installed we can build our assets.

    yarn prod

This will build and compile all our assets for a production environment, different environment builds can also be used, like `dev` for development mode, or `watch` for watch mode, which will re-build all the assets anytime any changes are made to the files.

The entire app should now be setup!

### Default login credentials

You can try visit the site in your browser, if everything is setup correctly you should be presented with a login screen, you can login using the credentials below as an admin user.

- **Username:**<EMAIL_ADDRESS>- **Password:** password

You can also edit the `config/fortify.php` file and uncomment `Features::registration()` on line 135 to enable user registration on the site, however do note that this means anyone can make an account, users created through the registration form are regular users and won't have access to the control panel, however they can upload images, files, and text snippets through the API using ShareX.

## Setting up ShareX

### Creating an API token

Before you start, you'll first need to create an API token that can be used with ShareX requests, the API token is used to validate your image, file, and text snippet uploads, to ensure you're actually allowed to upload files.

To create an API token you can click on your account name in the navigation in the top right of the app, and then click on the `API Tokens` menu item, this should move you to a page where you can create your own token, from there give the token a name, and make sure that you tick the upload permissions so the API token has the permissions to upload files to the media server.

![ShareX Media Server - Creating an API token](ShareX-create-api-token.png 'ShareX Media Server - Creating an API token')

After clicking on `Create` you'll get a popup with your newly created API token, make sure to copy it so you have it for later, since it won't ever be shown to you again.

### Custom ShareX Uploader

To setup a custom ShareX uploader you can navigate to: _Destinations_ -> _Custom Uploader Settings_ in the ShareX app.

From there create a new custom uploader, to setup everything we have to do a few things.

1. Set the request method to `POST`.
2. Set the URL to the root of your media server, followed by the API endpoint for the type of uploader you're setting up, example `/api/images` for images.
3. Add an `Authorization` header to the request, and set the value to `Bearer <your API token>`
4. Set the "File from name" value to match what you're uploading, for images it would be `image`.
5. Finally, click on the `response` tab, select the JSON option and set the URL to `$json:resource_url$`, this will select the resource URL being generated by the API during the upload and make it available to you so you can copy it to your clipboard.

It should all look something like this.

#### Request page

![ShareX - Custom Uploader Request](ShareX-custom-uploader-request.png 'ShareX - ShareX - Custom Uploader Request')

#### Response page

![ShareX - Custom Uploader Response](ShareX-custom-uploader-response.png 'ShareX - ShareX - Custom Uploader Response')

## Changelog

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

#### License

The ShareX Media Server open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).

repository: LouisHacking/ShareX-Media-Server

repo_name: LouisHacking/ShareX-Media-Server


text:
# Modular inverses

<!-- TOC -->

- [1. What is an inverse?](#1-what-is-an-inverse)
- [2. What is a modular inverse?](#2-what-is-a-modular-inverse)
- [3. How to find a modular inverse](#3-how-to-find-a-modular-inverse)

<!-- /TOC -->

## 1. What is an inverse?

Recall that a number multiplied by its inverse equals `1`. From basic arithmetic we know that:

- The inverse of a number `A` is `1/A` since `A * 1/A = 1` (e.g. the inverse of `5` is `1/5`)
- All real numbers other than `0` have an inverse
- Multiplying a number by the inverse of `A` is equivalent to dividing by A (e.g. `10/5` is the same as `10 * 1/5`)

## 2. What is a modular inverse?

In **modular arithmetic** we do not have **a division operation**. However, we do have **modular inverses**.

- The **modular inverse** of `A (mod C)` is `A^-1`
- `(A * A^-1) ≡ 1 (mod C)` or equivalently `(A * A^-1) mod C = 1`
- Only the numbers coprime to `C` (numbers that share no prime factors with `C`) have a modular inverse (mod `C`)

## 3. How to find a modular inverse

A naive method of finding **a modular inverse** for `A (mod C)` is:

- step 1. Calculate `A * B mod C` for `B` values `0` through `C-1`
- step 2. The **modular inverse** of `A mod C` is the `B` value that makes `A * B mod C = 1`

Note that the term `B` mod `C` can only have an integer value `0` through `C-1`, so testing larger values for `B` is redundant.

repository: lsieun/learn-cryptography

repo_name: lsieun/learn-cryptography


text:
# Startup-Manager
It's a simple program that forces other programs to run, even if they are closed

![Main Window](images/Startup-Manager.png)

## Usage
Download and run the latest version:
[Latest version](https://github.com/ProDev2/Startup-Manager/releases/latest)

## Configuration
After starting the program once there will be a config.txt file within the same folder.
**Changes to this file will be applied on the next program start!**

![Config File](images/Startup-Manager_Config.png)

> The 'update_interval' is set in milliseconds. (1 second = 1000 milliseconds).

> If you disable the exit option you have to force close the program via task manager.

## Registry Manager
By using the registry manager within the program you can add the program to the registry of your computer. By doing so the program will start on boot up.

> If you move the program in your file system make sure to start the program once afterwards. This will ensure that the path in the registry is set to the right location.

## Important
It is not recommended to start the program twice. To close it right click the little notification item in your taskbar and hit 'Exit'
(if that option in't disabled in the 'config.txt' file).

## Adding a new task
To add a program to the list hit 'Add' in the bottom right corner of the Startup-Manager's main window. In the following dialog window you can choose a name for the new list entry. After clicking 'Ok' you can choose a process which should be started once in a while. You can also press 'Cancel' and fill in the empty fields ('<empty>') afterwards by clicking on them.

> When choosing a process from the list make sure that the program you're searching for is currently running.

![Process / Task selector](images/Startup-Manager_Task_Chooser.png)

## Details
#License Copyright (C) by Pascal Gerner
```
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

gha_language: C#


text:
---
layout: page
title: Hi, I'm Josh
subtitle: welcome to my online resume
use-site-title: true
---

I'm a biomedical engineer with a particular interest in imaging and instrumentation. I recently graduated from the University of Waterloo with a B.ASc in Systems Design Engineering. I'm looking for a full time role working with friendly people and interesting technology.

Most recently, I worked for [Dr. Chris Macgowan](http://www.sickkids.ca/AboutSickKids/Directory/People/M/christopher-macgowan-staff-profile.html) as a medical imaging engineer at the Hospital for Sick Children. Previously, I worked and as a researcher in Professor [Edith Law's lab](http://edithlaw.ca/) on the [CrowdEEG project](http://crowdeeg.ca/).

For my full work history, please see my [resume](pdfs/Josh_Bradshaw_CV.pdf). My [projects page](projects) showcases my academic and personal projects. The best way to reach me is by [email](mailto:#joshbradshaw11@gmail.com). I'm also on [Linkedin](https://github.com/JoshBradshaw) and [Github](https://github.com/JoshBradshaw).


text:
# Analysis keywords

| Keyword | Default Value | Allowed value | Description |
| --- | --- | --- | --- |
|`kinship_output_file` | Kinship_Output_File.txt | true/false | OpenMendel generated output file with table of kinship coefficients |
|`repetitions` | 1 | Integer | Repetitions for sharing statistics |
|`xlinked_analysis` | false | beelean| Whether markers are on the X chromosome |
|`compare_kinships` | false | boolean | Whether we want to compare theoretical vs empiric kinship |
|`kinship_plot` | "" | User defined file name | A user specified name for a plot comparing theoretical and empiric kinship value |
|`z_score_plot` | "" | User defined file name |  A user specified name for a plot of fisher's z statistic.  |
|`grm_method` | MoM | GRM, MoM, Robust | Method used for empiric kinship calculation. Defaults to `MoM`, but user could choose the more common `GRM` or Robust GRM methods instead. (**Warning:** Based on our experience, Fisher's z score is very unreliable if the GRM method is used for rare (maf < 0.2) snps) |
|`maf_threshold` | 0.01 | Real number between 0 and 1 | The minor allele frequency threshold for the GRM computation |
|`deviant_pairs` | false | Integer less than $n(n+1)/2$ | Number of top deviant pairs (theoretical vs empiric kinship) the user wants to keep |

## See also

+ [MendelBase documentation](https://openmendel.github.io/MendelBase.jl/#keywords-table) for general keywords common to most analysis package
+ [Old MendelKinship documentation](https://openmendel.github.io/MendelKinship.jl/)

gha_language: Julia


text:
---
title: toc-lib-pattern-local-first-offlineable
tags: [lib, local-first, pattern, toc]
created: 2021-08-25T15:50:00.635Z
modified: 2021-09-04T14:03:39.046Z
---

# toc-lib-pattern-local-first-offlineable

# guide

- search: local-first, local first, offline first

- ref
  - https://github.com/arn4v/offline-first

- local-first + realtime协作的示例
  - https://github.com/gongojs/project
  - https://github.com/a-type/lo-fi
# popular
- tuple-database /219Star/NALic/202209/ts
  - https://github.com/ccorcos/tuple-database
  - 依赖fs-extra, lodash, fractional-indexing
  - The architecture of this database draws inspiration from a bunch of different places (although, primarily from FoundationDb).
  - 👉🏻 The local-first, "end-user database" database.
  - 👉🏻 All queries are reactive.
  - 👉🏻 ✨ Schemaless — schemas are enforced by the application, not the database.
  - 👉🏻 Asynchronous or Synchronous, Persisted or In-Memory Storage
  - Transactional read/writes written in TypeScript.
  - 👉🏻 Directly read/write indexes with the ability to index graph/relational queries.
    - The logic we've written here for the tuple-database code is exactly what any SQL database is doing under the hood.
  - Suitable for frontend state management.
  - https://github.com/maccman/tuple-playground

- tinybase /1.4kStar/MIT/202212/ts/NoDeps
  - https://github.com/tinyplex/tinybase
  - https://tinybase.org/
  - TinyBase is a smart new way to structure your local app data
  - 基于自定义TinyQL(类似SQL)实现查询
  - 基于checkpoint实现undo
  - 基于hlc crdt实现冲突处理
  - Familiar concepts of tables, rows, and cells, and schematization to model your data domain.
  - Flexibly reactive to reconciled updates, so you only spend cycles on the data that changes.
  - Indexing, metrics, relationships - and even an undo stack for your app state!
  - Easily sync your data to local or remote storage, and use idiomatic bindings to your React UI.
  - Powerful query engine to select, join, filter, group, sort and paginate data - reactively.
    - The Queries object lets you query data across tables, with filtering and aggregation - using a SQL-adjacent syntax called `TinyQL`.
  - A Persister object lets you save and load Store data to and from different locations, or underlying storage types.

- evolu /101Star/GPLv3/202210/ts
  - https://github.com/evoluhq/evolu
  - https://www.evolu.dev/
  - React Hooks library for local-first software with end-to-end encrypted backup and sync using SQLite and CRDT
  - writing local-first software has been challenging because of the lack of libraries and design patterns. I personally failed several times, and that's why I created Evolu.
  - Evolu architecture is almost a clone of James Long CRDT for mortals. Rewritten and improved
  - Evolu uses end-to-end encryption and generates strong and safe passwords for you.
    - Evolu sync and backup server see only timestamps. Nothing more.
    - We plan to do at least two security audits.
  - Evolu is not pure P2P software. For syncing and backup, there needs to be a server.
  - Evolu CRDT has no support for transactions because CRDT transactions are still an unsolved issue.

- dxos /20Star/MIT/202306/ts
  - https://github.com/dxos/dxos
  - https://www.dxos.org/
  - TypeScript implementation of the DXOS protocols, SDK, and toolchain.
  - A decentralized alternative to the commercial cloud for privacy preserving software.

- redux-offline /6.1kStar/202012/MIT/js
  - https://github.com/redux-offline/redux-offline
  - https://github.com/redux-offline/offline-side-effects /202101/ts
  - Build Offline-First Apps for Web and React Native
  - Persistent Redux store for Reasonaboutable Offline-First applications, with first-class support for optimistic UI.
  - Use with React, React Native, or as standalone state container for any web app.
  - 🤔 没必要执着于寻找已有的offline方案，使用 persist + crdt 也可以实现协作，甚至普通的协作同步

- turtleDB /443Star/MIT/201809/js
  - https://github.com/turtle-DB/turtleDB
  - https://turtle-db.github.io/
  - turtleDB is a JavaScript framework and in-browser database for developers to build offline-first, collaborative web applications.
  - It provides a developer-friendly API to access an in-browser database built on top of IndexedDB.
  - It comes with built in document versioning and automatic server synchronization when paired with our back-end package tortoiseDB
  - https://github.com/turtle-DB/tortoiseDB
    - NodeJS server and mongoDB wrapper for clients to sync to when using turtleDB.

- SingleFile /9.5kStar/AGPLv3/202211/js
  - https://github.com/gildas-lormeau/SingleFile
  - a Web Extension (and a CLI tool) compatible with Chrome, Firefox to save a complete web page into a single HTML file.
  - 比较了各种格式：singleFile、mhtml、webarchive、html-folder
  - For security reasons, SingleFile is sometimes unable to save the image representation of canvas and snapshots of video elements.
  - [File name doesn't match the page title when saving a page](https://github.com/gildas-lormeau/SingleFile/issues/1106)
    - Please, uncheck "save pages in background" in options (Misc) than you will get the correct title name!
  - https://github.com/gildas-lormeau/SingleFileZ
    - a fork of SingleFile that allows you to save a webpage as a self-extracting HTML file
  - https://github.com/gildas-lormeau/SingleFile-Lite /js
    - This is the new version of SingleFile compatible with the long-awaited Manifest V3!

- https://github.com/aphrodite-sh/aphrodite
  - Aphrodite is a schema layer whose first goal is to make P2P & Local-First software as easy to develop as traditional client-server software.
  - You can think of Aphrodite as an ORM of sorts that is designed for the needs of Local-First applications and P2P data transfer.
  - everything in Aphrodite begins with a schema. This schema encodes the application's data

- local-first /191Star/202104/js/inactive
  - https://github.com/jaredly/local-first
  - This aims to eventually be a fully-featured solution for managing, syncing, and storing application data, in a way that works offline, and collaboratively.
  - Currently implemented
    - a hybrid logical clock (blog post, code)
    - a nested object CRDT (code)
    - a rich-text CRDT (code, example integration with quill, visualization of the data structure)
  - [Local-first database: RxDB + PouchDB](https://jaredforsyth.com/posts/local-first-database-rxdb-pouchdb/)

- IDBSideSync /8Star/MIT/202104/ts
  - https://github.com/clintharris/IDBSideSync
  - https://idbsidesync-todo-demo.vercel.app/
  - IDBSideSync is an experimental JavaScript library that makes it possible to sync browser-based IndexedDB databases using CRDT concepts
  - 基于浏览器的同步方案可参考更成熟的remoteStorage
  - As your app makes CRUD calls to its IndexedDB database, IDBSideSync proxies/intercepts those calls and records the operations to a log (the "oplog").
  - IDBSideSync will upload the client's oplog entries (CRDT state mutation messages) to the remote data store using the registered plugins, and also download other client's oplog entries
  - A hybrid logical clock (i.e., time + counter) is maintained among the clients to help figure out which operations "win" if more than one exists for the same database store/record/property.

- https://github.com/logux/client
  - https://logux.io/
  - Logux is a new way to connect client and server.
  - Instead of sending HTTP requests (e.g., AJAX and GraphQL) it synchronizes log of operations between client, server, and other clients.
  - Logux and WebSocket client/server framework to make:
    - Logux has features inspired by CRDT to resolve edit conflicts between users. Real-time updates to prevent conflicts
    - Logux combines WebSocket with modern reactive client architecture. It synchronizes Redux actions between clients and servers, and keeps the same order of actions.
    - Offline-first for the next billion users or New York City Subway. Logux saves Redux actions to IndexedDB and has a lot of features to merge changes from different users.
    - Compatible with modern stack: Redux, Vuex and pure JS API, works with any back-end language and any database.

- https://github.com/anita-app/anita /ts/暂不支持同步
  - https://anita-app.com/
  - Anita is a private, no-server, powerful and fully customizable data management solution
  - Your data is stored on your computer in a JSON file and/or on a remote database of your choice: flexible, open & no lock-in. Stay independent from servers that will go away, sooner or later.
  - full support for CRUD operations on data stored
  - locally in the browser's IndexedDB (with Dexie.js)
  - locally in a JSON or SQLite file in the device FS

- https://github.com/nornagon/autowiki /automerge
  - Autowiki is a tool for creating networked documents.
  - Autowiki is a local-first app: you own all the data you put into it, and your data never leaves your own machine unless you want it to.
  - Autowiki uses automerge under the hood to resolve edit conflicts automatically.

- https://github.com/hoodiehq/hoodie
  - Hoodie lets you build apps without thinking about the backend and makes sure that they work great independent of connectivity.
  - https://github.com/hoodiehq/hoodie-app-tracker

- https://github.com/local-first-web/state /automerge
  - A Redux-based state container for local-first software, offering seamless synchronization using Automerge CRDTs. (Formerly known as fish Cevitxe).
  - @localfirst/state is an automatically replicated Redux store that gives your app offline capabilities and secure peer-to-peer synchronization superpowers.
  - https://github.com/local-first-web/auth
  - https://github.com/local-first-web/relay

- rxdb /17.6kStar/Apache2/202206/ts
  - https://github.com/pubkey/rxdb
  - https://rxdb.info/
  - 依赖rxjs7
  - A fast, offline-first, reactive database for JavaScript Applications
  - a NoSQL-database for JavaScript Applications like Websites, hybrid Apps, Electron-Apps and NodeJs.
  - 👉🏻 RxDB is not a self contained database.
    - It is a wrapper around another database that implements the `RxStorage` interface.
    - At the moment you can either use `PouchDB` or `Dexie.js` or `LokiJS` as underlaying storage.
    - Each of them respectively has it's own adapters that can be swapped out, depending on your needs.
    - For example you can use and IndexedDB based storage in the browser, and an SQLite storage in your hybrid app

- https://github.com/milahu/browserforge
  - run github + github-pages + codesandbox in your browser, offline-first - CONCEPT
# local-first-examples
- https://github.com/kndwin/jikan
  - https://jikan-murex.vercel.app/
  - I've been using the T3 stack but below is my new option
    - https://twitter.com/kndwindev/status/1675367708437692416
    - @DrizzleOrm - typesafety with relational queries

- https://github.com/crutchcorn/offline-first-react-app
  - a proof-of-concept for an offline-first React app that interacts with a server.

- hamsterbase /158Star/MIT/202211/ts/仅开源sdk
  - https://github.com/hamsterbase/hamsterbase
  - https://hamsterbase.com/zh/
  - 一个本地优先的网页存档应用。 a self-hosted, local-first web archive application.
  - 本地部署 + 完全离线 + 点对点同步（马上发布了）
  - 储存、管理和预览 HTML, MHTML and Webarchive 格式的文档。
  - 对保存的页面进行高亮、批注。
  - 开源 SDK，目前免费。
  - Full Text Search
  - Open source SDK
  - 推荐使用 SingleFile 保存 html 页面
  - 支持点对点同步，测试时可用本地同步官网，api填写 https://hamsterbase.onrender.com，结尾无/
  - https://github.com/carytrivett

- https://github.com/unigraph-dev/unigraph-dev
  - A local-first and universal knowledge graph, personal search engine, and workspace for your life.

- https://github.com/digidem/mapeo-desktop
  - An offline map editing application for indigenous territory mapping in remote environments.
  - It uses mapeo-core for offline peer-to-peer synchronization of an OpenStreetMap database, without any server.
  - The map editor is based on iDEditor.
  - The app is built with Electron.
# offline
- https://github.com/localForage/localForage
  - Offline storage, improved. Wraps IndexedDB, WebSQL, or localStorage using a simple but powerful API.

- https://github.com/hoodiehq/hoodie
  - A generic backend with a client API for Offline First applications

- https://github.com/lana-k/sqliteviz
  - Sqliteviz is a single-page offline-first PWA for fully client-side visualisation of SQLite databases or CSV files.
  - Instant offline SQL-powered data visualisation in your browser
  - run SQL queries against a SQLite database and create Plotly charts and pivot tables based on the result sets

- https://github.com/cloudpeers/tlfs  /rust
  - offers a stack to write applications as productively as when using state-of-the-art cloud-based architectures, while providing the Seven Ideals for Local-First Software

- https://github.com/delta-db/deltadb /201602/js/inactive
  - DeltaDB is an offline-first database designed to talk directly to clients and works great offline and online.
  - I have decided to suspend development of DeltaDB for the following reasons:
  - last-write-wins policy is nice when starting a new project as it is automatic, but other conflict resolution policies that force the user to manually resolve the conflict, like CouchDB’s revision protocol, have become more of the standard in the offline-first world.
  - Building a DB that scales and is Building a DB that scales and is distributed over many nodes, takes a lot of work. distributed over many nodes, takes a lot of work.
# collab
- https://github.com/YousefED/Matrix-CRDT
  - Use Matrix as a backend for local-first applications with the Matrix-CRDT Yjs provider.

- https://github.com/rocicorp/replicache
  - Realtime Sync for Any Backend Stack
# exploring
- https://github.com/drifting-in-space/plane /202212/rust
  - Plane is a container orchestrator for ambitious browser-based applications.
  - Plane implements an architecture we call session backends.
  - Plane assigns a unique subdomain to each instance, through which it proxies HTTPS/WebSocket connections. When all inbound connections to a container are dropped, Plane shuts it down.
  - [Session Backends](https://driftingin.space/posts/session-lived-application-backends)
# more
- https://github.com/cwise89/react-detect-offline
  - Components that track offline and online state. Render certain content only when online (or only when offline).

- https://github.com/dxxzst/OfflineMap
  - 基于MySQL + Node.js + Leaflet的离线地图展示，支持百度、谷歌、高德、腾讯地图

- https://github.com/madipta/offline-first
  - Sample offline first using Nx monorepo, React, RxDb, NestJs, Prisma, GraphQl, PostgreSql

- https://github.com/rjmackay/offline-db-preso
  - Offline-first data sharing talk for nz.js(con)

- https://docs.amplify.aws/lib/datastore/getting-started/q/platform/js/
  - allows you to start persisting data locally to your device with DataStore, even without an AWS account.
  - Amplify DataStore provides a programming model for leveraging shared and distributed data without writing additional code for offline and online scenarios, which makes working with distributed, cross-user data just as simple as working with local-only data.


text:
+++
Talk_date = ""
Talk_start_time = ""
Talk_end_time = ""
Title = "Infrastructure as Code with ARM Templates and why it matters for developers"
Type = "talk"
Speakers = ["peter-orneholm"]
+++

Keeping the infrastructure and configuration consistent between different environments can be a nightmare. You need to make sure that all services and servers are setup and configured in the same way and in too many cases this is done manually, and manual steps eventually turns into inconsistency. ARM templates is here to change thatng the infrastructure and configuration consistent between different environments can be a nightmare. You need to make sure that all services and servers are setup and configured in the same way and in too many cases this is done manually, and manual steps eventually turns into inconsistency. ARM templates is here to change that.

Azure ARM templates allows you to provision your applications using a declarative template written in JSON. This enables you to take full advantage of the cloud by upgrading existing environments or creating new ones in a fast and consistent manner.

repository: KrisBuytaert/devopsdays-web

gha_license_id: NOASSERTION

repo_name: KrisBuytaert/devopsdays-web


text:
# Route Parser

- Input an Angular project
- Steps through the project to grab all of the routing files
- Parse out the information for the `Routes` object useful for isomorphic routing purposes
- Output the routes used by the angular project
- Routes use CSharp regex instead of angular endpoint variables

----------------------------

# Usage

```sh
~$ dotnet run "/Path/To/Angular_Project"
```

---------------------------------

# Advantages
- Information from the project will give back ends and API applications the knowledge to send proper 404 errors


text:
# conversation-proxy

Initial attempt to set up a CORSifying proxy for the Watson Conversation API. Probably not a great idea but please do open an issue for any glaring errors or omissions!

## Deploy to Bluemix

Can be deployed to Bluemix using the following command:

`cf push conversation-proxy`

repository: jt-nti/conversation-proxy

repo_name: jt-nti/conversation-proxy


text:
.NET Core 2.1 Typescript/React/MobxJS boilerplate
========

This is a simple project to get an ASP.NET Core site, using .NET Core, Typescript, React and MobxJS.

## Setup

If you're running VS2017, make sure you have the ASP.NET Core and Node workloads. Open the solution and build it. It should automatically pull down the dependencies from nuget and NPM, run Webpack, and build the solution.

If you're running .NET Core CLI on Windows, Mac, or Linux, make sure you install the .NET Core 2.0+ SDK and node/npm. Then, run the following...

- `cd DotnetTypescript`
- `npm install`
- `dotnet build`
- `dotnet run`


text:
# Introduction

## Interfaces

An interface is a type containing members defining a group of related functionality. It distances the uses of a class from the implementation allowing multiple different implementations or support for some generic behavior such as formatting, comparison or conversion.

The syntax of an interface is similar to that of a class or struct except that methods and properties appear as the signature only and no body is provided.

```csharp
public interface ILanguage
{
    string LanguageName { get; set; }
    string Speak();
}

public class ItalianTaveller : ILanguage, ICloneable
{
    public string LanguageName { get; set; } =  "Italiano";

    public string Speak()
    {
        return "Ciao mondo";
    }

    public object Clone()
    {
        ItalianTaveller it = new ItalianTaveller();
        it.LanguageName = this.LanguageName;
        return it;
    }
}
```

All operations defined by the interface must be implemented.

Interfaces can contain instance methods and properties amongst other members

## Ordering

To allow an object to be compared to another object, it must implement the `IComparable<T>` interface.
This interface has a single method that needs to be implemented: `int CompareTo(T other)`.

There are three possible return values for the `CompareTo` method:

- Value smaller than zero: the current object is smaller than the other object.
- Value greater than zero: the current object is greater than the other object.
- Value is zero: the current object is equal to the other object.

repository: exercism/csharp

repo_name: exercism/csharp


text:
# Topic

> 日本與美國的速食菜單有何不同？ (Japan vs USA | How different are fast food menus?)

> And the thing is, if you switch those ideal body weights between countries, you might find them rejected by the other country's media as too fat, or too thin. There are many reasons for this stark difference in weight, and of course one of them is portion size.

> 重點是，當你在國家間切換這些對於理想體重的要求，你可能會被他國媒體形容為太胖或太瘦而嫌棄，對於體重出現如此顯著的差異有著許多原因，當然其中一個原因是餐點份量

[![Image](https://cdn.voicetube.com/assets/thumbnails/ZW4jOlyj-sM.jpg)](https://www.youtube.com/embed/ZW4jOlyj-sM?rel=0&showinfo=0&cc_load_policy=0&controls=1&autoplay=1&iv_load_policy=3&playsinline=1&wmode=transparent&start=73&end=90&enablejsapi=1&origin=https://tw.voicetube.com&widgetid=1)

Host: Priscilla

Today issue: Did you know that the food portion in Japan and in America are different?

[Host record](https://cdn.voicetube.com/tmp/everyday_records/priscilla.huang/2511.mp3)

## learning points
1. _
	* switch [swɪtʃ] (v.) 改變；轉移
          - We switch to the plan B the moment, we found out the plan A wasn't going to work.
            + 當我們發現計畫A無法運作，就立刻切換到計畫B。
	* swear [swɛr] (v.) 發誓
          - He swore to God that he would not give up before success .
            + 他向上帝發誓他在成功之前不會放棄。

2. _
	* ideal [aɪˋdiəl] (adj.) 理想的、完美的
           - I would never become the ideal husband that she wants.
             + 我永遠不會成為她想要的理想丈夫。
	* idealistic [aɪ͵dɪəlˋɪstɪk] (adj.) 理想主義的
          - She is often criticized for being too idealistic.
             + 她經常因過於理想主義而受到批評。

3. _
	* reject [rɪˋdʒɛkt] (v.) 拒絕、抵制
          - His idea was rejected by most of his employees but he still did it anyway.
             + 他的想法遭到了大多數員工的拒絕，但無論如何他仍然這樣做。
	* reiterate [riˋɪtə͵ret] (v.) 重做；重申
          - He reiterated his innocence and pleaded not guilty.
             + 他重申了自己的清白，並表示無罪。
             + reiterated => say again.
             + pleaded not guilty. => 宣示無罪，　pleaded guilty => 認罪

4. _
	* stark [stɑrk] (adv.) 明顯地；突出地
          - His appearance is in stark contrast to his behaviors.
            + 他的外表與他的行為形成鮮明對比。
            +  in stark contrast to => 形成對比(極大的)
	* stare [stɛr] (v.) 盯，凝
          - He kept staring at me angrily but I don't know what I did wrong?
            + 他憤怒地一直盯著我，但我不知道我做錯了什麼？
            + staring + at => 盯著

5. _
	* portion [ˋporʃən] (n.) (食物等的)一份
          - The food portion of this restaurant is too generous for me I could never finish it.
            + 這家餐廳的食物部分對我來說太慷慨了，我永遠無法完成它。
	* proportion [prəˋporʃən] (n.) 比例；比率
          - The proportion of immigrants and emigrants has become a major issue.
            + 移入的移民和移出的移民比例已成為一個主要問題。
            + immigrants 移入的移民
            + emigrants 移出的移民
            + a major issue => 重大議題


text:
# FEP+ input and results for Syk dataset

This folder contains:
- protein structure prepared with Maestro Protein Preparation Wizard.
- ligands.sdf: 3D conformations of the ligands in the binding site. Prepared with LigPrep.
- results_5ns.csv: FEP+ results with sampling time of 5ns.
- results_20ns.csv: FEP+ results with sampling time of 20ns.
- results_edges_5ns.csv: FEP+ results for individual edges with sampling time of 5ns.
- results_edges_20ns.csv: FEP+ results for individual edges with sampling time of 20ns.

repository: cando-developers/fep-benchmark

repo_name: cando-developers/fep-benchmark


text:
## Alexa Adapter for Bot Builder v4 .NET SDK

### Build status
| Branch | Status | Recommended NuGet package version |
| ------ | ------ | ------ |
| master | [![Build status](https://ci.appveyor.com/api/projects/status/b9123gl3kih8x9cb?svg=true)](https://ci.appveyor.com/project/garypretty/botbuilder-community) | [![NuGet version](https://img.shields.io/badge/NuGet-1.0.100-blue.svg)](https://www.nuget.org/packages/Bot.Builder.Community.Adapters.Alexa/) |

### Description

This is part of the [Bot Builder Community Extensions](https://github.com/garypretty/botbuilder-community) project which contains various pieces of middleware, recognizers and other components for use with the Bot Builder .NET SDK v4.

The Alexa Adapter allows you to add an additional endpoint to your bot for Customer Alexa Skills. The Alexa endpoint can be used
in conjunction with other channels meaning, for example, you can have a bot exposed on out of the box channels such as Facebook and
Teams, but also via an Alexa Skill.

Incoming Alexa Skill requests are transformed, by the adapter, into Bot Builder Activties and then when your bot responds, the adapter transforms the outgoing Activity into an Alexa response.

A basic sample bot is available [here](https://github.com/BotBuilderCommunity/botbuilder-community-dotnet/tree/master/samples/Alexa%20Adapter%20Sample).

The adapter supports a broad range of capabilities for Alexa Skills, including;

* Support for voice based Alexa bots
* Support for the available display directives for Echo Show / Spot devices, with support for the new Fire Tablets coming very soon
* Support for Alexa Cards
* Support for Audio / Video directives
* Integration libraries (similar to those for the Bot Framework Adapter), allowing for the bot to also have its own middleware pipeline for Alexa
* TurnContext extensions allowing the developer to;
    * Send Alexa Progressive Updates
    * Explicitly define and attach an Alexa Card to the response (alternatively Bot Builder Hero / Signin cards can be automatically converted if attached to the outgoing activity)
    * Specify Alexa RePrompt speech / text
    * Add to / access Alexa Session Attributes (similar to TurnState in Bot Builder SDK)
    * Check if a device supports audio or audio and display
    * Retrieve the raw Alexa request
    * A new method to allow the user to call the relevant API and access user details (with skill permission), such as address
* Validation of incoming Alexa requests (required for certification)
* Middleware to automatically translate incoming Alexa requests into different types of activities

### Installation

Available via NuGet package [Bot.Builder.Community.Adapters.Alexa](https://www.nuget.org/packages/Bot.Builder.Community.Adapters.Alexa/)

Install into your project using the following command in the package manager;
```
    PM> Install-Package Bot.Builder.Community.Adapters.Alexa
```

### Sample

Basic sample bot available [here](https://github.com/BotBuilderCommunity/botbuilder-community-dotnet/tree/master/samples/Alexa%20Adapter%20Sample).

### Usage

* [Adding the adapter and skills endpoint to your bot](#adding-the-adapter-and-skills-endpoint-to-your-bot)
    * [.NET Core MVC](#net-core-mvc)
	* [.NET Core](#net-core-non-mvc)
* [Default Alexa Request to Activity mapping](#Default-Alexa-Request-to-Activity-mapping)
* [Default Activity to Alexa Response mapping](#Default-Activity-to-Alexa-Response-mapping)
* [Alexa TurnContext Extension Methods](#TurnContext-Extension-Methods)
    * [Session Attributes](#Session-Attributes)
	* [Adding an Alexa Card to a response](#Adding-an-Alexa-Card-to-a-response)
	* [Progressive Responses](#Progressive-Responses)
	* [Get entire Alexa Request Body](#Get-entire-Alexa-Request-Body)
	* [Get the user's device address](#Get-the-alexa-device-address)
	* [Add Directives to response](#Add-Directives-to-response)
	* [Check if device has Display or Audio Player support](#Check-if-device-has-Display-or-Audio-Player-support)
* [Alexa Middleware for transforming incoming Intent requests to Message activities](#Alexa-IntentRequest-to-MessageActivity-Middleware)
* [Alexa Show / Spot Display Support](#Alexa-Show-/-Spot-Display-Support)
* [Automated Translation of Bot Framework Cards into Alexa Cards](#Automated-Translation-of-Bot-Framework-Cards-into-Alexa-Cards)

### Adding the adapter and skills endpoint to your bot

Currently integration is available for .NET Core applications, with or without MVC.
When using the non-MVC approach, a new endpoint for your Alexa skill is created at '/api/skillrequests'.
e.g. http://www.yourbot.com/api/skillrequests.  This is the endpoint that you should configure within the Amazon Alexa
Skills Developer portal as the endpoint for your skill.

When using MVC, you configure your chosen endpoint when creating your controller which will handle your skill requests. An example of this can be seen [in the .NET Core MVC secton below](#.net-core-mvc).

#### .NET Core MVC

You can use the Alexa adapter with your bot within a .NET Core MVC project by registering the AlexaHttpAdapter.
When registering the AlexaHttpAdapter, you can add middleware and also set settings, such as if a session should
end by default or what happens when an error occurs during a bot's turn.

```cs
	services.AddSingleton<IAlexaHttpAdapter>((sp) =>
	{
	    var alexaHttpAdapter = new AlexaHttpAdapter(validateRequests: true)
	    {
	        OnTurnError = async (context, exception) =>
	        {
	            await context.SendActivityAsync("Sorry, something went wrong");
	        },
	        ShouldEndSessionByDefault = true,
	        ConvertBotBuilderCardsToAlexaCards = false
	    };

	    return alexaHttpAdapter;
	});
```

Once you have registered your the AlexaHttpAdapter in Startup.cs, you can then create a normal
MVC controller to provide an endpoint for your bot and process requests to them using the Alexa adapter.

```cs

    [Route("api/skillrequests")]
    [ApiController]
    public class BotController : ControllerBase
    {
        private readonly IAlexaHttpAdapter _adapter;
        private readonly IBot _bot;

        public BotController(IAlexaHttpAdapter adapter, IBot bot)
        {
            _adapter = adapter;
            _bot = bot;
        }

        [HttpPost]
        public async Task PostAsync()
        {
            await _adapter.ProcessAsync(Request, Response, _bot);
        }
    }

```

#### .NET Core (non-MVC)

An example of using the Alexa adapter with a bot built on Asp.Net Core (without MVC). The implementation of the
integration layer is based upon the same patterns used for the Bot Framework integration layer.
In Startup.cs you can configure your bot to use the Alexa adapter using the following;

```cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAlexaBot<EchoBot>(options =>
        {
            options.AlexaOptions.ValidateIncomingAlexaRequests = true;
            options.AlexaOptions.ShouldEndSessionByDefault = false;
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseDefaultFiles()
            .UseStaticFiles()
            .UseAlexa();
    }

```

### Default Alexa Request to Activity mapping

When an incoming request is receieved, the activity sent to your bot is comprised of the following values;

* **Channel ID** : "alexa"
* **Recipient Channel Account** : Id = Application Id from the Alexa request, Name = "skill"
* **From Channel Account** : Id = User Id from the Alexa request, Name = "user"
* **Conversation Account** : Id = "{Alexa request Application Id}:{Alexa Request User Id}"
* **Type** : Request Type from the Alexa request. e.g. IntentRequest, LaunchRequest or SessionEndedRequest
* **Id** : Request Id from the Alexa request
* **Timestamp** : Timestamp from the Alexa request
* **Locale** : Locale from the Alexa request

For incoming requests of type IntentRequest we also set the following properties on the Activity

* **Value** : DialogState value from the Alexa request

For incoming requests of type SessionEndedRequest we also set the following properties on the Activity

* **Code** : Reason value from the Alexa request
* **Value** : Error value from the Alexa request

The entire body of the Alexa request is placed into the Activity as Channel Data, of type skillRequest.

### Default Activity to Alexa Response mapping

The Alexa adapter will send a response to the Alexa skill request if the outgoing activity is of type MessageActivity or EndOfConversation activity.

If the actvity you send from your bot is of type EndOfConversation then a response is sent indicating that the session should be ended, by setting the the ShouldEndSession flag on the ALexa response to true.

If the activity type you send from your bot is of type MessageActivity the following values are mapped to an Alexa response object;

* **OutputSpeech Type** : Set to 'SSML' if activity.Speak is not null. Set to 'PlainText' if the activity.Text property is populated but the activity.Speak property is not.
* **OutputSpeech SSML** : Populated using the value of activity.Speak if it is not null.
* **OutputSpeech Text** : Populated using the value of activity.Text if it is not null.

* **ShouldEndSession** : Defaults to false. However, setting the InputHint property on the activity to InputHint.IgnoringInput will set this value to true and end the session.

### TurnContext Extension Methods

#### Session Attributes

Alexa Skills use Session Attributes on the request / response objects to allow for values to be persisted accross turns of a conversation.  When an incoming Alexa request is receieved we place the Session Attributes on the request into the Services collection on the TurnContext.  We then provide an extension method on the context to allow you to add / update / remove items on the Session Attributes list. Calling the extension method AlexaSessionAttributes returns an object of type Dictionary<string, string>. If you wanted to add an item to the Session Attributes collection you could do the following;

```cs
    context.AlexaSessionAttributes.Add("NewItemKey","New Item Value");
```

#### Adding an Alexa Card to a response

You can attach a card to your response to be shown in the Alexa app or on a Fire tablet.

```cs

var card = new AlexaCard
{
    Type = AlexaCardType.Simple,
    Title = "Card title",
    Content = "This is the content to be shown on the card"
};

context.AlexaSetCard(

```

The following types of card are supported;

* Simple (populate the title / content properties)
* Standard (populate the title / text / image properties)
* LinkAccount
* AskForPermissionConsent (populate the Permissions property with a list of permission types)

#### Progressive Responses

Alexa Skills allow only a single primary response for each request.  However, if your bot will be running some form of long running activity (such as a lookup to a 3rd party API) you are able to send the user a holding response using the Alexa Progressive Responses API, before sending your final response.

To send a Progressive Response we have provided an extension method on the TurnContext called AlexaSendProgressiveResponse, which takes a string parameter which is the text you wish to be spoken back to the user. e.g.

```cs
    context.AlexaSendProgressiveResponse("Hold on, I will just check that for you.");
```

The extension method will get the right values from the incoming request to determine the correct API endpoint / access token and send your Progressive response for you.  The extension method will also return a HttpResponseMessage which will provide information as to if the Progressive Response was send successfully or if there was any kind of error.

***Note: Alexa Skills allow you to send up to 5 progressive responses on each turn.  You should manage and check the number of Progressive Responses you are sending as the Bot Builder SDK does not check this.***

#### Get entire Alexa Request Body

We have provided an extension method to allow you to get the original Alexa request body, which we store on the ChannelData property of the Activity sent to your bot, as a strongly typed object of type skillRequest.  To get the request just call the extension method as below;

```cs
    skillRequest request = context.GetskillRequest();
```

***Note: If you call this extension method when the incoming Activity is not from an Alexa skill then the extension method will simply return null.***

#### Get the Alexa device address

You can access the address the user has set against their device (or in some cases the address stored against their Amazon account).

You can call the AlexaGetUserAddress TurnContext extension to retrieve an AlexaAddress object.

If the skill doesn't have the permission to access the address, a UnauthorizedAccessException will be thrown.
In this case you can send a card to the user's Alexa app to prompt them to grant the permissions, as shown below.

```cs

AlexaAddress alexaAddress = null;

try
{
    alexaAddress = await context.AlexaGetUserAddress();
}
catch (Exception ex)
{
    if (ex is UnauthorizedAccessException)
    {
        await context.SendActivityAsync("Sorry, Looks like I dont have permission to see your address. "
		+ " I have sent a card to your Alexa app to ask for the permission");

        context.AlexaSetCard(new AlexaCard()
        {
            Type = AlexaCardType.AskForPermissionsConsent,
            Permissions = new string[] { "read::alexa:device:all:address" }
        });
    }

    alexaAddress = null;
}

```

#### Add Directives to response

Add objects of type IAlexaDirective to a collection used when sending outgoing requests to add directives to the response.  This allows you to do things like
controlling the display on Echo Show / Spot devices.  Classes are included for Display and Hint Directives.

```cs
	dialogContext.Context.AlexaResponseDirectives().Add(displayDirective);
```

#### Check if device has Display or Audio Player support

```cs
    dialogContext.Context.AlexaDeviceHasDisplay()

	dialogContext.Context.AlexaDeviceHasAudioPlayer()
```

### Alexa IntentRequest to MessageActivity Middleware

By default, incomign requests from Alexa are transformed into Activity objects, where the type of Activity is the same as the incoming Alexa request type. e.g. IntentRequest or LaunchRequest.
You can use the AlexaIntentRequestToMessageActivityMiddleware middleware to automatically transform Alexa Intent requests into MessageActivities, so that you can more easily build bots that work accross multiple channels, including Alexa.

You can add the middleware to your bot with the following line;

```cs

options.Middleware.Add(
	new AlexaIntentRequestToMessageActivityMiddleware(transformPattern: RequestTransformPatterns.MessageActivityTextFromSinglePhraseSlotValue));

```

You can specify one of two transform patterns;

* **MessageActivityTextFromSinglePhraseSlotValue** - This option will look for a single Alexa intent slot called 'Phrase' and set the contents of this slot as the Text property for the generated Activity.

* **MessageActivityTextFromIntentAndAllSlotValues** - This slot will generate MessageActivity text from the name of the Intent and all identified slots. e.g. "Intent='YourIntentName' SlotName1='SlotValue' SlotName2='SlotValue'"

Optionally you can also provide your own function to transform the incoming Alexa request and determine how your generate the MessageActivity yourself.

Note: Any incoming requests with built in Amazon Intents will simply have the name of the Intent set as the Message activity text. e.g.

```cs

if (activity.Text == "AMAZON.CancelIntent")
{
	...
}

```

This middleare will only transform incoming custom IntentRequests, for other types of request such as LaunchRequest or SessionEndedRequest will geneate activities of that type, which you can then check within your code. e.g.

```cs

if (activity.Type == AlexaRequestTypes.LaunchRequest)
{
	...
}

```

### Alexa Show / Spot Display Support

Display Directives to support devices with screens, such as the Echo Show and Spot, can be added to your bots response.  A class for each of the currently supported templates
exists within the Alexa.Directives namespace.  A context extension method allows you to add directives to the services collection which will then be used by the Alexa Adapter
when processing outgoing activities and will add the appropriate JSON to the response.

***Note: You should also use the AlexaDeviceHasDisplay() extension method on the ITurnContext object to check if the Alexa device that has sent the incoming
request has a display - this is because if you send a display directive to a device without a display it will cause an error and not simply be ignored.***

``` cs

            var displayDirective = new DisplayDirective()
            {
                Template = new DisplayRenderBodyTemplate1()
                {
                    BackButton = BackButtonVisibility.HIDDEN,
                    Title = "Claim Update",
                    TextContent = new TextContent()
                    {
                        PrimaryText = new InnerTextContent()
                        {
                            Text = "<font size=\"7\"><b>Good news!</b></font>",
                            Type = TextContentType.RichText
                        },
                        SecondaryText = new InnerTextContent()
                        {
                            Text = "<br/><font size=\"3\">This is your Secondary Text",
                            Type = TextContentType.RichText
                        },
                        TertiaryText = new InnerTextContent()
                        {
                            Text = "This is tertiary text - this time it is plain text",
                            Type = TextContentType.PlainText
                        }
                    },
                    Token = "",
                    BackgroundImage = new Image()
                    {
                        ContentDescription = "test",
                        Sources = new ImageSource[]
                                {
                                    new ImageSource()
                                    {
                                        Url = "https://www.yourimageurl.com/background.jpg",
                                        WidthPixels = 1025,
                                        HeightPixels = 595
                                    }
                                }
                    }
                }
            };

            if (dialogContext.Context.AlexaDeviceHasDisplay())
            {
                dialogContext.Context.AlexaResponseDirectives().Add(displayDirective);
            }

```

### Automated Translation of Bot Framework Cards into Alexa Cards

The Alexa Adapter supports sending Bot Framework cards of type HeroCard, ThumbnailCard and SigninCard as part of your replies to the Alexa skill request.

The Alexa adapter will use the first card attachment by default, unless you have disabled this using the AlexaBotOptions property ConvertFirstActivityAttachmentToAlexaCard.

* **HeroCard and ThumbnailCard** :

 * Alexa Card Small Image URL = The first image in the Images collection on the Hero / Thumbnail card
 * Alexa Card Large Image URL = If a second image exists in the Images collection on the Hero / Thumbnail card this will be used. If no second image exists then this is null.
 * Alexa Card Title = Title property of the Hero / Thumbnail card
 * Alexa Card Content = Text property on the Hero / Thumbnail card

***Note: You should ensure that the images you use on your HeroCard / Thumbnail cards are the correct expected size for Alexa Skills responses.***

* **SigninCard** : If a SignInCard is attached to your outgoing activity, this will be mapped as a LinkAccount card in the Alexa response.

repository: daltskin/botbuilder-community-dotnet

repo_name: daltskin/botbuilder-community-dotnet


text:
---
layout: page
title: Neural Audio AI
date: 2021-05-01
author: Joseph Turian
abstract: We believe that machine learning for audio should connect all subcommunities of audio ML researchers (speech, music, environmental sounds, etc.). Moreover, we encourage cross-polination of audio ML research with adjacent fields, such as vision, deep learning, traditional DSP, NLP, and beyond. We specifically encourage benchmarking on audio ML tasks that have high societal impact, in addition to our broader mission of promoting cross-domain evaluation and knowledge sharing.
---

## News

We will be hosting a NeuroIPS 2021 challenge entitled ["HEAR 2021: Holistic Evaluation of Audio Representations"](https://neuralaudio.ai/hear2021-holistic-evaluation-of-audio-representations.html).

Please consider subscribing to our low-volume announcement [mailing list](http://eepurl.com/hwrhrz) and following us on [twitter](https://twitter.com/neuralaudio). Or simply check this web-page for updates.

## Discussion

Do you want to talk about audio ML? Please join our [forum](https://discuss.neuralaudio.ai/). Discussion is open to all audio researchers, whether you are participating in the shared task or simply want to exchange knowledge on audio ML.

repository: turian/latex

gha_language: HTML

repo_name: turian/latex