text:
# Rules.JS

[![Build Status](https://travis-ci.org/bluealba/rules-js.svg?branch=master)](https://travis-ci.org/bluealba/rules-js)
[![npm](https://img.shields.io/npm/v/rules-js.svg)](https://npmjs.org/package/rules-js)
[![npm](https://img.shields.io/npm/dt/rules-js.svg)](https://npmjs.org/package/rules-js)
![David](https://img.shields.io/david/bluealba/rules-js.svg)
[![Coverage Status](https://coveralls.io/repos/github/bluealba/rules-js/badge.svg?branch=master)](https://coveralls.io/github/bluealba/rules-js?branch=master)

## Overview

This is an implementation of a very lightweight pure javascript rule engine.
It's very loosely inspired on drools, but keeping an extra effort in keeping complexity to the bare minimum.

- [Rules.JS](#rulesjs)
  * [Overview](#overview)
    + [Install](#install)
    + [Usage Example](#usage-example)
  * [Engine](#engine)
  * [Fact](#fact)
  * [Closures](#closures)
    + [Provided closures](#provided-closures)
      - [Parameterizable closures](#parameterizable-closures)
      - [Parameterless closures (syntax sugar)](#parameterless-closures-syntax-sugar)
    + [Rules](#rules)
    + [Closure arrays (reduce)](#closure-arrays-reduce)
    + [Rules flow](#rules-flow)

### Install

```
npm install rules-js
```

### Usage Example
This very naive example on how to create an small rule engine to process online orders. This isn't meant to imitate a full business process, neither to shown the full potential of Rules.JS

We start by defining a rules file in JSON.

```json
{
	"name": "process-orders",
	"rules": [
		 {
			 "when": "always",
			 "then": "calculateTotalPrice"
		 },
		 {
			 "when": { "closure": "checkStockLocation", "location": "localDeposit" },
			 "then": [
				 { "closure": "calculateTaxes", "salesTax": 0.08 },
				 "createDispatchOrder"
			 ]
		 },
		 {
			 "when": { "closure": "checkStockLocation", "location": "foreignDeposit" },
			 "then": [
				 "calculateShipping",
				 "createDispatchOrder"
			 ]
		 },
		 {
			 "when": { "closure": "checkStockLocation", "location": "none" },
			 "then": { "closure": "error", "message": "There is availability of such product"}
		 }
	]
}
```

Now we can evaluate any order using such rules file. First we create the engine.  We can do it inside a js module:

```javascript
const engine = new Engine();

// We are intentionally missing something here:
// We need first to define what the verbs 'checkStockLocation', 'calculateTaxes'
// 'calculateShipping' and 'createDispatchOrder' actually mean

const definitions = require("./process-orders.rules.json");
engine.add(definitions);

module.exports = function (order) {
	return engine.process("process-orders", order);
}
```

Then we just use that module to evaluate orders.  Each order is a **fact** that
will be provided to our rule engine.

```javascript
const orderProcessorEngine = require("./order-processor-engine");

const order = {
	books: [
		{ name: "Good Omens", icbn: "0060853980", price: 12.25 }
	],
	client: "mr-goodbuyer"
};

//result is a Promise since rules might evaluate asynchronically.
orderProcessorEngine(order).then(result => {
	const resultingDispatchOrder = result.fact;
	// handle the result in any way
})
```

Of course, we intentionally omit defining what this verbs mean: *calculateTotalPrice*,
*checkStockLocation*, *calculateTaxes*, *calculateShippingAndHandling* and *createDispatchOrder*.
Those reference to provided closures and are the place were implementor should provide
their own business code.

This is where we drift slightly away from the drools-like frameworks take on defining
how a rule engine should actually be configured.  We believe that's a good idea
to define separately the implementation of the business actions that can be executed
and the logic that tells us when and how they are triggered.

There are two ways to do define the missing verbs, through functions or objects. Both
of them are rather similar:

```javascript
engine.closures.add("calculateTotalPrice", (fact, context) => {
	fact.totalPrice = fact.books.reduce((total, book) => total + book.price, 0);
	return fact;
});
```

or

```javascript
class CalculateTotalPrize extends Closure {
	process(fact, context) {
		fact.totalPrice = fact.books.reduce((total, book) => total + book.price, 0);
		return fact;
	}
}

engine.closures.add("calculateTotalPrice", new CalculateTotalPrize());
```

## Engine
This is the main entry point for Rules.js.  The typically lifecycle of a rule engine implies three steps:

1. Instantiate the rule engine.  This instance will be kept alive during the whole life of the application.
2. Configure the engine provided closures.
3. Configure the engine with high-level closures (rules, ruleflows). This is usually done by requiring a rule-flow definition file
4. Evaluate multiple facts using the engine and obtain a result for each one of them.

```javascript
const Engine = require("rules-js");

// 1. instantiate
const engine = new Engine();

// 2. configure
engine.closures.add("calculateTotalPrice", (fact, context)) => {
	fact.totalPrice = fact.books.reduce((total, book) => total + book.price, 0);
	return fact;
});

engine.closures.add("calculateTaxes", (fact, context)) => {
	fact.taxes = fact.totalPrice * context.parameters.salesTax;
	return fact;
}, { required: ["salesTax"] });

const definitions = require("./process-orders.rules.json");
engine.closures.create(definitions);

// 3. at some time later, evaluate facts using the engine
module.exports = function (fact) {
	return engine.process("process-orders", fact);
}

```

## Fact
A fact is an object that is feeded to the rule engine in order to produce a
computational result. Any object can be a fact.

## Closures
One of the core concepts of Rules.JS are closures. We defined **closure** as any
computation bound to a certain context that can act over a **fact** and return a
value.

### Provided closures

In Rules.JS we have a mechanism to tie either a plain old javascript function or
an object that extends the `Closure` class to a certain
name. These are provided closures can be later referenced by any other piece of
the rule engine (*rules*, *ruleFlows*) hence becoming the foundational stones of
the library.

```javascript
// a simple closure implementation function
function (fact, context) {
	return fact.totalPrice * context.parameters.salesTax;
}

//the same thing implemented through a class
class TaxCalculator extends Closure {
	process(fact, context) {
		return fact.totalPrice * context.parameters.salesTax;
	}
}
```

Note that any closure will receive two parameters:
```
@param      {Object}  fact - the fact is the object that is current being evaluated by the closure.
@param      {Context} context - the fact's execution context
@param      {Object}  context.parameters - the execution parameters
@param      {Engine}  context.engine - the rule engine

@return     {Object}  the result of the computation (this can be a Promise too!)
```
The main parameter is of course the **fact**, closures need to derive their result
from each different fact that is provided. **context.parameters** hash is introduced
to allow the reuse of closure implementations through parameterization.

Closures will often enhance the current provided fact by adding extra information
to it. Of course, a closure can always alter the fact.

```javascript
function (fact, context) {
	fact.taxes = fact.totalPrice * 0.8;
	return fact;
}
```

*Note*: It's a good idea to keep closures stateless and idempotent, however this
is not a limitation imposed by Rules.JS

We can register provided closures into a rule engine by invoking the following:

```javascript
engine.closures.add("calculateTaxes", (fact, context) => {
	fact.taxes = fact.totalPrice * 0.08
	return fact;
});
```

Notice that in a simplest form the `add` method receive the name
that we want the closure to have and the closure implementation function.

We can later reference to any provided closure (actually, any *named* closure)
in the JSON rule file through a json object like the following:

```json
{ "closure": "calculateTaxes" }
```

#### Parameterizable closures

We can add parameters to our closures implementation, that way the same closure
code can be reused in different contexts. We can change the former `calculateTaxes`
to receive the tax percentage.

```javascript
engine.closures.add("calculateTaxes", (fact, context) => {
	fact.taxes = fact.totalPrice * context.parameters.salesTax;
	return fact;
}, { required: ["salesTax"] });
```

Now every time that a closure is referenced in a rules file we will need to provide
a value for the `salesTax` parameter (otherwise we will get an error while parsing
it!).

```json
{ "closure": "calculateTaxes", "salesTax": 0.08 }
```

#### Parameterless closures (syntax sugar)
When using closures that don't receive any parameters we can, instead of writing
the whole closure object `{ "closure": calculateShipping" }` we can simply
reference it by its name: `"calculateShipping"`.

### Rules
Rules an special kind of closures that are composed by two component closures (of
any kind!). One of the closures will act as a condition (the *when*), conditionating
the execution of the second closure (the *then*) to the result of its evaluation.

```json
{
	"when": { "closure": "hasStockLocally" },
	"then": { "closure": "calculateTaxes", "salesTax": 0.08 }
}
```

... which is the same than writing ...

```json
{
	"when": "hasStockLocally",
	"then": { "closure": "calculateTaxes", "salesTax": 0.08 }
}
```

### Closure arrays (reduce)
Closures can also be expressed as an array of closures.  When evaluating an
array of closures Rule.JS will perform a reduction, meaning that the resulting
object of each closure will become the fact of the next one.

```json
[
	{ "closure": "calculateTaxes", "salesTax": 0.08 },
	{ "closure": "makeCreditCardCharge" },
	{ "closure": "createDispatchOrder" }
]
```

You can also mix syntaxes inside the array

```json
[
	{ "closure": "calculateTaxes", "salesTax": 0.08 },
	"makeCreditCardCharge",
	"createDispatchOrder"
]
```

Or even using completely different types of closures (i.e. regular provided closures,
rules, nested arrays of closures)

```json
[
	{
		"when": "isTaxAccountable",
		"then": { "closure": "calculateTaxes", "salesTax": 0.08 }
	},
	"makeCreditCardCharge",
	"createDispatchOrder"
]
```

#### Arrays as conditions

You can also use closure arrays as conditions. By default they will work with "and" (`&&`) logic

```json
{
	"when": ["isFoo", "isBar"],
	"then": "executeOrder66"
},
```

You can also define an "and" or "or" strategies to apply them.

```json
{
	"when": ["isFoo", "isBar"],
	"conditionStrategy": "or",
	"then": "executeOrder66"
},
```

There is also a "last" strategy, which makes it work like a regular reducer closure array.

```json
{
	"when": ["transformForFoo", "isFoo"],
	"conditionStrategy": "last",
	"then": "executeOrder66"
},
```

### Rules flow
A rule flow is a definition of a chain of rules that will be evaluated (and applied)
in order. Typically this is the higher order construction that is registered into rules js.

```json
{
	"name": "process-orders",
	"rules": [
		 {
			 "when": "always",
			 "then": "calculateTotalPrice"
		 },
		 {
			 "when": { "closure": "checkStockLocation", "location": "localDeposit" },
			 "then": [
				 { "closure": "calculateTaxes", "salesTax": 0.08 },
				 "createDispatchOrder"
			 ]
		 },
		 {
			 "when": { "closure": "checkStockLocation", "location": "foreignDeposit" },
			 "then": [
				 "calculateShipping",
				 "createDispatchOrder"
			 ]
		 },
		 {
			 "when": { "closure": "checkStockLocation", "location": "none" },
			 "then": { "closure": "error", "message": "There is availability of such product"}
		 }
	]
}
```

license: ISC

repository: ccpu/rules-js

repo_name: ccpu/rules-js


text:
---
title:  The Family
date:  03/10/2020
---

### Read for This Week’s Study
Gen. 3:1–15, 2 Cor. 4:6, Luke 1:26–38, Matt. 1:18–24, Eph. 4:15, 1 John 3:18, Deuteronomy 6.

>
Memory Text

> “My son, hear the instruction of your father, and do not forsake the law of your mother” (Proverbs 1:8, NKJV).

As human beings, we are always (ideally) learning. In fact, life itself is a school.

“From the earliest times the faithful in Israel had given much care to the education of the youth. The Lord had directed that even from babyhood the children should be taught of His goodness and His greatness, especially as revealed in His law, and shown in the history of Israel. Song and prayer and lessons from the Scriptures were to be adapted to the opening mind. Fathers and mothers were to instruct their children that the law of God is an expression of His character, and that as they received the principles of the law into the heart, the image of God was traced on mind and soul. Much of the teaching was oral; but the youth also learned to read the Hebrew writings; and the parchment rolls of the Old Testament Scriptures were open to their study.”—Ellen G. White, The Desire of Ages, p. 69.

For most of human history, education took place mostly in the home, especially for the early years. What does the Bible say about education in the family, and what principle can we take away from it for ourselves, whatever our family situation happens to be?

_*Study this week’s lesson to prepare for Sabbath, October 10._

license: MIT

repository: PrJared/sabbath-school-lessons

branch_name: refs/heads/stage

extension: md

gha_language: CSS

gha_license_id: MIT

license_type: permissive

repo_name: PrJared/sabbath-school-lessons


text:
---
title: "Providers and Consumers"
slug: providers-and-consumers
type: "docs"
toc: true

back: /docs/quickstart/output-variables/
backLabel: Output Variables
next: /docs/quickstart/errands/
nextLabel: Errands
---

Things often run on other things or need other things to run. In Escape we can
express this idea using _providers_ and _consumers_. A _provider_ provides
a certain service or platform and a _consumer_ makes use of it.

In practical terms Providers and Consumers are regular Escape packages. A provider
defines what kind of interface it implements and usually has a few outputs:

```yaml
name: quickstart/my-provider
version: 0.0.@
provides:
- introduction

outputs:
- id: credentials
  default: "My platform specific configuration output"
```

A consumer defines what kind of provider it consumes, and will usually use the
outputs to configure itself:

```yaml
name: quickstart/my-consumer
version: 0.0.@
consumes:
- introduction

inputs:
- id: credentials
  default: $introduction.outputs.credentials
```

When we try to `escape run build` or `escape run deploy` this package that
requires a provider we get an error:

```bash
$ escape run build --plan escape-consumer.yml
Build: Starting build.
Build: Error: Missing provider of type 'introduction'. This can be configured using the -p / --extra-provider flag.
```

Which is Escape complaining that it can't find a provider of type
'introduction', because we haven't deployed one. We can fix this by releasing
and deploying the provider:

```
$ escape run release --plan escape-provider.yml
Release: Releasing quickstart/my-provider-v0.0.0
  Build: ✔ Completed build
  Test: ✔ Tests passed.
  Destroy: ✔ Destruction complete
  Deploy: ✔ Successfully deployed my-provider-v0.0.0 with deployment name quickstart/my-provider in the dev environment.
  Smoke tests: ✔ Smoke tests passed.
  Destroy: ✔ Destruction complete
  Package: ✔ Packaged quickstart/my-provider-v0.0.0 at /home/user/workspace/.escape/target/my-provider-v0.0.0.tgz
  Push: ✔ Push successful.
Release: ✔ Successfully released quickstart/my-provider-v0.0.0

$ escape run deploy quickstart/my-provider-latest
Deploy: ✔ Successfully deployed my-provider-v0.0.0 with deployment name quickstart/my-provider in the dev environment.

$ escape run build --plan escape-consumer.yml
Build: ✔ Completed build

```

## Dependencies vs Providers/Consumers

In a previous section we have seen
[dependencies](/docs/quickstart/dependencies/). Dependencies are resolved at
build time and provide a tight coupling between parents and their children.
Providers and consumers provide a much looser coupling due to interface typing.
This makes it possible to implement multiple implementations for a provider
without having to change consumers; for example: we can provide a different
provider for testing or local development purposes.

We can configure dependency inputs from the parent package and/or use their
outputs. Consumers, on the other hand, are unable to configure the providers
and solely have access to their outputs.

Another difference is that a provider can be consumed by multiple deployments
in the same environment, whereas a dependency only works as part of a parent
release. In practical terms this means that a platform or shared service (e.g.
a Kubernetes cluster, a message queue, etc.) is usually much more appropriate
to implement as a provider than a dependency.

repository: ankyra/escape-docs

branch_name: refs/heads/master

repo_name: ankyra/escape-docs


text:
# 2.2.1

Removed invalid key `types` from `package.json` (thanks @imjordanxd)

# 2.2.0

Fix issue with build, `dist/` wasn't included with the ESM change (thanks @imjordanxd)

Fix Typescript version in CHANGELOG (thanks @rnestler)

Adds Node v20 support (CI coverage)

# 2.1.0

Now using React 18.2.0 and Typescript 5.0.4. If this change effects your application, depend directly on 2.0.0

# 2.0.0

BREAKING: Package is now ESM-compatible (thanks @imjordanxd!)

Bumps a number of deep dependencies with security issues

# 1.2.0

Removes `index.ts` from the distributed package

# 1.1.0

Avoid adding an extra first period to the keys at the zero depth (what was
`..$apple` is now `.$apple`)

# 1.0.0

Initial release

repository: grrowl/react-keyed-flatten-children

gha_language: TypeScript

repo_name: grrowl/react-keyed-flatten-children


text:
# Cluster Run Book

- [How to login to instances](#login)
- [How to update cloud-config](#update-cloud-config)
- [How to scale the cluster](#scaling-the-cluster)
- [How to verify services status](#service-verification)
- [How to upgrade kubernetes binaries](#upgrade-kubernetes)
- [How to add more Terraform modules, such as elb, efs, rds](#add-modules)
- [How to upgrade vault binary](#upgrade-vault)
- [How to upgrade cluster operating system](#upgrade-instances-operating-system)

## Login

For trouble-shooting, you can login to etcd, master, and nodes. First make sure the AWS instance key pairs are already added to ssh agent:
```
$ ssh-add -l
2048 SHA256:h9ps0iAK8QeptEzNcvLEQRIZVl7kam7gTD5InP2Sqbk /Users/xxxxx/.ssh/kubev1-vault.pem (RSA)
2048 SHA256:7rzk7bd6AZU7cW+vkfi0Nr79FIZfb7O0jRxfLXCmXUM /Users/xxxxx/.ssh/kubev1-etcd.pem (RSA)
2048 SHA256:FLveXZTsgOrmCp9iwJiNVK6suYeN/ARkk5snY4We/q8 /Users/xxxxx/.ssh/kubev1-master.pem (RSA)
2048 SHA256:z6YWKb75hb3BLaxtVWQFAXg3Lgfm1kqg/KBSCitAJpk /Users/xxxxx/.ssh/kubev1-node.pem (RSA)
```

If not, add necessary key to ssh agent:

```
$ ssh-add /Users/xxxxx/.ssh/kubev1-master.pem
$ cd resources/master
$ make get-ips
master; public ips:  <aws-profile-name> <IP_ADDRESS>
$ ssh<EMAIL_ADDRESS>core@ip-10-240-10-80-kubev1-master ~ $
```

Same for node, etcd nodes.

## Update Cloud Config

All machines use the same script ('user-data') to bootstrap. The bootstrap uses role-based IAM policy to download the
machine's own cloud-config.yaml and run cloud-init to setup the machine. This second stage bootstrapping gives us the flexibilty of changing cloud-config without having to re-provisioned the machine. All you need to do is to reboot the machine.

Cloud config contains system units and post-installation scripts. Per resource **cloud-config.yaml.tmpl** file is located at resources/\<master|node|etcd|vault\>/artifacts/cloug-config.yaml.tmpl. The generated cloud-config.yaml file is uploaded to the resource's specific s3 bucket and will be picked up at each reboot.

To upload a new file after modifying the **cloud-config.yaml.tmpl**:

```
$ cd resources/<master|node|etcd|vault>
$ make update-user-data
```
When you reboot etcd, masters, wait the cluster has elected new leaders before rebooting another one.

## Scaling the Cluster

You re-size master, node, vault, and etcd autoscaling group by overriding the default vaules defined in **enva.sh**.

NOTE: For etcd autoscaling group, use 1,3,5,7.. odd number and make min=max=desired. For production, use at least 3 to begin with for high availability.

Here is an example of adding more nodes:

In **resources/node/envs.sh** file, change the capacity you want:

```
# Workers ASG override
export TF_VAR_instance_type="m3.large"
export TF_VAR_cluster_min_size=1
export TF_VAR_cluster_max_size=10
export TF_VAR_cluster_desired_capacity=5
```

Updating the autoscaling group

```
$ cd resources/node
$ make
```

## Service Verification

This verifies master installation status.
```
$ cd resources/master
$ make get-ips
$ ssh<EMAIL_ADDRESS>"cd /etc/systemd/system; systemctl status kube-*" | less
```
This verifies node's installation status.
```
$ cd resources/node
$ make get-ips
$ ssh<EMAIL_ADDRESS>"cd /etc/systemd/system; systemctl status kube*" | less
```

## Upgrade Kubernetes

Read Kubernetes release notes to make necessary configuration changes. Ideally use a test environment to test out the new releases.

* Edit envs.sh file to change the version of Kubernetes, as shown in bellow example:

```
export TF_VAR_kube_version="v1.11.0"
```

* Update systemd install-kubernetes unit

```
$ make upgrade-kube
```

* Reboot each master and nodes to pickup new configurations. To validate:

```
$ /opt/bin/kubectl version
```

## Add modules

- mkdir -p resource/\<module\>
- cd resource/\<module\>; ln -sf ../common/common.tf common.tf
- cd resource/\<module\>; ln -sf ../common/common.mk Makefile, or include ../common/common.mk in module's customized Makefile
- Add envs.sh to define module name, override auto-configuration parameters
- Add a target and its dependencies in top level Makefile
- Add "terraform_remote_state" in common.tf if the module output will be referenced by other modules

## Upgrade-Vault

* Find TF_VAR_vault_release in envs.sh, and change it like so:

```
# Vault release: restart vault service if changed
export TF_VAR_vault_image=0.10.3
```

* Change vault's configuration and restart vault

```
$ cd resources/vault
$ make update
$ make ssh
Permitted 22 from <yourip>/32 to vault...
$ sudo reboot
```

* Verify vault status
```
$ cd resources/vault
$ make remote-cmd "source /etc/profile.d/vault.sh; vault status"
Permitted 22 from <yourip>/32 to vault...
Sealed: false
Key Shares: 5
Key Threshold: 3
Unseal Progress: 0
Unseal Nonce:
Version: 0.10.3
Cluster Name: vault-cluster-e4a80891
Cluster ID: f5137877-494e-c38b-8dab-********

High-Availability Enabled: false
```
## Upgrade Instances Operating System

All machines are running CoreOS image. With auto-update enabled, CoreOS and etcd binaries will be upgraded automatically when CoreOS has new release.

repository: xuwang/kube-aws-terraform

gha_language: HCL

repo_name: xuwang/kube-aws-terraform


text:
# Speaker @ StackWorld Conference

## Kabuki Hotel, San Francisco CA | June 28th, 2016
http://www.stackworld.com/conference

![Building Scalable Web Applications using Microservices Architecture and Serverless Computing from AWS](http://image.slidesharecdn.com/2016-06-27-microservices-architecture-preview-160509115434/95/building-scalable-web-applications-using-microservices-architecture-and-serverless-computing-from-aws-1-638.jpg?cb=1467050165)

> Powerpoint Presentation:
>
> [Building Scalable Web Applications using Microservices Architecture and Serverless Computing from AWS](http://www.slideshare.net/mitocgroup/microservices-architecture-for-web-applications-with-aws-lambda-at-core)


text:
# Azure App Services, Application Insights and Java agent

If you're running your Java app on Azure App Services and you'd like to get deeper insights on your application dependencies, logs etc. you might want to consider the [Azure Application Insights Java Agent](https://docs.microsoft.com/en-us/azure/azure-monitor/app/java-agent).

In principle, it's sufficient to include a reference to the Java agent to get things rolling. However, currently App Services doesn't provide a standard way of including the Applicaton Insights Java agent in its configuration, so the responsibilty of uploading the agent jar file lies with the developers. This is an example repository of how to bundle and configure the Application Insights Java agent using mainly Java tooling as part of the development process.

## Building and deploying the example

Let's start with declaring a few variables:

```bash
RG=...  # the target resource group, assuming that this has been created already
BASE_NAME=...  # i.e. myapp, choose something with less than 6 alphanumeric characters
APP_INSIGHTS_VERSION=...  # i.e. 2.5.1, the version of the app insights dependency
```

> As some of the Azure resources need to have globally unique names, the included ARM templates attempt to generate more or less unique names by appending a hash of the resource group name to the provided base name. If you prefer to have more control or need to use specific names, just update the variables in the templates.

The first step is to create the resources. If you already have an Azure App Services instance running, you might want to skip this. This repository contains an ARM template that creates a number of Azure resources and connects those, such as an Azure App Services instance to host the web app, a MySQL database, a Key Vault for storing secrets and of course an Application Insights instance.

```bash
WEBAPP=`az deployment group create -g $RG \
    --template-file infra/webapp-template-simple.json \
    --parameters baseName="$BASE_NAME" \
    --query properties.outputs.webAppName.value \
    -o tsv`
```

If you've cloned this repo, change directory to the `app` folder and run the following command to build the application. The pom file uses the passed variable to resolve the Application Insights jar dependency.

```bash
mvn clean package -Dapp.insights.version=$APP_INSIGHTS_VERSION
```

The above command also downloads and copies the necessary dependencies for the Java agent. These end up in the `target` directory, under the `resources` subdirectory.

Typically only a jar/war/ear file is deployed to App Services. However, in order to install the Java agent, we'll need to bundle it (separately) with the application jar file. In this example we'll explore two Maven based options for this purpose, first with the [assembly](https://maven.apache.org/plugins/maven-assembly-plugin/index.html) plugin, and alternatively with the [azure-web-app-maven](https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Web-App) plugin. Note that these are not the only options, you could also go for a command line utility such as `zip` or other specific tasks in your CI pipeline.

### Maven Assembly plugin

According to its [docs](http://maven.apache.org/plugins-archives/maven-assembly-plugin-3.0.0/index.html) the *assembly* plugin is primarily intended to allow users to aggregate the project output along with its dependencies, modules, site documentation, and other files into a single distributable archive. There's a bunch of predefined specifications to bundle common artifacts, however, for our project we need to be very prescriptive and create a special zip file that contains all the required resources. The end result should look like this:

```bash
├── app.jar
└── resources
    ├── AI-Agent.xml
    └── applicationinsights-agent-2.5.1.jar
```

> Note that you can also put the agent at the top level, but it's best practice to put it in a specific directory together with its configuration.

In order to create such a file, we need to specify an assembly descriptor, which should be pretty trivial:

```xml
...
    <formats>
        <format>zip</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory> <!-- no root folder for the zip file-->
    <fileSets>
        <fileSet>
            <directory>${project.build.directory}</directory>
            <outputDirectory>.</outputDirectory> <!-- don't include target as a folder -->
            <includes>
                <include>app.jar</include>
                <include>resources/*</include>
            </includes>
        </fileSet>
    </fileSets>
...
```

It's possible to associate generation of the zip file with the package phase, but in this example we'll be explicitly executing that goal.

```bash
mvn assembly:single
```

The command will generate the zip file `app-service.zip` in the build directory. Next step is to deploy that using Azure CLI.

```bash
az webapp deployment source config-zip -g $RG -n $WEBAPP --src target/app-service.zip
```

There's also one more important piece of information that needs to be configured. The Application Insights agent jar needs to be specified as a startup option for the Java process. We can do that by setting the `JAVA_OPTS` application setting.

```bash
AGENT_CONFIG=-javaagent:D:/home/site/wwwroot/resources/applicationinsights-agent-$APP_INSIGHTS_VERSION.jar
az webapp config appsettings set -g $RG -n $WEBAPP --settings JAVA_OPTS="$AGENT_CONFIG" -o none
```

> A few remarks regarding the location of the agent jar, the zip deployment process unzips the contents of the zip file into the `$HOME/site/wwwroot` directory, and the javaagent option needs the absolute path for the agent jar. The included ARM template creates an App Services instance on a Windows plan, hence the prefix `D:/home`. For a Linux plan, you'd need to replace that with just `/home`. See the [Kudu docs](https://github.com/projectkudu/kudu/wiki/File-structure-on-azure) on the topic of the App Service File structure.

Now, you're ready to test the application.

### Azure Maven Web App plugin

If you don't want to use the assembly plugin or if you'd like to combine the packaging and deployment as a single step, you might want to try out the deployment capabalities of the [Azure Web App](https://github.com/microsoft/azure-maven-plugins/wiki/Azure-Web-App:-Deploy) Maven plugin.

The configuration for this plugin also includes the application settings (and it can also create new App Services instances), so you wouldn't need the Azure CLI commands to set those.

```xml
...
    <plugin>
        <groupId>com.microsoft.azure</groupId>
        <artifactId>azure-webapp-maven-plugin</artifactId>
        <version>1.9.1</version>
        <configuration>
            <schemaVersion>V2</schemaVersion>
            <resourceGroup>${resource.group.name}</resourceGroup>
            <appName>${webapp.name}</appName>
            <runtime>
                <os>windows</os>
                <javaVersion>1.8</javaVersion>
                <webContainer>java 8</webContainer>
            </runtime>
            <appSettings>
                <property>
                    <name>JAVA_OPTS</name>
                    <value>-javaagent:D:/home/site/wwwroot/resources/applicationinsights-agent-${app.insights.version}.jar</value>
                </property>
            </appSettings>
            <deploymentType>ZIP</deploymentType>
            <deployment>
                <resources>
                    <resource>
                        <directory>${project.build.directory}</directory>
                        <includes>
                            <include>app.jar</include>
                            <include>resources/*</include>
                        </includes>
                    </resource>
                </resources>
            </deployment>
        </configuration>
    </plugin>
...
```

Once you have your `pom.xml` configured, all you need to do is pass the relevant information and run the `deploy` goal.

```bash
mvn azure-webapp:deploy -Dresource.group.name=$RG -Dwebapp.name=$WEBAPP -Dapp.insights.version=$APP_INSIGHTS_VERSION
```

> You might notice an error message in your application logs when you're running this for the very first time, indicating that there's an error opening zip file or JAR manifest missing for the agent jar. That's because the deploy plugin first configures the application setting with the java agent startup option, while the agent jar file has not been extracted yet. The application will restart after the deployment, with the jar files present so you can safely ignore that. Subsequent deployments won't have this problem (unless there's a new version of the agent gets configured).

## Testing the functionality

The sample application is pretty basic, you can list registered *employees* by running the following command:

```bash
$ curl https://$WEBAPP.azurewebsites.net/api/employee
[]
```

The first time will return an empty list, you can insert new entries by *POST*ing them:

```bash
$ curl -X POST https://$WEBAPP.azurewebsites.net/api/employee -H "Content-Type: application/json" -d '{"alias":"meken", "firstName":"Murat", "lastName":"Eken"}'
{"id":1,"firstName":"Murat","lastName":"Eken","alias":"meken"}
```

After running a few of these you can tinker with Application Insights metrics/logs/dependency map to verify that the agent is sending telemetry to Application Insights. Note that it'll take a few minutes for the telemetry to be ingested by Application Insights, so if you don't immediately see anything, try it again after some time.

## Summary

This repository illustrates how to deploy the Application Insights agent jar and configure Azure App Services properly for a Spring Boot Java application using Maven tooling.

repository: meken/app-services-app-insights-java

repo_name: meken/app-services-app-insights-java


text:
# Oracle PL/SQL Profiling / Flat Profiler

The Oracle PL/SQL Profiling module contains the code for a series of articles demonstrating the use of three PL/SQL profiling methods on two example program structures. The examples are designed to illustrate their behaviour over as many different scenarios as possible, while keeping the examples as simple as possible. This submodule, on Oracle's flat profiler, is one of three covering each of the profilers individually.

Blog: [PL/SQL Profiling 2: Flat Profiler](http://aprogrammerwrites.eu/?p=2867)

[Tweet with recording attached](https://twitter.com/BrenPatF/status/1278558982945243139)

The root README shows the scenarios covered with call structure diagrams for the two examples, and has a table summarising the features of the different profilers. These are extracted from the overview article. It also has full installation instructions for running the three profilers on the two example program structures.

- [README: Root](../README.md)

The current, detail, README shows the data model for the flat profiler, and summaries of results on the second, simpler, example. These are extracted from the detail article linked above. It also shows how to install and run just the Flat profiler on the two examples.

## In this README...
- [Data Model](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#data-model)
- [Results for Example 2: Sleep](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#Results-for-example-2-sleep)
- [Running Driver Scripts](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#running-driver-scripts)

## Data Model
- [In this README...](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#in-this-readme)

<img src="plsql_profiling - DP ERD.png">

## Results for Example 2: Sleep
- [In this README...](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#in-this-readme)
- [Run Header](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#Run-Header)
- [Profiler Data Summaries](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#Profiler-Data-Summaries)
- [Profiler Data by Unit and Line](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#profiler-data-by-unit-and-line)
- [Calls to Units with EXECUTE ONLY Access](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#Calls-to-Units-with-EXECUTE-ONLY-Access)
- [Aggregate/Detail Timing Discrepancy](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#aggregatedetail-timing-discrepancy)

### Run Header
- [Results for Example 2: Sleep](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#Results-for-Example-2-Sleep)

The record produced in the run table, PLSQL_PROFILER_RUNS, was:

     Run Id Time     Seconds  Microsecs
    ------- -------- ------- ----------
          2 07:52:22  11.000   11000000

### Profiler Data Summaries
- [Results for Example 2: Sleep](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#Results-for-Example-2-Sleep)

Profiler data overall summary (PLSQL_PROFILER_DATA):

    Seconds  Microsecs    Calls
    ------- ---------- --------
      0.000        265        7

Profiler data summary by unit (PLSQL_PROFILER_DATA):

    Unit                 Unit# Seconds  Microsecs    Calls
    -------------------- ----- ------- ---------- --------
    <anonymous>              1   0.000        242        5
    SLEEP_BI                 2   0.000         23        2

### Profiler Data by Unit and Line
- [Results for Example 2: Sleep](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#Results-for-Example-2-Sleep)

The records produced in the functions table, PLSQL_PROFILER_DATA, are listed below in order of unit name, then unit number and line number.

    Seconds  Microsecs   Min S   Max S    Calls Unit                 Unit# Type            Line# Line Text
    ------- ---------- ------- ------- -------- -------------------- ----- --------------- ----- ------------------------------------------------------------------
      0.000          0   0.000   0.000        0 <anonymous>              1 ANONYMOUS BLOCK     1
      0.000          2   0.000   0.000        0 <anonymous>              1 ANONYMOUS BLOCK     5
      0.000         23   0.000   0.000        1 <anonymous>              1 ANONYMOUS BLOCK     9
      0.000         10   0.000   0.000        1 <anonymous>              1 ANONYMOUS BLOCK    11
      0.000        199   0.000   0.000        1 <anonymous>              1 ANONYMOUS BLOCK    13
      0.000          3   0.000   0.000        1 <anonymous>              1 ANONYMOUS BLOCK    15
      0.000          5   0.000   0.000        1 <anonymous>              1 ANONYMOUS BLOCK    17
      0.000          0   0.000   0.000        0 <anonymous>              1 ANONYMOUS BLOCK    19
      0.000          2   0.000   0.000        0 SLEEP_BI                 2 TRIGGER             1 TRIGGER sleep_bi
      0.000         20   0.000   0.000        1 SLEEP_BI                 2 TRIGGER             2 BEFORE INSERT
      0.000          1   0.000   0.000        1 SLEEP_BI                 2 TRIGGER             4 FOR EACH ROW

    11 rows selected.

### Calls to Units with EXECUTE ONLY Access
- [Results for Example 2: Sleep](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#Results-for-Example-2-Sleep)

The manual states "you cannot use the package to profile units for which EXECUTE ONLY access has been granted". In this example there are calls to two units where this applies: the system package DBMS_Lock, and the custom utility package Utils, which is in a different schema (lib) from the one (app) in which the script is run.

In the output above we can see the lines from which the calls are made but nothing within the units called.

### Aggregate/Detail Timing Discrepancy
- [Results for Example 2: Sleep](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#Results-for-Example-2-Sleep)

Where the flat profiler does not provide data for program units, such as DBMS_Lock.Sleep, the timings at the detail level do not add up to the overall time recorded in the runs table. As there were three calls using elapsed time of 11 seconds in total the total recorded in the runs table is 11 seconds, while this 11 seconds is missing from the detail records, which add up to only 265 microseconds in total.

## Running Driver Scripts
[Schema: app; Folder: dprof]
- [In this README...](https://github.com/BrenPatF/plsql_profiling/blob/master/dprof/README_DP.md#in-this-readme)

You need to have first run the [prerequisite installation](..\README.md#installation)

 ### Create Flat Profiler Components
If the script has not already been run from the root README:
- Run script from slqplus:
```
SQL> @install_dprof_app
```

### Run Driver Scripts
- Run scripts from slqplus for general and sleep examples (output will be in .log files):
```
SQL> @dp_example_general
SQL> @dp_example_sleep
```


text:
# Spark Scala Training by DataKickstart

## Purpose
This project exists as a place to view and test out Scala Spark examples with corresponding pom.xml file to be used with Maven to build locally.  Assumes using IntelliJ IDEA as IDE but should work with anything.   Spark examples can be found at src/main/scala/com/datakickstart/spark/examples.

Recommended starting points:
1. Spark Core Batch: [`Spark Core Example`](https://github.com/datakickstart/spark-scala-training/blob/master/src/main/scala/com/datakickstart/spark/examples/batch/core/BasicSparkExample.scala)
2. Spark Structure Streaming: [`Kafka Structure Streaming`](https://github.com/datakickstart/spark-scala-training/blob/master/src/main/scala/com/datakickstart/spark/examples/streaming/structured/KafkaStructuredStreamingExample.scala)

## Getting started locally
Recommendation is to use Docker in which case you can follow the instructions in order (Docker setup, Building project, Running pipeline).  You will need Java 8 and Maven installed locally.  If on a Mac, using homebrew should work but may have to specify versions.

### Docker setup
To test Kafka pipeline locally, you can use Docker and Docker Compose.  Once those are installed follow these steps:

1) Start docker (if not already running)
2) In a terminal window, navigate to project home directory (likely `spark-scala-training`)
3) Run command `docker-compose up -d zookeeper`
4) Run command `docker-compose up`
5) Leave this running in the terminal window and proceed with other steps in a new terminal window/tab

### Building project
1) Navigate to project home directory
2) Run command `mvn install`

### Running pipeline with local spark
1) Kick off the [`Kafka Structure Streaming`](https://github.com/datakickstart/spark-scala-training/blob/master/src/main/scala/com/datakickstart/spark/examples/streaming/structured/KafkaStructuredStreamingExample.scala) consuming pipeline with command `spark-submit --master local[*] --packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.3.0 --class com.datakickstart.spark.examples.streaming.structured.KafkaStructuredStreamingExample target/spark-training-1.0-SNAPSHOT.jar`.
2) While the pipeline is running, produce messages to Kafka by running job `VehicleStopsWriter`(https://github.com/datakickstart/spark-scala-training/blob/master/src/main/scala/com/datakickstart/common/VehicleStopsWriter.scala) either from your IDE or with command `java -cp target/spark-training-1.0-SNAPSHOT.jar com.datakickstart.common.VehicleStopsWriter vehicle-stops localhost:9092`.

repository: datakickstart/spark-scala-training

repo_name: datakickstart/spark-scala-training


text:
# Development

## Setting the `PYTHONPATH`

Set the `PYTHONPATH` variable for module importing. To do this, you need to work in the command line.

### Mac OS X / Linux

    $ cd nyc-green-taxi-map-visualization
    $ export PYTHONPATH="$(pwd)"

## Working in a Virtual Environment \[RECOMMENDED\]

### Using vanilla `virtualenv`

### Using `virtualenvwrapper` \[RECOMMENDED\]

## Installing pip packages

    $ pip install -U pip
    $ pip install -r requirements_dev.txt

## Updating requirements \& dependencies

Make sure `pip-tools` has already been installed. If you ran `pip install -r requirements_dev.txt`, then `pip-tools==1.11.0` should be installed.

_NOTE: Never directly update `requirements.txt` or `requirements_dev.txt`._

Instead, use `pip-compile`

    $ pip-compile requirements.in
    $ pip-compile requirements_dev.in

repository: eddowh/nyc-green-taxi-map-visualization

repo_name: eddowh/nyc-green-taxi-map-visualization


text:
# Patent Vista

A bird's-eye view of patent landscape.

Click [here](https://docs.google.com/presentation/d/1GYmk3EMiETBooWJDNu6uFWAWcya_pcZEPCu1biHSnyw/edit#slide=id.gc6f73a04f_0_0) to see my presentation.

Click [here](https://www.youtube.com/watch?v=mJf5L2jHnGw) to see a video demo.

#### How to install and get it up and running

1. Migrate [data](https://cloud.google.com/public-datasets) from Google Cloud to AWS S3

2. Set up a Spark cluster on AWS (e.g., 4 EC2 instances including 1 master and 3 workers)

3. Install Neo4j on a separate instance

4. Change file index in run.sh, start index and end index

5. ```
   sh run.sh
   ```

### Introduction

---

Patent Vista is a data pipeline designed to visualizaing patent citation relationships to:

1. Spot VIP (very import patent) of a patent portfolio
   - More citations = more important (similar to more retweets more influence)
2. Check how a patent portfoli is structured (technical fields distribution)
   - What is the strategy of protecting the core technologies?
3. Identify potential licensees for monetizing patent asset
   - How to monetize patent asset?

### Architecture

---

![](data-pipeline.jpg)

1. 1.5 TB data is [migrated](https://github.com/shao-shuai/birdview-patent-landscape/blob/master/ingestion/README.md) from Google Cloud to Amazon S3
2. The data is splitted into 1667 batches, each batch is 1 GB
3. The batch data is fetched into Apache Spark for batch processing to extract citation information and patent ownership information
4. The result of the batch processing is sotred into Neo4j to visualizaing relatinships

### Dataset

---

Raw dataset is patents public data from Google Cloud.

### Engineering challenges

---

Writing data from Spark to Neo4j was quite slow at the beginning. I used [neo4j-python-driver](https://github.com/neo4j/neo4j-python-driver) for writing and it took more than 20 minutes for writing a batch.

Meanwhile neither [Neo4j JDBC driver](https://github.com/neo4j-contrib/neo4j-jdbc) nor [neo4j-spark-connector](https://github.com/neo4j-contrib/neo4j-spark-connector) supports writing Neo4j, also there is not enough documentation in writing Neo4j for both.

[neo4j-admin import](https://neo4j.com/docs/operations-manual/current/tutorial/import-tool/) is a very handy built-in command provided by Neo4j, writing a batch only took 6 seconds. But the problem is this command can only be used to import data into an empty database, if there is existing data in database, we cannot use this command. As I have `1667` batches,  merging all the processing results for the batches to use this command seems not that efficient.

Then I learned how to do batch writing with Cypher

```cypher
WITH $names AS nested
UNWIND nested AS x
MERGE (w:PATENT {name: x[0]})
MERGE (n:PATENT {name: x[1]})
MERGE (w)-[r:CITE]-(n)
```

This is very fast for writing nodes in Neo4j, but writing relationships could also take 50+ minutes.

Finally I found my **Swiss Army Knife**, creating a constraint which will automatically create a schema index in the database. With this, each batch takes less than 1 minute.💪

```cypher
CREATE CONSTRAINT ON (p:PATENT) ASSERT p.name IS UNIQUE
```

### Trade-offs

---

repository: shao-shuai/birdview-patent-landscape

repo_name: shao-shuai/birdview-patent-landscape


text:
---
_id: 5f35cc6a5f299c0046cea119
title: "ReactJS Based RPG Game! (part 1) React Hooks, Sprite Animation, Event Listener, Classless React"
url: 'https://www.youtube.com/watch?v=DqpPgK13oEM'
category: articles
slug: 'reactjs-based-rpg-game-part-1-react-hooks-sprite-animation-event-listener-classless-react'
user_id: 5a83ce59d6eb0005c4ecda2c
username: 'bill-s'
createdOn: '2020-08-13T23:27:38.789Z'
tags: [javascript]
---

Today we start building an old school style RPG game using JavaScript, React, Custom React Hooks, Event Listeners, Sprites, and more! This first screencast will cover sprite walk animations and moving around the screen as well as adding basic zone info and tilesets.

Next week I will be releasing the second part which is about creating maps and zones. Following that will be the fight screens. I think this series will be 6-9 parts and I will be releasing them 3 in a row, 1 a week!

repository: dotnetweekly/dnw-gatsby

gha_language: JavaScript

repo_name: dotnetweekly/dnw-gatsby


text:
# Addition

Scenario: Addition of two positive numbers .

  Given: The Calculator is ON .

  When:  The user enters two numbers and a '+' operator .

  Then:  The result is sum of two numbers .

Scenario: Addition of two negative numbers .

  Given: The Calculator is ON .

  When: The user enters two negative numbers and a '+' operator .

  Then: The result is sum of two numbers with a negative sign .

Scenario: when user enters more than one operator .

  Given: The Calculator is ON .

  When: The user enters more than one operator .

  Then: The result is an error message and
        user need to perform the operation again .

Scenario: The input is in wrong format ( 6 + * ) .

  Given: The Calculator is ON .

  When: The user gives input in wrong format like a single operand
        and more than one operator, single operand and single operator .

  Then: The result is an error message.
        User need to enter the input parameters again .

Scenario: Adding numbers where result goes out of range .

  Given: The Calculator is ON .

  When: The user enters two operands, an operator and
        the result exceeds the display range .

  Then: The result is an error message.
        User need to enter smaller numbers .

Scenario: Addition of fractions .

  Given: The Calculator is ON .

  When:  The user enters two fractional numbers and a '+' operator .

  Then:  The result is sum of two fractional numbers in decimals .

Scenario: Addition of positive and negative numbers .

  Given: The Calculator is ON .

  When:  The user enters one positive number and a negative number
         along with the '+' operator .

  Then:  The result is subtraction of two numbers with a greater number sign .

Scenario: Addition of more than two numbers .

  Given: The Calculator is ON .

  When:  The user enters more than two numbers and a '+' operator .

  Then:  The result is summation of the numbers .


text:
---
layout: post
title: "SIMD"
description: ""
category:
tags: []
---
{% include JB/setup %}

#  Single Instruction Multiple Data (SIMD)

Related GCC flags `-msse`.

HotSpot JVM supports SIDM. For details, refer to
[Intrinsic Methods in HotSpot VM](http://www.slideshare.net/RednaxelaFX/green-teajug-hotspotintrinsics02232013).

- [An Introduction to GCC Compiler Intrinsics in Vector Processing](http://www.linuxjournal.com/content/introduction-gcc-compiler-intrinsics-vector-processing)
- [Intrinsic function](https://en.wikipedia.org/wiki/Intrinsic_function)
- [Intel Intrinsics Guide](https://software.intel.com/sites/landingpage/IntrinsicsGuide/)
- MSDN Compiler Intrinsics

gha_language: Ruby


text:
---
hrs_structure:
  division: '1'
  volume: '2'
  title: '6'
  chapter: '53'
  section: 53-11
type: hrs_section
tags:
  - Government
menu:
  hrs:
    identifier: HRS_0053-0011
    parent: HRS0053
    name: 53-11 Government instrumentalities to cooperate with agency
weight: 14055
title: Government instrumentalities to cooperate with agency
full_title: 53-11 Government instrumentalities to cooperate with agency
---
**§53-11 Government instrumentalities to cooperate with agency.** For the purpose of aiding and cooperating in the planning, undertaking, construction, or operation of redevelopment projects located within the area in which it is authorized to act, any instrumentality of the government, may upon such terms, with or without consideration, as it may determine:

(1) Dedicate, sell, convey, or lease any of its property to a redevelopment agency;

(2) Cause parks, playgrounds, recreational, community, educational, water, sewer, or drainage facilities or any other works which it is otherwise empowered to undertake, to be furnished adjacent to or in connection with redevelopment projects;

(3) Furnish, dedicate, close, pave, install, grade, regrade, plan or replan streets, roads, roadways, alleys, sidewalks, or other places which it is otherwise empowered to undertake;

(4) Enter into agreements (which may extend over any period, notwithstanding any provision or rule of law to the contrary) with the federal government or any other public body or bodies respecting action to be taken pursuant to any of the powers granted by this part, including the furnishing of funds or other assistance in connection with projects being or to be undertaken pursuant to this part;

(5) Purchase or legally invest in any of the bonds of an agency and exercise all of the rights of any holder of the bonds;

(6) Reimburse the agency for lands acquired and transferred or dedicated by the agency for public purposes. [L 1949, c 379, pt of §4; am L 1955, c 271, §1(h); RL 1955, §143-11; [HRS §53-11](/title-6/chapter-53/section-53-11/)]

repository: SamMade/BlueAndKrabby

repo_name: SamMade/BlueAndKrabby


text:
# rpnc250

[![R-CMD-check](https://github.com/SilviaTerra/rpnc250/workflows/R-CMD-check/badge.svg)](https://github.com/SilviaTerra/rpnc250/actions)
[![Codecov test
coverage](https://codecov.io/gh/SilviaTerra/rpnc250/branch/main/graph/badge.svg)](https://codecov.io/gh/SilviaTerra/rpnc250?branch=main)

The goal of rpnc250 is to provide R functions that produce height,
volume, and biomass estimates using the equations and coefficients from
USFS Research Paper NC-250: Tree volume and biomass equations for the
Lake States.

Citation for publication: Hahn, Jerold T. 1984. Tree volume and biomass
equations for the Lake States. Research Paper NC-250. St. Paul, MN: U.S.
Dept. of Agriculture, Forest Service, North Central Forest Experiment
Station

The original publication can be accessed from the [U.S. Forest
Service](https://www.fs.usda.gov/treesearch/pubs/10037).

The equations and species-specific coefficients were copied out of the
PDF version of the publication by Henry Rodman in January 2021. The
tables are [stored in csv format](inst/csv/) in the R package and have
been [translated into package data objects](data-raw/tables.R) for use
in the internal functions.

The functions for estimating height, volume, and biomass have been
[tested](tests/testthat/test-eq.R) to align with the examples provided
in the original publication.

 For simplicity, we will assume that site index is constant
for all of the plot locations.

``` r
# summarize plot-level basal area
plot_ba <- test_trees %>%
  dplyr::filter(
    !is.na(dbh),
    !is.na(tpa_unadj),
    statuscd == 1
  ) %>%
  dplyr::group_by(
    plt_cn # FIA plot IDs
  ) %>%
  dplyr::summarize(
    bapa = sum(tpa_unadj * 0.005454 * dbh^2),
    .groups = "drop"
  )

# filter the trees and join to plot basal area table
trees_prepped <- test_trees %>%
  dplyr::filter(
    !is.na(dbh),
    statuscd == 1, # only live trees
    !is.na(tpa_unadj)
  ) %>%
  dplyr::left_join(
    plot_ba,
    by = "plt_cn"
  )
```

### Merchantable height

The height equation in the publication generates estimates of height to
a given top diameter (outside bark) provided species, DBH (inches), site
index, and stand basal area.

To estimate height to 4" top we can apply the function
`estimate_height`:

``` r
# clone prepped tree dataframe
ht_trees <- trees_prepped

ht_trees$height_4 <- estimate_height(
  spcd = ht_trees$spcd,
  dbh = ht_trees$dbh,
  site_index = 65,
  top_dob = 4,
  stand_basal_area = ht_trees$bapa
)
```

It is also possible to use the functions within `dplyr::mutate` calls
which facilitates clean data wrangling workflows.

``` r

ht_trees <- trees_prepped %>%
  dplyr::mutate(
    height_4 = estimate_height(
      spcd = spcd,
      dbh = dbh,
      site_index = 65,
      top_dob = 4,
      stand_basal_area = bapa
    )
  )
```

### Cubic feet

We can summarize total merchantable volume up to 4" top very easily.
First, join the plot-level basal area table to the tree table, then
estimate height to 4" top for each stem. Using those estimates as inputs
to the volume equations we can estimate stem-level volumes.

``` r
merch_cuft_4 <- trees_prepped %>%
  dplyr::mutate(
    height_4 = estimate_height(
      spcd = spcd,
      dbh = dbh,
      site_index = 65,
      top_dob = 4,
      stand_basal_area = bapa
    ),
    gross_cuft_vol = estimate_volume(
      spcd = spcd,
      dbh = dbh,
      height = height_4,
      vol_type = "cuft"
    )
  )

# plot relationship between diameter and gross volume
merch_cuft_4 %>%
  ggplot2::ggplot(
    ggplot2::aes(
      x = dbh,
      y = gross_cuft_vol,
      color = common_name
    )
  ) +
  ggplot2::geom_point() +
  ggplot2::labs(
    x = "DBH (inches)",
    y = "gross volume to 4\" top (cubic ft)",
    color = "species"
  )
#> Warning: Removed 106 rows containing missing values (geom_point).
```

### Board feet

To get merchantable volume in board feet (Int’l 1/4) we can set the
merchantable height to 9" for softwood trees, and 10" for hardwood
trees. You and I both know that the large aspen are probably not
destined for sawtimber products, but we can dream.

``` r
# make table of spcd and hardwood/softwood assignment
spp_groups <- tidyFIA::ref_tables[["species"]] %>%
  dplyr::transmute(
    spcd,
    class = dplyr::case_when(
      major_spgrpcd %in% c(1, 2) ~ "softwood",
      major_spgrpcd %in% c(3, 4) ~ "hardwood"
    )
  )

merch_bdft <- trees_prepped %>%
  dplyr::left_join(
    spp_groups,
    by = "spcd"
  ) %>%
  dplyr::mutate(
    top_dob = dplyr::case_when(
      class == "hardwood" ~ 10,
      class == "softwood" ~ 9
    )
  ) %>%
  dplyr::filter(
    dbh >= top_dob + 1 # make sure dbh is at least as big as top dob
  ) %>%
  dplyr::mutate(
    merch_height = estimate_height(
      spcd = spcd,
      dbh = dbh,
      site_index = 65,
      top_dob = top_dob,
      stand_basal_area = bapa
    ),
    gross_bdft_vol = estimate_volume(
      spcd = spcd,
      dbh = dbh,
      height = merch_height,
      vol_type = "bdft"
    )
  )

merch_bdft %>%
  ggplot2::ggplot(
    ggplot2::aes(
      x = dbh,
      y = gross_bdft_vol,
      color = common_name
    )
  ) +
  ggplot2::geom_point() +
  ggplot2::labs(
    x = "DBH (inches)",
    y = "gross volume (board ft)",
    color = "species"
  )
```

### Biomass

The publication outlines a process for obtaining estimates of green tons
of biomass. This method differs from the methods used by FIA so keep
that in mind if you are attempting to immitate the FIA methodology. The
[FIA methods](https://www.nrs.fs.fed.us/pubs/39555) use the gross cubic
foot volume equations and coefficients from this publication but use a
different process for converting the bole volume estimate into biomass.

``` r
trees_with_biomass <- trees_prepped %>%
  dplyr::mutate(
    biomass = estimate_biomass(
      spcd = spcd,
      dbh = dbh,
      site_index = 65,
      stand_basal_area = bapa
    )
  )

trees_with_biomass %>%
  ggplot2::ggplot(
    ggplot2::aes(
      x = dbh,
      y = biomass,
      color = common_name
    )
  ) +
  ggplot2::geom_point() +
  ggplot2::labs(
    x = "DBH (inches)",
    y = "biomass (green tons)",
    color = "species"
  )
```

branch_name: refs/heads/main

gha_license_id: NOASSERTION


text:
# The Connection Point
![Image](https://i.imgur.com/Dxlry4v.png)

## Example
 * **Clearnet** [HERE](https://lexshadow.cribcraft.co.uk/blog) (If this is offline then please submit a Issues), this might also be a few versions above the Git version as this is a live test bed.
* **Tor V3** [HERE](http://i2dny75d77eukohjtzax6tkbbd53lcsnb4g4wrzj3dbpmayxuv4osdqd.onion/?post=2020-12-20-0) (if this is down/offline give it another try, if it don't work a few hours later feel free to submit a Issue) This might be a few versions behind both the Git and **Cleanweb** versions.

* **Tor V2** [HERE](http://g2dv4s6shqictlln.onion/?post=2020-12-20-0) (if this is down/offline give it another try, if it don't work a few hours later feel free to submit a Issue) This might be a few versions behind both the Git and **Cleanweb** versions.

The connection point is a updated versions of [Dead Simple Blog](https://github.com/paintedsky/dead-simple-blog) by paintedsky

I have updated a lot since Dead Simple Blogs, changed the design and started to work on more functions for it, I liked this idea as I did something like
this in the past without markdown, that markdown seems to be a really cool idea, I also have added Font Awesome, ParsedownExta and my own ParsedownExtraFix
that give us Font Awesome, The system is no longer alost one file but this is because few files made more sence been there own files, this as been fully tested
on the tor network, view the demos above.

The Connection point used to be just a little sister of [Dead Simple Blog](https://github.com/paintedsky/dead-simple-blog) but she has grown in to something in it's
own right, there is more to be added in the future around the same ideas I always created things for, tor frendly, slow or no db servers

This blogging system supports custom pages and a comment system to boot, all based on the same ideals clean simple no database, we don't track a thing the user posts
part from the words so we can show them on the screen lol no IP, no browsr data, not even a username is taken.

Other useful things, no JS, easy to use in plain markdown, same system for pages and blogs, in the future comments and more.

## Bells & Whistles
* Bootstrap design.
* None Java Script.
* Blog returns of 8 (config).
* Blog Pagination.
* Comment System. (config)
* Standalone Page Support.
* Font Awesome Support.
* Tor Friendly(Full No Script)
* Database free.
*  -- More to come.

## Scripting/Design Languages
* PHP
* HTML
* CSS

## Installation

Clone the git, Download to Zip will do, unZip and place on your host, edit the settings in the coreserttings.php found in the config folder.

## Understanding Parsedown and Exta
[Parsedown](https://parsedown.org/demo)
[ParsedownExtra](https://parsedown.org/extra/)

With our ParsedownExtraFix we also have Tick Box's themed.

## Using Font Awesome Tags
You can use the normal html way Font Awesome shows you or you can use `{fas}fa-iconname{/fas}` and this will also convert
it to Font Awesome for you, Titles also support this.

# Changeable Settings
View our site version [View](https://lexshadow.cribcraft.co.uk/blog/?post=0003.txt)
Some of the settings are yet to fully be used and are there as placeholders, some settings wont be listed here yet

## Usage

1. Edit **coresettings.php** in the config folder with your text editor of choice, and change the variables listed above to your liking.
2. To Create a blog create a text file with a NUMERIC file name like so YYYY-MM-DD (e.g. 2018-10-30.txt) for the blogs.
3. To Create a page create a text file with a NUMERIC file name like so NNNN (e.g 0001.txt) for pages
4. Format text files with Markdown, or not. Whatever. ;)
5. If you need to link to image/video/audio/etc. files, you can upload them to the media folder.
6. Upload text files to the "content" directory.
7. You're done!!

## Admin
1. If you have enabled hide mode for comments you open the comments folder and open the YYYY-MM-DD-com file for the page of comments you want
here you then will be able to change Hide to View, under the random number you can also put Lock this will lock the post and you can also put
Admin there also there for making that post stand out as the Admin post.

## Page & Blog Layouts
* The first line of your file is the title line and must be a markdown title so `# Title` will convert in to the title for your link and page/blog
* The second line is the Date and poster information `<small>Posted By: <span style="color:red">Admin</span>, {fas}fa-calendar-alt{/fas} Wednesday 9th {fas}fa-snowman{/fas} December {fas}fa-snowman{/fas} 2020</small>  `
* Optional 3rd line can be used as the back link `[{fas}fa-hand-point-left{/fas} Back](?)`

We would then advice you to start your blog from line **5** or **6**

repository: LexShadow/The-Connection-Point

repo_name: LexShadow/The-Connection-Point


text:
## [v1.2](https://github.com/Almenon/AREPL-vscode/milestone/12?closed=1)

### Added:
Ability to dump local variables and variables at specific points in your program - https://github.com/Almenon/AREPL-vscode/issues/74
Click on errors to google them - https://github.com/Almenon/AREPL-vscode/issues/76

## [v1.1](https://github.com/Almenon/AREPL-vscode/milestone/11?closed=1)

### Added:
GUI library setting - https://github.com/Almenon/AREPL-vscode/issues/68
default imports - https://github.com/Almenon/AREPL-vscode/issues/67

### Fixed:
display of strings - see https://github.com/Almenon/AREPL-vscode/issues/71

## [v1.0](https://github.com/Almenon/AREPL-vscode/milestone/10?closed=1)

### Added:
Changelog in landing page (see [#58](https://github.com/Almenon/AREPL-vscode/issues/58))

Better landing page with examples (see [#32](https://github.com/Almenon/AREPL-vscode/issues/32))

Better display of variables (see [#63](https://github.com/Almenon/AREPL-vscode/issues/63))

### Fixed:
Relative imports not working (see [#69](https://github.com/Almenon/AREPL-vscode/issues/69))

---

## [v9](https://github.com/Almenon/AREPL-vscode/milestone/9?closed=1)

### Added:
Added telemetry (see [#50](https://github.com/Almenon/AREPL-vscode/issues/51)).
This is optional and can be turned off in the settings.

Having this turned on helps me analyze how many users I have, what settings are useful to them, and how frequently they use AREPL. It also reports internal errors with AREPL backend to help diagnose bugs.

### Fixed:
Exception stacktrace used to include internal AREPL stacktrace - now the stacktrace only shows info relative to your code (see [#51](https://github.com/Almenon/AREPL-vscode/issues/51))

---

## v8

Fixed too many prints slowing or freezing the preview.  See [#37](https://github.com/Almenon/AREPL-vscode/issues/37)

## v7

Fixing case issue causing error in linux systems

## v6

see https://github.com/Almenon/AREPL-vscode/milestone/6?closed=1

Fixed #47 new arepl session command fails when user does not have doc open

Implemented #33 footer bar with feedback links

## v5:

see https://github.com/Almenon/AREPL-vscode/milestone/5

### Added:
* Setting to skip landing page
* Setting for print results at top
* Command to execute highlighted code in AREPL
* command for creating new file
* allow user to customize pythonPath and pythonOptions
* allow user to execute on save

## Fixed:
* timing is not sticky

repository: cssho/AREPL-vscode

repo_name: cssho/AREPL-vscode


text:
# Architecture overview

**Model/Controller pattern.** Convector is designed to help you write reusable pieces of code that describe the nature of what a developer can do in a blockchain. A blockchain, in the developer’s eyes, is no more than a data layer protected by a logic layer defining the rules of what the outside world can do in with the inner data. Thus, a really comfortable way of writing chaincode logic (smart contracts) is by having Models describing the shape of the data and Controllers describing the actions and rules that apply to the models.

Convector has been built taking in consideration the best out of the modern architectural design landscape. Its modular approach aims to accompany you through the whole development cycle, whether through its **Core Components** or the already existing **Convector Tools**.

You usually focus the most on the Specification, a.k.a models and controllers, to make sure they do what the network expects them to do. A blockchain (for the developer's eyes) is no more than a data layer protected by a logic layer defining the rules of what the outside world can do in with the inner data. Thus, a really comfortable way of writing chaincode logic (_smart contracts_) is by having **Models** describing the shape of the data and **Controllers** describing the actions and rules that apply to the models.

* *Models* are real world objects or concepts (like a token, a cryptocurrency, a contract, a car, a container, a user...) with specific characteristics (like a name, a owner, a deadline...) that you structure for your project.
* *Controllers* are real world actions acting over objects (models). E.g.: build a car, transferring ownership, reporting an accident. It's the business logic of your sysem.

You can then include that project at any layer of your application, from the blockchain to the front end. You only need to specify the corresponding adapter and storage containing the functions implementations and storage target of that layer. For example, to test, you may include a mock storage to see if your blockchain logic works before deploying it.

By using the built-in storages and adapters, most of the basics are covered. For example, saving to the blockchain validating the wallet (certificate) submitting the transaction, or calling the blockchain peers.

## Convector Core

All the `@worldsibu/convector-core-*` packages. It provides all the necessary code to write contract specifications using the *Model/Controller* pattern.

### Convector Storage

Convector is designed thinking in a modular design from its conception. A model not only can be used at the chaincode layer, since most of the time you'll have to use the same model in your services or front-end application, the models can be used anywhere. The difference of its behavior is the **storage** layer it uses. At chaincode the storage is the _Fabric Shim_ to save and read data in the blockchain. But if you whish to run a model in a NodeJS backend, the storage layer can be swapped by the CouchDB storage layer, which will allow you to read data, but not write. In a browser environment you can even create your own storage layer mapping to your back-end api.

> An *Storage* is the basic data layer of your entity (Model) which defines where the object will be stored (added, updated, removed).

### Convector Adapters

Following the modular design pattern from models, controllers have **adapters**, they are the handlers to route the requests to the appropriate layer. In a blockchain it will be the Fabric API, but on NodeJS it might be the _Fabric Client SDK_, on unit tests it might be a mock class, and on browser it can map to your APIs.

> You may think of *Adapters* as the specific logic. It varies based on the layer you are using the code.

## Convector Tools

All the `@worldsibu/convector-tool-*` packages. They provide a set of helpers and utils to make the chaincode development easier.

### Chaincode Manager

Used to bundle controllers in a single chaincode and handle the installation and invokation.

### Dev Environment

It's a basic dev environment created with Fabric running on docker or vagrant. Contains two organization and three users in that organization, two channels, one orderer, one peer per org with its database, and all the cryptographic material for this to work.

## A high level view

A typical distribution and usage of the components goes as follow (asumming you have a [mono-repo](https://danluu.com/monorepo/), if not, then distribute according to the **"Why-column"** which explains what that package installation will give you):

| Project/Layer | Why | Command |
| --- | --- | --- |
| Root of your project | To have a dev env and the utility that will let you install, upgrade, invoke and so on, the chaincodes. | `npm install -D @worldsibu/convector-tool-{dev-env,chaincode-manager}` |
| Root chaincode project. E.g.: chaincodes/ | So that you can share settings between your multiple chaincodes, such as development environment, tests and testing scripts, blockchain installation setup (what to install, where), etc. | `npm install -D @worldsibu/convector-{adapter-mock,tool-{dev-env,chaincode-manager}} chai mocha @types/chai @types/mocha ts-node` |
| At for each of your chaincode projects. E.g.: chaincodes/cc-token | Each chaincode can be a separate project so that you don't have to carry everything when including in another layer of your stack. |  `npm install -SE @worldsibu/convector-core-{model,controller} && npm i -S yup reflect-metadata && npm i -D @types/yup` |
| At your backend / api | It typically calls the nodes (peers) of your blockchain, but it may call the World State or other services as well. |  Include each of your chaincode projects, they will carry the basic dependencies `npm install -SE @worldsibu/convector-{adapter-fabric,storage-couchdb} @types/bytebuffer` |
| At the front end | Here you may be calling your backend/api server, it is great to have the interfaces and structures coming right from the chaincodes layer so that you don't have to copy everything. |  Include each of your chaincode projects, they will carry the basic dependencies. |

---

## What's next

* [[Packages]]
* [[Models]]
* [[Controllers]]
* [[Chaincode-Manager]]
* [[Development-Environment]]

----

## Relevant references

* [[Getting-Started]]
* [Dev resources in our blog](https://medium.com/worldsibu/for-devs/home)
* [A fullstack TypeScript project showcasing Convector](https://github.com/worldsibu/convector-example-drug-supply-chain)
* [A bootstrap project for you](https://github.com/worldsibu/convector-boilerplate)

repository: hyperledger-labs/convector

branch_name: refs/heads/develop

repo_name: hyperledger-labs/convector


text:
Each image has size 512 x 512 and is annotated at the pixel level. The annotation of SECOND is carried out by an expert group of earth vision applications, which guarantees high label accuracy. For the change category in the SECOND dataset, we focus on 6 main land-cover classes, i.e. , non-vegetated ground surface, tree, low vegetation, water, buildings and playgrounds , that are frequently involved in natural and man-made geographical changes.

## Links
You can download this dataset in http://www.captain-whu.com/PROJECT/SCD/

## References
If you use this dataset for your projects, please take the time to cite their paper:
```
@misc{yang2020asymmetric,
title={Asymmetric Siamese Networks for Semantic Change Detection},
author={Kunping Yang and Gui-Song Xia and Zicheng Liu and Bo Du and Wen Yang and Marcello Pelillo},
year={2020},
eprint={arXiv:2010.05687},
}
```

repository: swjtulinxi/ChangeDetectionRepository

repo_name: swjtulinxi/ChangeDetectionRepository


text:
# E-commerce Web

E-commerce Web is a full stack website that has similar functionality as a [online shopping platform](https://uexpress.ca/).

## Getting Started

These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.

### Prerequisites

Here is the [stack](https://en.wikipedia.org/wiki/MEAN_(solution_stack)) we will be using for this project.
  * Mysql (document database)
  * Express (back-end application framework)
  * React or Angular (front-end application framework)
  * Node.js (JavaScript runtime environment)

### Installing

To install a MEAN stack, please check links below:
  * [Install MEAN Stack](http://osa.ma/2018/install-mean-stack-on-mac/)
  * [Install Node](https://nodejs.org/en/download/)

## Running the tests

Explain how to run the automated tests for this system

### Break down into end to end tests

Explanation

```
Give an example
```

### And coding style tests

Explanation

```
Give an example
```

## Deployment

Add additional notes about how to deploy this on a live system

## Built With

* [Dropwizard](http://www.dropwizard.io/1.0.2/docs/) - The web framework used
* [Maven](https://maven.apache.org/) - Dependency Management
* [ROME](https://rometools.github.io/rome/) - Used to generate RSS Feeds

## Contributing

Please read [CONTRIBUTING.md](https://gist.github.com/PurpleBooth/b24679402957c63ec426) for details on our code of conduct, and the process for submitting pull requests to us.

## Versioning

We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags).

## Authors

* **Luca(MingCong) Zhou** - *Initial work* - [chefZau](https://github.com/chefZau)
* **Rocky(YuanKun) Li** - *Initial work* - [RockyOrz](https://github.com/RockyOrz)
* **Kevin Gao** - *Initial work* - [kevaa](https://github.com/kevaa)

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

## License

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

## Acknowledgments

* Hat tip to anyone whose code was used
* Inspiration
* etc


text:
---
id: getting-started
title: Getting Started
---

## Create React App

StateX is a state management library for React, so you need to have React installed and running to use StateX. The easiest and recommended way for bootstrapping a React application is to use Create React App

```shell
npx create-react-app my-app --template statex-typescript
```

> `npx` is a package runner tool that comes with npm 5.2+ and higher.

For more ways to install Create React App, see the official documentation.

## Installation

The StateX package lives in npm. To install the latest stable version, run the following command:

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

<Tabs
defaultValue="yarn"
values={[
{ label: 'Yarn', value: 'yarn', },
{ label: 'NPM', value: 'npm', },
]
}>
<TabItem value="yarn">

```bash {1}
yarn add @cloudio/statex
```

</TabItem>
<TabItem value="npm">
```bash {1}
npm install --save @cloudio/statex
```
</TabItem>
</Tabs>

## Provider

Components that use atom state need **StateXProvider** to appear somewhere in the parent tree. A good place to put this is in your root component:

```jsx {6,8}
import React from 'react';
import { StateXProvider } from '@cloudio/statex';

function App() {
  return (
    <StateXProvider>
      <CharacterCounter />
    </StateXProvider>
  );
}
```

We'll implement the `CharacterCounter` component in the following section.

## Atom

An **atom** represents a node in the global **state** tree. Atoms can be read from and written to from any component. Components that read the value of an atom are implicitly **subscribed** to that atom, so any atom updates will result in a re-render of all components subscribed to that atom:

```javascript
const textAtom = atom({
  // unique path in the state tree
  path: ['mystate', 'text'],
  defaultValue: '', // initial value
});
```

Components that need to read from _and_ write to an atom should use `useStateX()` as shown below:

```jsx
function CharacterCounter() {
  return (
    <div>
      <TextInput />
      <CharacterCount />
    </div>
  );
}

function TextInput() {
  const [text, setText] = useStateX(textAtom);

  const onChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div>
      <input value={text} onChange={onChange} />
      <br />
      Echo: {text}
    </div>
  );
}
```

## Selector

A **selector** represents a piece of **derived atom**. Derived atom is a **transformation** of one or more atoms. You can think of derived atom as the output of passing atom to a pure function that modifies the given atom in some way:

```jsx
const charCountSelector = selector({
  path: ['mystate', 'charCount'], // unique path
  get: ({ get }) => {
    const text = get(textAtom);

    return text.length;
  },
});
```

We can use the `useStateXValue()` hook to read the value of `charCountSelector`:

```jsx
function CharacterCount() {
  const count = useStateXValue(charCountSelector);

  return <>Character Count: {count}</>;
}
```

We can use also use just the path, without having to define an atom, to read or write the state at any node in the tree. Below, is an example where we read the root JSON object at the root atom which has a nested atom 'mystate' which intern has 'text' & 'charCount'

```jsx
function JSONPayload() {
  const json = useStateXValue(['mystate'], {});

  return <pre>{JSON.stringify(json, null, '  ')}</pre>;
}
```

## Demo

Below is the finished product:

```jsx live
const textAtom = atom({
  path: ['mystate', 'text'],
  defaultValue: '',
});

const charCountSelector = selector({
  path: ['mystate', 'charCount'],
  defaultValue: 0,
  get: ({ get }) => {
    const text = get(textAtom);

    return text.length;
  },
});

function CharacterCounter() {
  return (
    <>
      <TextInput />
      <CharacterCount />
      <JSONPayload />
    </>
  );
}

function CharacterCount() {
  const count = useStateXValue(charCountSelector);

  return <>Character Count: {count}</>;
}

function JSONPayload() {
  const json = useStateXValue([], {});

  return (
    <>
      <pre>{JSON.stringify(json, null, '  ')}</pre>
    </>
  );
}

function TextInput() {
  const [text, setText] = useStateX(textAtom);

  const onChange = (event) => {
    setText(event.target.value);
  };

  return (
    <div>
      <input value={text} onChange={onChange} />
      <br />
      Echo: {text}
    </div>
  );
}

return <CharacterCounter />;
```

repository: CloudIOInc/statex

repo_name: CloudIOInc/statex


text:
---
layout: things-include
title: Brisbane
state: queensland
tag: things-brisbane
---
**Brisbane** • [Gold Coast](gold-coast) • [Sunshine Coast](sunshine-coast) • [Bundaberg](bundaberg) • [Cairns](cairns)

The capital city of Queensland. It is pretty small, but it’s pretty nice.

It's probably the most outdoors-y of the various state capitals, but they think that filling the CBD with one-way streets is a good idea, so it's by no means perfect.

Like most developed cities, they have a fancy integrated transport ticketing system, but Brisbane’s public transport includes catamarans all along the river that they call CityKats, and that has always amused me.

gha_language: HTML


text:
---
title: "Tweaking Subtext with Hero Shots next to each post"
disqus_identifier: https://www.matthidinger.com/archive/2011/12/12/tweaking-subtext-with-hero-shots-next-to-each-post.aspx
redirect_from: /archive/2011/12/12/tweaking-subtext-with-hero-shots-next-to-each-post.aspx/
tags:
- subtext
- open-source
header:
  teaser: subtext-content/www_matthidinger_com/Windows-Live-Writer/Modify_8E10/image_thumb_1.png
---
![](/images/subtext-content/www_matthidinger_com/Windows-Live-Writer/Modify_8E10/image_thumb_1.png)

This past weekend I decided to upgrade my Subtext blog to VS 2010 so I could finally rid my machine of VS 2008. After some small hiccups it was ready to rock, and thankfully the deployment to my server was entirely painless with WebDeploy.

So being in VS 2010 and having fully tested my deployment process it seemed like a good time to make a tweak to my Skin that I’ve been wanting to try for a while: showing “Hero Shots” next to each post.

Hero shots?
-----------

I’m not really sure what they should be called, I just know I’ve heard the term hero shot a lot this year and it seemed to fit, but call it whatever you want

The idea is pretty simple: when viewing a list of posts (the home page, a specific tag, the archives) I want to show an image that helps illustrate the topic and allow for easier scanning with the eye.

As for implementation I wanted to allow some basic configuration of the hero shot from within Live Writer (or whatever you use to author posts). It goes something like this:

1.  Find an  within each post and if found, float it inline with the PostText
2.  If no images have that ID, then grab the first  and float it inline with the PostText
3.  If I want to entirely disable a Hero Shot for a post then I just add a
 into the post body

Cool, what’s the tweak?
-----------------------

First I used NuGet to get HtmlAgilityPack – the absolute best way to work with an HTML string.

#### Install-Package HtmlAgilityPack

With that installed the change to Subtext was actually really simple. Within EntryList.cs I found where it was binding the Post Text and added the BindHeroShot() method seen below. BindHeroShot encapsulates that logic described above. The code below will respect Skins which do not use the PostImage, so this change should not affect any themes without a PostImage control declared.

#### Subtext.Web\\UI\\Controls\\EntryList.cs

```csharp
private void BindPostText(RepeaterItemEventArgs e, Entry entry)
{
    BindHeroShot(e, entry);

    var postText = (Literal)e.Item.FindControl("PostText");

    if(DescriptionOnly)
    {
        postText.Text = entry.HasDescription
                ? string.Format(CultureInfo.InvariantCulture, "<p>{0}</p>", entry.Description)
                : ShowTruncatedBody(entry, 150);
    }
    else
    {
        postText.Text = entry.HasDescription ? entry.Description : entry.Body;
    }
}

/// <summary>
///  Get the first image in a post to use as the "Hero Shot" on the list of entries
/// </summary>
private static void BindHeroShot(RepeaterItemEventArgs e, Entry entry)
{
    var postImage = e.Item.FindControl("PostImage") as System.Web.UI.WebControls.Image;
    if (postImage != null)
    {
        postImage.Visible = false;

        var html = new HtmlDocument();
        html.LoadHtml(entry.Body);

        var noHero = html.DocumentNode.SelectSingleNode("//div[@id='no-hero']");
        if (noHero != null)
            return;

        var img = html.DocumentNode.SelectSingleNode("//img[@id='hero']")
                  ?? html.DocumentNode.SelectSingleNode("//img");

        if (img != null)
        {
            postImage.Visible = true;
            postImage.ImageUrl = HttpUtility.HtmlDecode(img.Attributes["src"].Value);
        }
    }
}
```

That’s actually all that had to be changed in Subtext. The rest of the changes take place in your current Skin.

#### Subtext.Web\\Skins\\{YourSkin}\\EntryList.ascx

Below is the Repeater which shows each Post, the only thing I added to it was an **<asp:Image ID=”PostImage”/>**

```csharp
<asp:Repeater runat="server" ID="Entries" OnItemCreated="PostCreated">
    <ItemTemplate>
        <div class="post">
            <div class="title">
                <asp:HyperLink runat="server" ID="TitleUrl" />
                <asp:HyperLink runat="server" ID="editLink" />
            </div>
            <div class="body">
                <asp:Image runat="server" ID="PostImage" CssClass="post-hero-image" />
                <asp:Literal runat="server" ID="PostText" />
                <div class="clear">
                </div>
            </div>
        </div>
    </ItemTemplate>
</asp:Repeater>
```

#### Subtext.Web\\Skins\\{YourSkin}\\style.css

Naturally I gave the PostImage a CSS Class so I could style it. I chose to float it right and give it max height and widths so it doesn’t take up the entire post. You can of course tweak this any way you like – this part is entirely in your skin. Put the image wherever and style it how you like.

```csharp
.post-hero-image
{
    float: right;
    margin: 0 0 6px 10px;
    max-height: 200px;
    max-width: 400px;
}
```

Summary
-------

All in all pretty small tweaks and I actually like how it turned out. I think images next to the posts make it a lot easier to scan topics as I’m scrolling down the page. If you agree and are using Subtext then hopefully this post will make it easy to add to your blog!


text:
---
title: "Pożeracz Yeti"
date: 2019-01-21T19:21:18.175Z
translationKey: "yeti-eater"
slug: "pozeracz-yeti"
order: 2
tags:
  - findNearest
---

> Zabij Yeti . Wchłoń Yeti . Następny Yeti!

https://codecombat.com/play/level/yeti-eater

Rozwiązanie

```javascript
// Yetis surround us and we need to defeat them.
// Luckily the wizard had time to cast the sleep spell.
// Your hero can devour the yetis' vital powers when they are defeated.
// Defeat them in the order from weakest to the strongest.

// The wizard sorted enemies, but in the order from the strongest to the weakest.
var wizard = hero.findNearest(hero.findFriends());
var yetis = wizard.findEnemies();

// You need iterate the yetis list in the reverse order with a 'for-loop'.
// The start value should be 'yetis.length - 1'.
// Iterate while the index greater than -1.
// Use the negative step -1.
for(var i = yetis.length -1 ; i >= 0; i--) {
    // Attack each enemy while its health greater than 0.
    while( yetis[i].health > 0) {
        hero.attack(yetis[i]);
    }
}

// Look at the guide to get hints.

```

Potrzebne przedmioty z |
--- |
findNearest |
findFriends |
attack |

repository: LukaszSarzynski/static-site-go

repo_name: LukaszSarzynski/static-site-go


text:
# Sublime Configuration

These are my settings and snippets

## Snippet Guide

```
fsl --> # frozen_string_literal: true
factory --> FactoryBot.define do..end
service --> class Service..end
```

repository: rebelweb/dotfiles

gha_language: Vim script

repo_name: rebelweb/dotfiles


text:
---
title: "Key Generation Reference"
date: 2020-12-22
permalink: /keygen/keygen-reference/
categories:
  - Research
  - Key Generation
tags:
  - Key Generation
  - Reference
---

This paper summarizes some important key generation references.

# Review/Survey/Tutorial on Key Generation
1. **Junqing Zhang**, Guyue Li, Alan Marshall, Aiqun Hu, and Lajos Hanzo, “A New Frontier for IoT Security Emerging From Three Decades of Key Generation Relying on Wireless Channels,” _IEEE Access_, vol. 8, pp. 138406 - 138446, 2020. [link](https://ieeexplore.ieee.org/document/9149584){:target="_blank"}
1. **Junqing Zhang**, Trung Q. Duong, Alan Marshall, and Roger Woods, “Key generation from wireless channels: A review,” _IEEE Access_, vol. 4, pp. 614- 626, Mar. 2016. Open Access. [link](https://ieeexplore.ieee.org/abstract/document/7393435){:target="_blank"}
1. **Junqing Zhang**, Trung Q. Duong, Roger Woods, and Alan Marshall, “Securing wireless communications of the Internet of Things from the physical layer, An overview,” _Entropy_, vol. 19, no. 8, 420, 2017. (Invited Paper) [link](https://www.mdpi.com/1099-4300/19/8/420){:target="_blank"}
1. Guyue Li, Chen Sun, **Junqing Zhang**, Eduard Jorswieck, Bin Xiao, Aiqun Hu, “Physical Layer Key Generation in 5G and Beyond Wireless Communications: Challenges and Opportunities,” _Entropy_, vol. 21, no. 5, 497, 2019. [link](https://www.mdpi.com/1099-4300/21/5/497){:target="_blank"}
1. Christopher Huth, René Guillaume, Thomas Strohm, Paul Duplys, Irin Ann Samuel, and Tim Güneysu. “Information reconciliation schemes in physical-layer security: A survey.” _Computer Networks_, vol. 109, pp: 84-104, Nov. 2016. [link](https://www.sciencedirect.com/science/article/pii/S1389128616301864){:target="_blank"}
1. Tao Wang, Yao Liu, and Athanasios V. Vasilakos, ‘‘Survey on channel reciprocity based key establishment techniques for wireless systems,’’ _Wireless Networks_, vol. 21, no. 6, pp. 1835–1846, Aug. 2015. [link](https://link.springer.com/article/10.1007/s11276-014-0841-8){:target="_blank"}
1. Kai Zeng, ‘‘Physical layer key generation in wireless networks: Challenges and opportunities,’’ _IEEE Communications Magazine_, vol. 53, no. 6, pp. 33–39, Jun. 2015. [link](https://ieeexplore.ieee.org/document/7120014){:target="_blank"}
1. Kui Ren, Hai Su, and Qian Wang, ‘‘Secret key generation exploiting channel characteristics in wireless communications,’’ _IEEE Wireless Communications_, vol. 18, no. 4, pp. 6–12, Aug. 2011. [link](https://ieeexplore.ieee.org/document/5999759){:target="_blank"}

# Tool
* NIST SP 800-22: A Statistical Test Suite for the Validation of Random Number Generators and Pseudo Random Number.[Link] C code available for download. Python implementation can be downloaded from here.

Return to the Main Page of [Key Generation From Wireless Channels](https://junqing-zhang.github.io/research-area/keygen/){:target="_blank"}.


text:
---
title: "영어 단어 공부 101"
collection: memo
type: "voca"
permalink: /memo/voca-101
date: 2021-01-04
venue: "jj"
---

매일 공부한 단어를 복습하는 겸 남기는 메모장입니다.

| 단어 | 뜻 | 예문 |
| --------         | ------ | ------------------------------------------------------------ |
| renewable energy | 재생 가능한 에너지 | The energy policy by the government is focusing on developing **renewable energy** |
| solar energy | 태양 에너지 |  |
| strike a balance | 균형을 맞추다 | We need to **strike a balance** between energy development and environmental protection |
| strive | 노력하다 | Scientists **strive** to solve the global energy crisis by developing alternative energy |
| substitute | 대체하다 | It is difficult or impossible to entirely substitute the fossil fuel use with biofuels |
| sustainable | 지속 가능한 | Wind power is the cleanest and most **sustainable** source of energy |
| turbine | 터빈, 엔진기관 | The government invested 5 billion dollars on wind **turbines** powering the rotations |
| unleaded petrol | 무연 휘발유 | Using **unleaded petrol** is beneficial to protect the environment and save money on petrol |
| vehicle | 차량, 운송 수단 | The amount of C02 aircrafts released is about three times greater than **vehicles** on the ground |


text:
# hwk [![Build Status](https://travis-ci.org/lukasmartinelli/hwk.svg?branch=master)](https://travis-ci.org/lukasmartinelli/hwk) ![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)

> :warning: Please use **[Hawk](https://github.com/gelisam/hawk)**.
  While **hwk** is a hacky MVP to test how well Haskell works as text processing language, **Hawk** is a more mature tool. This repository is no longer maintained by Lukas Martinelli.

<img align="right" alt="hwk" src="hwk.png" />

**hwk** tries to demonstrate how a modern Haskell based stream manipulation tool could look like.
It is similar to tools like **awk** or **sed**.
`hwk` allows compact command sequences that operate on a list of strings. Because Haskell is lazy and has a powerful arsenal of functions, there is no need to invent another DSL and hopefully
push people into using functional goodness. `hwk` also provides a method to store small functions for
reuse in environment variables.

## Example

```bash
# prepend a string to each line
seq 1 10 | hwk 'map ("number " ++)'

# load the negative function into the current environment
eval $(hwk env negative '(0 >)')

# sum all negative numbers
# the ints function transforms a list of strings into a list of ints
seq -100 100 \
  | hwk '\lines -> filter negative $ ints lines' \
  | hwk '\lines -> sum $ ints lines'

# get first two columns of tsv file
# `cabal install split` to use the library for splitting lists
cat data.tsv |
  | hwk '\lines -> map (take 2) $ map (splitOn "\t") lines'
```

The argument passed to `hwk` must be a valid Haskell statement. It should always return a function that takes a list of strings and returns either a new list or a single element.
The `hwk env` command loads the statement into the environment with the specified function name for later reuse.

## Install

To install `hwk` locally you need [Haskell](https://www.haskell.org/platform/) and
the [stack build tool](http://docs.haskellstack.org/en/stable/install_and_upgrade.html).
You can build the binary with stack or cabal.

```bash
git clone https://github.com/lukasmartinelli/hwk
cd hwk
stack build

# or with cabal
cabal install
```

## What does `hwk` do?

- `hwk` will generate code and execute it under `runhaskell`.
- `hwk` will try to lookup functions in the passed environment variables.
- `hwk` tries to convert the different result types into a list of strings `[String]`.
- `hwk` provides additional functions that help with converting streams.

## Supported return types

The `hwk` statement can return the following types.

- `[String]`
- `[[String]]`
- `[Integer]`
- `String`
- `Integer`

## What happens under the Hood?

The `hwk` code above can be translated directly into a valid Haskell program.

```haskell
ints = map (\l -> read l :: Int)
hwk = \lines -> filter (0 >) $ ints lines

main = do
    contents <- getContents
    mapM_ putStrLn $ map (\r -> show r) $ hwk $ lines contents
```

The second `hwk 'foldl (+) 0'` command will translate to.

```haskell
ints = map (\l -> read l :: Int)
hwk = \lines -> foldl (+) 0 $ ints lines

main = do
    contents <- getContents
    mapM_ putStrLn $ map (\r -> show r) $ hwk $ lines contents
```

## Alternatives

- https://github.com/gelisam/hawk
- https://code.google.com/p/pyp/
- https://en.wikipedia.org/wiki/AWK
- https://en.wikipedia.org/wiki/Sed

repository: lukasmartinelli/hwk

repo_name: lukasmartinelli/hwk


text:
FILTERS

### A filter, in the context of the Linux command line, is a program that accepts textual data and then transforms it in a particular way. Filters are a way to take raw data, either produced by another program, or stored in a file, and manipulate it to be displayed in a way more suited to what we are after

__Commands__

    head [-number of lines to print] [path] - view the first n lines of data

    tail [-number of lines to print] [path] - view the last n lines of data

    sort [-options] [path] - organize the data into order

    nl [-options] [path] - number lines - print line numbers before data

    wc [-options] [path] - word count

    cut [-options] [path] - cut the data into fields

    sed <expression> [path] - stream editor

    uniq [options] [path] - unique

    tac [path]

    ###  Additional commands

        awk
        diff

__Concepts__

    Processing
        Filters allow us to process and format data in interesting ways.
    man pages
        Most of the programs we looked at have command line options that allow you to modify their behaviour.

__Examples__

    * beginning
    cat mysampledata.txt
    Fred apples 20
    Susy oranges 5
    Mark watermellons 10
    Robert pears 5
    Terry oranges 10
    Lisa peaches 10
    Susy oranges 15
    Mark grapes 40
    Anne mangoes 5
    Greg pineapples 5
    Oliver rockmellons 5
    Betty limes 15

    * end

    tac mysampledata.txt
    Betty limes 14
    Oliver rockmellons 2
    Greg pineapples 3
    Anne mangoes 7
    Mark grapes 39
    Susy oranges 12
    Lisa peaches 7
    Terry oranges 9
    Robert pears 4
    Mark watermellons 12
    Susy oranges 5
    Fred apples 20