text:
# Tree Data Structure Java Library

[![Build Status](https://travis-ci.org/Scalified/tree.svg)](https://travis-ci.org/Scalified/tree)
[![Maven Central](https://img.shields.io/maven-central/v/com.scalified/tree.svg)](http://search.maven.org/#search|gav|1|g%3A%22com.scalified%22%20AND%20a%3A%22tree%22)

## Description

This Library contains different implementations of the tree data structures, such as K-ary, binary, expression trees etc.

## Requirements

The Library requires [Java SE Development Kit 7](http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u80-oth-JPR) or higher

## Gradle dependency

```java
dependencies {
	compile 'com.scalified:tree:0.2.5'
}
```

## Theory

### Definition

A **tree data structure** can be defined recursively (locally) as a collection of nodes (starting at a root node),
where each node is a data structure consisting of a value, together with a list of references to nodes (the children),
with the constraints that no reference is duplicated, and none points to the root

A tree is a (possibly non-linear) data structure made up of nodes or vertices and edges without having any cycle.
The tree with no nodes is called the *null* or *empty* tree. A tree that is not empty consists of a root node and
potentially many levels of additional nodes that form a hierarchy

### Terminology

**Node** - a single point of a tree

 **Edge** - line, which connects two distinct nodes

 **Root** - top node of the tree, which has no parent

 **Parent** - a node, other than the root, which is connected to other successor nodes

 **Child** - a node, other than the root, which is connected to predecessor

 **Leaf** - a node without children

 **Path** - a sequence of nodes and edges connecting a node with a descendant

 **Path Length** - number of nodes in the path - 1

 **Ancestor** - the top parent node of the path

 **Descendant** - the bottom child node of the path

 **Siblings** - nodes, which have the same parent

 **Subtree** - a node in a tree with all of its proper descendants, if any

 **Node Height** - the number of edges on the longest downward path between that node and a leaf

 **Tree Height** - the number of edges on the longest downward path between the root and a leaf (root height)

 **Depth (Level)** - the path length between the root and the current node

 **Ordered Tree** - tree in which nodes has the children ordered

 **Labeled Tree** - tree in which a label or value is associated with each node of the tree

 **Expression Tree** - tree which specifies the association of an expression's operands and its operators in a
                    uniform way, regardless of whether the association is required by the placement of parentheses
                    in the expression or by the precedence and associativity rules for the operators involved

 **Branching Factor** - maximum number of children a node can have

 **Pre order** - a form of tree traversal, where the action is called firstly on the current node, and then the
              pre order function is called again recursively on each of the subtree from left to right

 **Post order** - a form of tree traversal, where the post order function is called recursively on each subtree from
               left to right and then the action is called

### Trees Representation

#### Array-of-Pointers

One of the simplest ways of representing a tree is to use for each node a structure, which contains an array of
pointers to the children of that node

The maximum number of children a node can have is known as **branching factor (BF)**

The *ith* component of the array at a node contains a pointer to the *ith* child of that node.
A missing child can be represented by a **null** pointer

![Array-of-Pointers Representation](https://github.com/Scalified/tree/blob/master/assets/array_of_pointers_representation.png)

**Array-of-Pointers** representation makes it possible to quickly access the *ith* child of any node

This representation, however, is very wasteful of space when only a few nodes in the tree have many children.
In this case, most of the pointers in the arrays will be **null**

> The Library, however, is optimized for using Array-of-Pointers representation likewise it is done in the
**java.util.ArrayList**. The subtrees size grows automatically in case of reaching the limit. Additionally you may
specify what is called a *branching factor*, that the initial number of subtrees before grow (like *capacity* in
the **java.util.ArrayList**)

#### Leftmost-Child—Right-Sibling

In the **Leftmost-Child—Right-Sibling** representation each node contains a pointer to its leftmost child; a node does
not have pointers to any of its other children. In order to locate the second and subsequent children of a node *n*,
the children link list created, in which each child *c* points to the child of *n* immediately to the right of *c*.
That node is called the right sibling of *c*

![Leftmost-Child-Right-Sibling Representation](https://github.com/Scalified/tree/blob/master/assets/leftmost_child_right_sibling_representation.png)

In the figure above *n3* is the right sibling of *n2*, *n4* is the right sibling of *n3*, and *n4* has no right sibling.
The children of *n1* can be found by following its leftmost-child pointer to *n2*, then the right-sibling pointer to
*n3*, and then the right-sibling pointer of *n3* to *n4*. *n4*, in turn has no right-sibling pointer (it is **null**
indeed), therefore *n1* has no more children

The figure above can be represented in such a way:

![Leftmost-Child-Right-Sibling Another Representation](https://github.com/Scalified/tree/blob/master/assets/leftmost_child_right_sibling_another_representation.png)

The downward arrows are the leftmost-child links; the sideways arrows are the right-sibling links

### Recursions on Trees

![Recursion on Trees](https://github.com/Scalified/tree/blob/master/assets/recursion_on_trees.png)

#### Traversal

**Traversal** is a process of visiting each node in a tree data structure, exactly once, in a systematic way

**Pre order** is a form of tree traversal, where the action is called firstly on the current node, and then the
pre order function is called again recursively on each subtree from left to right

Pre order listing on the figure is: **+ a − b c d**

**Post order** is a form of tree traversal, where the post order function is called recursively on each subtree
from left to right and then the action is called

Post order listing on the figure is: **a b c − d * +**

#### Evaluating Expression Tree

There are three types of expressions: **infix**, **prefix** and **postfix**

**Infix** are expressions in the ordinary notation, where binary operators appear between their operands. For the
figure above the *infix* expression is: **a + (b − c) * d**. The equivalent *prefix* and *postfix* expressions are:
**+ a − b c d** for *prefix* and **a b c − d * +** for *postfix*

Having either the *prefix* or *postfix* expression the *infix* expression can be constructed in a simple way.
For instance, in order to construct the *infix* expression from prefix one, firstly the operator that is followed by
the required number of operands with no embedded operators must be found

In prefix expression **+ a * − b c d** the **− b c** is such a string, since the minus sign, like all operators
in running example takes two operands. This subexpression is then replaced by a new symbol, say **x = − b c**. Then,
this process of identifying an operator followed by its operands repeated again. Now the expression is: **+ a * x d**.
The next subexpression will be **y = * x d**. This reduces the target expression to **+ a y**, which is lastly
converted to just **a + y**

The remainder of the infix expression **a + y** then is reconstructed by retracing the steps above. Firstly,
the *y* is substituted to **x * d**, changing the target expression to: **a + (x * d)**. And lastly the *x* is replaced
by **− b c** or simply **b − c**. So the target expression now is: **a + ((b − c) * d)** or **a + (b − c) * d**

The conversion from *postfix* to *infix* expression uses the same algorithm. The only difference is that firstly
the operator, which is preceded by the requisite number of operands must be found in order to decompose the *postfix*
expression

#### Structural Induction

**Structural Induction** is a proof method that is used to prove some statement *S(T)* is true for all trees *T*

![Structural Induction](https://github.com/Scalified/tree/blob/master/assets/structural_induction.png)

For the basis *S(T)* must be shown to be true when *T* consists of a single node. For the induction, *T* is supposed
to be a tree with root *r* and children *c1*, *c2*, …, *ck*, for some *k ≥ 1*. If *T1*, *T2*, …, *Tk* are the subtrees
of *T* whose roots are *c1*, *c2*, …, *ck* respectively, then the inductive step is to assume that *S(T)* is true
for all trees *T*. Structural Induction does not make reference to the exact number of nodes in a tree, except to
distinguish the basis (one node) from  the inductive step (more than one node)

The general template for Structural Induction has the following outline:

1. Specify the statement *S(T)* to be proved, where *T* is a tree
2. Prove the basis, that *S(T)* is true whenever *T* is a tree with a single node
3. Set up the inductive step by letting *T* be a tree with root *r* and *k ≥ 1* subtrees, *T1*, *T2*, …, *Tk*.
State that the inductive hypothesis assumed: *S(Ti)* is true for each of the subtrees *Ti*, *i = 1*, *2*, …, *k*
4. Prove that *S(T)* is true under the assumptions mentioned in step 3

Structural Induction is generally needed to prove the correctness of a recursive program that acts on trees

As an example of using the Structural Induction to prove the correctness of statement the  evaluate function
(listed above) can be used. This function is applied to a tree *T* by given a pointer to the root of *T* as a
value of its argument *n*. It then computes the value of the expression represented by *T*

The following statement must be proved:

**S(T)**: The value returned by evaluate function when called on the root of *T* equals the value of the arithmetic
expression represented by *T*

For the basis, *T* consists of a single node. That is, the argument *n* is a (pointer to a) leaf. Since the
operator field has the value *‘i’* when the node represents and operand, the function succeeds

![Structural Induction Nodes](https://github.com/Scalified/tree/blob/master/assets/structural_induction_nodes.png)

If the node *n* is not a (pointer to a) leaf, the inductive hypothesis is that *S(T’)* is true for each tree *T’*
rooted at one of the children of *n*. *S(T)* then must be proved for the tree *T* rooted at *n*

Since operators are assumed to be binary, *n* has two subtrees. By the inductive hypothesis, the values of
*value_1* and *value_2* are the values of the left and right subtrees. In the figure, *value_1* holds the value of
*T1* and *value_2* holds the value of *T2*

Whatever operator appears at the root, *n* is applied to the two values: *value_1* and *value_2*. For example,
if the root holds, *+*, then the value returned is *value_1 + value_2*, as it should be for an expression that is
the sum of the expressions of trees *T1* and *T2*

Now, *S(T)* holds for all expression trees *T*, and, therefore, the function evaluate correctly evaluates trees
that represent expressions

## Usage

[**TreeNode**](https://github.com/Scalified/tree/blob/master/tree/src/main/java/com/scalified/tree/TreeNode.java) -
is the top interface, which represents the basic tree data structures. It describes the basic methods, which are
implemented by all the trees

### Creation

Suppose you need to create the following tree with **String** data using array-of-pointer representation:

![K-ary tree](https://github.com/Scalified/tree/blob/master/assets/k_ary_tree.png)

The following code snippet shows how to build such tree:

```java
// Creating the tree nodes
TreeNode<String> n1 = new ArrayMultiTreeNode<>("n1");
TreeNode<String> n2 = new ArrayMultiTreeNode<>("n2");
TreeNode<String> n3 = new ArrayMultiTreeNode<>("n3");
TreeNode<String> n4 = new ArrayMultiTreeNode<>("n4");
TreeNode<String> n5 = new ArrayMultiTreeNode<>("n5");
TreeNode<String> n6 = new ArrayMultiTreeNode<>("n6");
TreeNode<String> n7 = new ArrayMultiTreeNode<>("n7");

// Assigning tree nodes
n1.add(n2);
n1.add(n3);
n1.add(n4);
n2.add(n5);
n2.add(n6);
n4.add(n7);
```

### Storing And Retrieving Data

Data is stored in a tree node during creation:

```java
// Storing string data during creation
TreeNode<String> node = new ArrayMultiTreeNode<>("data");

// Null values can also be stored:
TreeNode<String> nullNode = new ArrayMultiTreeNode<>(null);
```

Data can be changed after node creation:

```java
// Setting the data
node.setData("data");

// Getting the data
String data = node.data();
```

### Identifying the Root

```java
// Checking whether the current node is root
boolean result = node.isRoot();

// Getting the reference to the root node
TreeNode<String> root = node.root();
```

> NOTE: Calling *root()* on the root node returns this root node itself

### Identifying the Parent

```java
// Getting the reference to the parent node
TreeNode<String> parent = node.parent();
```
> NOTE: If the current *node* is root, calling *node.parent()* returns *null*

### Subtrees

```java
// Retrieving subtrees as a new collection
Collection<? extends TreeNode<String>> subtrees = node.subtrees();

// Checking whether the specified subtree is present
TreeNode<String> subtreeToCheck = new ArrayMultiTreeNode<>("subtreeToCheck");
boolean resultHasSubtree = node.hasSubtree(subtreeToCheck);

// Removing the entire subtree with all of its descendants from node
TreeNode<String> subtreeToDrop = new ArrayMultiTreeNode<>("subtreeToDrop");
boolean resultDropSubtree = node.dropSubtree(subtreeToDrop);
```

### Checking For Presence

```java
// Checking whether the tree node contains the specified node
TreeNode<String> nodeToCheck = new ArrayMultiTreeNode<>("nodeToCheck");
boolean resultContains = node.contains(nodeToCheck);

// Checking whether the tree node contains all of the collection's nodes
Collection<TreeNode<String>> collectionToCheck;
// ... collection initialization skipped
boolean resultContainsAll = node.containsAll(collectionToCheck);
```

### Finding nodes

```java
// Finding the first occurence of the tree node within the tree with the specified data
TreeNode<String> nodeToFind = node.find("dataToFind");

// Finding the collection of all tree nodes within the tree with the specified data
Collection<TreeNode<String>> nodesToFind = node.findAll("dataToFind");
```

### Modification

```java
// Adding new subtree / tree node
TreeNode<String> nodeToAdd = new ArrayMultiTreeNode<>("nodeToAdd");
node.add(nodeToAdd);

// Removing the tree node from entire tree
TreeNode<String> nodeToRemove = new ArrayMultiTreeNode<>("nodeToRemove");
boolean resultRemove = node.remove(nodeToRemove);

// Removing all of the tree nodes specified in the collection from the entire tree
Collection<TreeNode<String>> collectionToRemove;
// ... collection initialization skipped
boolean resultRemoveAll = node.removeAll(collectionToRemove);

// Removing all of the subtrees with all of theirs descendants from the entire tree
node.clear();
```

### Traversal

[TraversalAction](https://github.com/Scalified/tree/blob/master/tree/src/main/java/com/scalified/tree/TraversalAction.java)
allows to define an action, which has a single method **perform(TreeNode<T>)**. This method is called during traversal
on each node visited

```java
// Creating traversal action
TraversalAction<TreeNode<String>> action = new TraversalAction<TreeNode<String>>() {
	@Override
	public void perform(TreeNode<String> node) {
		System.out.println(node.data()); // any other action goes here
	}

	@Override
	public boolean isCompleted() {
	    return false; // return true in order to stop traversing
	}
};

// Traversing pre order
node.traversePreOrder(action);

// Traversing post order
node.traversePostOrder(action);
```

### Iteration

```java
// Iterating over the tree elements using foreach
for (TreeNode<String> node : root) {
	System.out.println(node.data()); // any other action goes here
}

// Iterating over the tree elements using Iterator
Iterator<TreeNode<String>> iterator = root.iterator();
while (iterator.hasNext()) {
	TreeNode<String> node = iterator.next();
}
```

> NOTE: Iteration starts from the root node and goes in a pre ordered manner
>
Iterator support removing by calling **remove()** while iterating
>
Removing any tree node while iterating using foreach throws **ConcurrentModificationException**

### Converting To Collection

```java
// Retrieving all the tree nodes as a pre ordered collection of elements
Collection<? extends TreeNode<String>> preOrderedCollection = node.preOrdered();

// Retrieving all the tree nodes as a post ordered collection of elements
Collection<? extends TreeNode<String>> postOrderedCollection = node.postOrdered();
```

> NOTE: Any modification of the retrieved collection won't cause the correspondent modification in the tree

### Additional Useful Methods

```java
// Checking whether the current node is leaf
boolean nodeIsLeaf = node.isLeaf();

// Retrieving the collection of nodes, which connect the current node with its descendants
TreeNode<String> descendant = new ArrayMultiTreeNode<>("descendant");
Collection<? extends TreeNode<String>> path = node.path(descendant);

// Getting the common ancestor
TreeNode<String> anotherNode = new ArrayMultiTreeNode<>("anotherNode");
TreeNode<String> commonAncestor = node.commonAncestor(anotherNode);

// Checking whether the node is the sibling of the current node
TreeNode<String> sibling = new ArrayMultiTreeNode<>("sibling");
boolean nodeIsSibling = node.isSiblingOf(sibling);

// Checking whether the current node is ancestor of another node
TreeNode<String> anotherDescendantNode = new ArrayMultiTreeNode<>("anotherDescendantNode");
boolean nodeIsAncestor = node.isAncestorOf(anotherDescendantNode);

// Checking whether the current node is descendant of another node
TreeNode<String anotherAncestorNode = new ArrayMultiTreeNode<>("anotherAncestorNode");
boolean nodeIsDescendant = node.isDescendantOf(anotherAncestorNode);

// Getting the size of entire tree including the current tree node
int size = node.size();

// Getting the level of the current tree node within the whole tree
int level = node.level();

// Getting the height of the current tree node
int height = node.height();
```

### K-ary (multinode) Trees

[**MultiTreeNode**](https://github.com/Scalified/tree/blob/master/tree/src/main/java/com/scalified/tree/multinode/MultiTreeNode.java) -
interface, which adds additional methods for multi tree node (K-ary) tree data structures:

```java
// Getting the siblings of the current tree node
Collection<? extends MultiTreeNode<String>> siblings = node.siblings();

// Checking whether the current tree node has all of the subtrees specified in the collection
Collection<? extends MultiTreeNode<String>> collectionToCheck;
// ... collection initialization skipped
boolean resultHasSubtrees = node.hasSubtrees(collectionToCheck);

// Adding all of the subtrees from the collection to the current tree node
Collection<? extends MultiTreeNode<String>> collectionToAdd;
// ... collection initialization skipped
boolean resultAddSubtrees = node.addSubtrees(collectionToAdd);

// Removing all of the subtrees specified in the collection from the current tree node
Collection<? extends MultiTreeNode<String>> collectionToRemove;
// ... collection initialization skipped
boolean resultRemoveSubtrees = node.removeSubtrees(collectionToRemove);
```

K-ary (multi node) trees are represented by **MultiTreeNode** interface and have 2 implementations:

* [**ArrayMultiTreeNode**](https://github.com/Scalified/tree/blob/master/tree/src/main/java/com/scalified/tree/multinode/ArrayMultiTreeNode.java) -
implementation based on the array-of-pointers representation
* [**LinkedMultiTreeNode**](https://github.com/Scalified/tree/blob/master/tree/src/main/java/com/scalified/tree/multinode/LinkedMultiTreeNode.java) -
implementation based on the leftmost-child-right-sibling representation

**LinkedMultiTreeNode** is better optimized for trees with many nodes, whereas **ArrayMultiTreeNode** is better for large node trees

## License

```
  Copyright 2016 Scalified <http://www.scalified.com>

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

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

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

## Scalified Links

* [Scalified](http://www.scalified.com)
* [Scalified Official Facebook Page](https://www.facebook.com/scalified)
* Scalified Support

repository: ymind/tree

repo_name: ymind/tree


text:
# TO DO

## Yeah, do it...

* Other output formats:
PNG, JPG, PS etc.  As a collection of single page images.
Also include option to tar/zip them together?

## Under Consideration

* --pages -p M:N
Add an option that selects a subset of the output pages.
Page generation is slow; if the user wants only certain
pages then this would make it faster.
Consider tho the interaction with the --insert option;
the -p pages get chopped *before* inserting so the -i numbers
would be off.  Unless I get clever and associate the original
page numbers with the @pdf_files list (use a hashmap).  Hmmm....

* --generator -g GENUTIL
Default generator is `inkscape`.  It's good but slow.
Allow others, such as rsvg-convert?
Do this in place of a -I option that gives the full path to
the Inkscape binary?

* Windows install
Yuck... Winderz.  Need instructions to make this work on
Windows, perhaps a VM to test it too.  What about MacOS too?

## What I really want...

Is to build this multi-page support into Inkscape itself.
I'm able to build Inkscape 1.* from source already,
and I've played around with duplicating/changing the Layers
dialog box, but my new UI widgets don't appear.
I need help getting over the hump here...

license: MIT

branch_name: refs/heads/main

extension: md

gha_license_id: MIT

license_type: permissive


text:
# Compare

Compare is a web application that allows users, typically those who are indecisive, to compare data such as items and places.

Submitted by: Jonathan Chery

## Tech(s) Used

The following **technologies** were used to complete this website:

* Javascript
* Bootstrap
* MongoDB
* Express.js
* Angular.js
* Node.js

## Included Package(s)

* Mean currently uses gulp as a build tool and bower to manage frontend packages. ``` $ npm install -g gulp ``` and ``` bower $ npm install -g bower ```
* Added a list od dependencies and saved it within my directory ``` $ npm install express --save ```

## License

Copyright 2017 Jonathan Chery

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

branch_name: refs/heads/master


text:
# LESSAlgorithm

This is an accompanying website for a paper submission to the EWSN'18 (https://ewsn2018.networks.imdea.org) conference.

This project presents the LESS algorithm for promoting energy neutrality in energy harvesting Wireless Sensor Networks (WSNs) delivering services to multiple users. LESS is a lightweight distributed algorithm designed to achieve synergy between applications requirements and Energy-Neutral Operation (ENO) leading to energy-neutral operation of sensors. The approach provides an orchestration framework allowing users to specify application requirements, which are disseminated to sensors to indicate the frequency of sensing and data transmission required by applications. Sensors use the provided specification to determine the duty cycle needed to satisfy the requirements of applications, while still conforming to the constraints of ENO.

A prototype version of LESS is currently available along with a simulator, which allows to evaluate the algorithm for solar, wind and thermal energy sources.

## Basic Features

* **Orchestrator** component, which allows users to specify requirements pertaining to the application whilst being agnostic to the operation of the ENO algorithm itself. These requirements are normalized by the orchestrator and disseminated into the network.

* **Low Energy Sensor Scheduling (LESS)** algorithm that has been developed to promote synergy between the requirements of applications and the energy constraints of ENO WSNs whilst maintaining fairness when provisioning tasks.

The orchestration framework scheme.

## Requirements
* Python 2.7.x
* numpy (1.13.1)
* pandas (0.20.3)
* simplejson (3.11.1)

```bash
sudo apt-get install python-pip
sudo pip install numpy
sudo pip install pandas
sudo pip install simplejson
```

## Simulation

#### Start the simulator ####
```bash
python cmd_interpreter.py
```

Start the simulator.

#### Read application requirements ####

Application requirements are stored in the ```requirements.txt``` file.

```
# This dataset defines application requirements for use cases presented in the
# EWSN submission. The park is divided in two main areas, i.e., riverside and
# avenue. The WSN layout is provided in the park_wsn_layout.png file.

@App1=[9:00pm-4:30am->2, 4:30am-6:00am->5, 6:00am-9:00am->30, 9:00am-4:00pm->5, 4:00pm-9:00pm->30]
@App2=[9:00pm-6:00am->2, 6:00am-9:00am->5, 9:00am-11:00am->15, 11:00am-1:00pm->30, 1:00pm-7:00pm->15, 7:00pm-9:00pm->5]
@App3=[9:00pm-4:30am->2, 4:30am-6:00am->5, 6:00am-9:00am->30, 9:00am-11:00am->15, 11:00am-1:00pm->30, 1:00pm-4:00pm->15, 4:00pm-9:00pm->30]

# <time, location, frequency>
# App1 requirements (smart lighting system)
<9:00pm-4:30am, RIVERSIDE_N2, 2>
<9:00pm-4:30am, RIVERSIDE_N4, 2>
<9:00pm-4:30am, RIVERSIDE_N5, 2>
<9:00pm-4:30am, RIVERSIDE_N7, 2>
<9:00pm-4:30am, AVENUE_N11, 2>
<9:00pm-4:30am, AVENUE_N13, 2>
<9:00pm-4:30am, AVENUE_N16, 2>
<9:00pm-4:30am, AVENUE_N20, 2>
...
```

These requirements are defined for application scenarios described in the paper submission. The layout of the WSN in the urban park is as depicted below.

WSN layout of the urban park deployment.
        The blue area indicates the RIVERSIDE location. The purple area indicates the AVENUE location.
        Pins indicate sensor assignment to applications: blue(App1), orange(App2), green(App3)

The orchestration profile for each application and sensor node is produced using the list command.

```bash
>>> list
```

List the orchestration profile of applications and sensors.

#### Generate energy harvesting prediction ####

To generate the prediction for energy harvesting by sensors using solar, wind and thermal use the ```engen``` command. Environmental data used for generating energy harvesting prediction can be found in ```datasets/env_data/0ATotal_solarcalc_raw.csv```.

```bash
>>> engen
```

Engen command output.

Graph presenting the energy generated using various energy harversting methods:
        solar(blue), wind(green), thermal(red).

#### Simulating algorithms ####

To run a simulation using provided application requirements and the defined energy harvesting model use the ```run``` command.
The command takes two arguments: 1. application identifier (e.g., App1), 2. energy harvesting sources (s -> solar, w -> wind, t -> thermal). Solar is the default harvesting source.

```bash
>>> run App1 s
```

Run command output.

Graph presenting the operation of different algorithms for App1 over time.

Simulation results are stored in the JSON format and can be found in the ```datasets/results``` folder.

Results presented in the JSON format.

The results presented in the EWSN paper submission can be found in the ```ewsn_results``` folder.

## Algorithm design

The operations provided by the LESS algorithm are described below

#### findDuty ####
The ```findDuty``` operation calculates a the duty cycle of a sensor for each time slot at the beginning of each time window. The code for findDuty can be found in less_simulator.py file where the initial seeding is provided in lines 500 - 509.

From the initial seeding the duty cycle required for each timeslot is calculated from the predicted energy for the new time window Nw. Then, during the operation of ```performDuty```, the energy generation predicted is used to define the number of sensing, computation and transmission tasks possible for the upcoming timeslot. After these tasks have been completed the real energy generated is then calculated in ```checkHg```. The difference between the predicted energy generation and real energy generation then determines if there is residual energy in the system and the upcoming scheduled tasks in future timeslots in the current time window are dynamically updated to account for differences between prediction and reality to ensure sustainability.

#### performDuty ####
The ```performDuty``` function, in the lessWSN function at 529 to 564 in less_simulator.py works out energy from performing the tasks scheduled in the current timeslot as per the energy model described in the associated EWSN paper. This information is provided to the dynamic scheduling element of the algorithm described in ```findDuty```.

#### checkHg ####
In the lessWSN function, at lines 579-615 of less_simulator.py, the ```checkHg``` function is performed.

As this is a simulator, careful consideration has been undertaken to represent the real world dynamics and prediction of solar. The EWMA prediction method for solar is used over a time window, Nw, but at the end of a time slot the real energy generated is known in a WSN. This knowledge is simply gained by measuring energy generated (once or at set intervals throughout the timeslot via a high side current sensor, depending on timeslot length).

For the simulation, ```checkHg``` here uses the real data for said timeslot (known from NREL database) and compares this to the predicted data from the EWMA method.  The algorithm goes on to use this to understand if the system over or under provisioned the network tasks in a timeslot when compared to the predicted amount. This is how the residual energy metric is calculated to reassign energy dynamically for future timeslots in the same time window .

The actual energy generated is calculated in the functions ```panelEnergyGen```, for solar, ```NRELtoWindPower```, for wind, and ```NRELtoTEGPower``` for theroelectric generators.

#### surplusTask ####
The ```surplusTask``` function in the lessWSN function of less_simulator.py at lines 542-548 flags state where surplus energy is generated.

If orchestrator needs have been met for the time window and the energy storage element is full, the remaining energy can be used to perform system and maintenance tasks. For the purpose of this paper we keep the notion of surplus tasks abstract, however this will inform future work. However, it is important to note that the dynamic d_t^max of this paper will promote a greater energy surplus in comparion to the ENO-Kansal method which in turn will allow for a greater number of surplus tasks to be performed, highlighting a benefit of our work.

#### ewmaUpdate ####
In the ```ewmaUpdate``` function in the lessWSN function of the less_simulator.py script at the end of each time slot in the master loop the EWMA is updated for that timeslot, weighted against historical values, calculated in lines 529-564 and updated at line 566.

Uses recorded data from current sensor, or historical real trace data in the case of the simulator, to update energy generation array for future time window as per prescribed EWMA function. This then informs the potential for energy generation in the next time window.

repository: lessalgorithm/LESSAlgorithm

repo_name: lessalgorithm/LESSAlgorithm


text:
# vhs-door-nfc
Space access using NFC + PIN code

## Building Firmware
You will need an API key that has the 'PIN Authentication Service' and 'RFID Authentication Service' privileges.

1. You will need Visual Studio Code with the PlatformIO extension installed as the firmware projects are set up with Visual Studio Code workspaces using PlatformIO for the build system.
1. Obtain the API key from Nomos and grant it the required permissions.
1. Create the file software/esp32-firmware/src/nomos_api_key.h
1. Edit the file to contain
    ```C
    #ifndef __NOMOS_API_KEY_H__
    #define __NOMOS_API_KEY_H__

    #ifndef NOMOS_API_KEY
    #define NOMOS_API_KEY "put_your_api_key_here"
    #endif //NOMOS_API_KEY

    #endif //__NOMOS_API_KEY_H__
    ```
1. In VSCode you should be able to use the regular PlatformIO build and upload commands for each workspace.

repository: vhs/vhs-door-nfc

repo_name: vhs/vhs-door-nfc


text:
# Welcome to Chatty! :speech_balloon:

This is a simple chat application built using React, WebSockets, and WebPack. Multiple users can connect and chat in real time! All users can see the list of messages in the current conversation and see a notification if a user changes their username.

To get started:
1. clone the repo
2. run `npm install` in the root directory
3. open a second terminal window and cd into the chatty-server directory
4. run `npm install` again
5. use the command `npm start` in both terminal windows to get chatting!

![2 users connected and chatting](https://github.com/maryshrives/chattyapp/blob/master/docs/chattyScreenShot.png)

## Dependencies

-    "react": "15.4.2",
-    "react-dom": "15.4.2"
-    "express": "4.16.2"
-    "uuid": "^3.1.0"
-    "ws": "4.0.0"

## Dev Dependencies

-    "babel-core": "6.23.1"
-    "babel-loader": "6.3.1"
-    "babel-preset-es2015": "6.22.0"
-    "babel-preset-react": "6.23.0"
-    "babel-preset-stage-0": "6.22.0"
-    "css-loader": "0.26.1"
-    "node-sass": "4.5.0"
-    "sass-loader": "6.0.0"
-    "sockjs-client": "^1.1.2"
-    "style-loader": "0.13.1"
-    "webpack": "2.2.1"
-    "webpack-dev-server": "2.3.0"

repository: maryshrives/chattyapp

repo_name: maryshrives/chattyapp


text:
# BED to VCF match

> Correlate calls from bed files to vcf to determine percent match to archaic
genotypes.

## Installation
All dependencies are specified in the environment.yaml file.  A conda
environment can be created with
```
conda create --name bed2vcf --file environment.yaml
```
Once created, activate the environment with: `conda activate bed2vcf`

## Tests
All unit tests can be run within the conda environment by calling `pytest`

## Usage
There are two main functions in the top level directory

### thin\_vcf.py
This function performs filtering of vcfs based on individual names or bed files
to retain.  The script thin\_vcf.slurm shows a submission along with the
vcftools implementation.  Leveraging zcat and gzip to perform compression and
using the sorted nature of both files, this runs more quickly than the vcftools
version.

### bed2vcf.py
This performs the main analysis and is run with run.slurm.  Bed files are
provided with the `--bed_files` flag and outputs are written to the
`--output_dir` with the same base filename as the inputs, appended with
".matched".  Vcfs should be provided for each chromosome and labeled with a
wildcard for python formatting.  E.g. if the files are named chrom\_1\_filter.vcf
the command line expects the input chrom\_\{chr\}\_filter.vcf and will expand
to each chromosome in \[1, 22\]

### Output Format
Currently only bed output is supported.  Each row corresponds to a row in the
input bed file.  The columns are:
1. Chromosome
2. Start position
3. End position
4. Number of entries in the modern VCF within this region.
5. Number of derived variants within the region for a haplotype
6. Number of derived variants in the modern VCF joined with archaic.
Intersection of sites, not necessarily matching variants.
7. Number of derived variants in the archaic VCF within the region (number of alleles/2)
8. Number of derived variants in archaic which match a derived variant
in the modern vcf.

## License

MIT © [Troy Comi](https://github.com/troycomi)


text:
# Overview
This is the Python script of producing word2vec on tags of [stackoverflow](https://stackoverflow.com/).
The tags was gathered from posts of stackoverflow related to Python.
## Prerequisite
Before run script you must install [gensim](https://radimrehurek.com/gensim/) library.
You can install gensim by running below command in terminal:

```
$ pip install --upgrade gensim
```
## Usage
You can simply run script by typing below command:

```
$ python word2vec.py
```
Taking into account that word2vec.py has three parameters:
- positive
- negative
- topn

Make sure you set parameters according to what you want.


text:
An Electric Imp serial display driver
=====================================

Here are two examples of a simple Screen class for driving these handy serial LCD screens: https://www.sparkfun.com/products/9067.

* driver.nut is a simple, single screen hello world example.  Simply connect the RX pin of the screen to PIN1 of the Imp.

* example.nut is a more complex example that prints JSON from the internet (via a GET HTTP Request block) on two screens.


text:
examples-nextjs

This example uses a next.js custom server

### How to run this example

1. Clone the openid-client-server-repo
2. Run `yarn` in the root of the cloned repo
3. cd -> examples/nextjs
4. Create a `.env` file with the openid client info (see the .env.example file in the repo root for more info)
4. Run `yarn`
5. Run `yarn dev`
6. Open http://localhost:8080 in your browser

repository: mtintes/openid-client-server

repo_name: mtintes/openid-client-server


text:
---
weight: 30
title: "Default Values"
---
# Fields And Default Values

The client lib will fill the "proto" default values for the fields when they are not transmited. This means i.e. numeric types will get a 0, strings a empty string.
The default value that you can specify in the specs has nothing to do with proto directly. Proto 3 does not know anything about default values.

This comes very handy when you create an instance of a type on the client side and pass the data object to a form.

## Static Default Values
The standard spec let you define a default value. This values are entered as **string** and must be parsed by them who use them.
The client framework, does the parsing transparently for you.

```yaml
fields:
  description:
    type: string
    description: Describe the fruit
    __proto:
      number: 3
      oneof: ""
    __ui: null
    meta:
      default: "This is the default" #<-- default values goes here!
      hint: ""
      label: fruit.Fruit.description.label
      options:
        flags: []
        list: []
      readonly: false
      repeated: false
      typespecific: null
    constraints:
      required:
        is: "true"
        message: description is required
```

### Json Object Example
It is recomended to enter the default values as json string. The javascript clients will not parse them,
when you use yaml notation.

```yaml
fields:
  fruit:
    type: fruit.Fruit
    meta: #the following default value is a string too, it just look like a json object.
      default: |
        {"key":"value"}

```

## Runtime Default Values
This topic belongs more to the client libs and is here only for completenes.

You can set default value for a type on the client side during runtime with a server response via the *meta* field.

```json
{
  "data": {
    "id": "1",
    "scalar_string": "this is a scalar string"
  },
  "links": [],
  "meta": {
    "fields": {
      "data.scalar_string": {
        "meta": {
          "label": "scalar_string string label setted via response meta",
          "readonly": false,
          "default": "runtime default value"
        }
      }
    }
  }
}

```

{{< hint info >}}
There are more patterns to feed the clien with default values. It is also possible to build a custom method which creates a
default object on the server side and feed this to the data object on the client side to create a new object. Hint: by doing this do not forget to set the HATEOAS link for the rel *create*.
{{< /hint >}}

repository: veith/eclipsefuro

repo_name: veith/eclipsefuro


text:
# v1.26.0 (2023-08-31)

* **Feature**: Updated "type" description for CreateChannel, UpdateChannel, Channel, and ChannelSummary.

# v1.25.5 (2023-08-21)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.25.4 (2023-08-18)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.25.3 (2023-08-17)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.25.2 (2023-08-07)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.25.1 (2023-08-01)

* No change notes available for this release.

# v1.25.0 (2023-07-31)

* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide.
* **Dependency Update**: Updated to the latest SDK module versions

# v1.24.1 (2023-07-28)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.24.0 (2023-07-17)

* **Feature**: This release provides the flexibility to configure what renditions or thumbnail qualities to record when creating recording configuration.

# v1.23.1 (2023-07-13)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.23.0 (2023-06-27)

* **Feature**: IVS customers can now revoke the viewer session associated with an auth token, to prevent and stop playback using that token.

# v1.22.2 (2023-06-15)

* No change notes available for this release.

# v1.22.1 (2023-06-13)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.22.0 (2023-06-01)

* **Feature**: API Update for IVS Advanced Channel type

# v1.21.4 (2023-05-04)

* No change notes available for this release.

# v1.21.3 (2023-04-24)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.21.2 (2023-04-10)

* No change notes available for this release.

# v1.21.1 (2023-04-07)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.21.0 (2023-03-30)

* **Feature**: Amazon Interactive Video Service (IVS) now offers customers the ability to configure IVS channels to allow insecure RTMP ingest.

# v1.20.8 (2023-03-21)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.20.7 (2023-03-10)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.20.6 (2023-03-06)

* **Documentation**: Updated text description in DeleteChannel, Stream, and StreamSummary.

# v1.20.5 (2023-02-22)

* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes.

# v1.20.4 (2023-02-20)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.20.3 (2023-02-16)

* **Documentation**: Doc-only update. Updated text description in DeleteChannel, Stream, and StreamSummary.

# v1.20.2 (2023-02-15)

* **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910.
* **Bug Fix**: Correct error type parsing for restJson services.

# v1.20.1 (2023-02-03)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.20.0 (2023-01-20)

* **Feature**: API and Doc update. Update to arns field in BatchGetStreamKey. Also updates to operations and structures.

# v1.19.0 (2023-01-05)

* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401).

# v1.18.7 (2022-12-15)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.18.6 (2022-12-02)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.18.5 (2022-10-24)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.18.4 (2022-10-21)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.18.3 (2022-09-20)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.18.2 (2022-09-14)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.18.1 (2022-09-02)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.18.0 (2022-08-31)

* **Feature**: IVS Merge Fragmented Streams. This release adds support for recordingReconnectWindow field in IVS recordingConfigurations. For more information see https://docs.aws.amazon.com/ivs/latest/APIReference/Welcome.html
* **Dependency Update**: Updated to the latest SDK module versions

# v1.17.2 (2022-08-29)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.17.1 (2022-08-24)

* **Documentation**: Documentation Change for IVS API Reference - Doc-only update to type field description for CreateChannel and UpdateChannel actions and for Channel data type. Also added Amazon Resource Names (ARNs) paragraph to Welcome section.

# v1.17.0 (2022-08-14)

* **Feature**: Updates various list api MaxResults ranges

# v1.16.13 (2022-08-11)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.12 (2022-08-09)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.11 (2022-08-08)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.10 (2022-08-01)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.9 (2022-07-05)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.8 (2022-06-29)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.7 (2022-06-07)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.6 (2022-05-17)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.5 (2022-04-25)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.4 (2022-03-30)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.3 (2022-03-24)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.2 (2022-03-23)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.16.1 (2022-03-09)

* No change notes available for this release.

# v1.16.0 (2022-03-08)

* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.15.0 (2022-02-24)

* **Feature**: API client updated
* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options.
* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.14.0 (2022-01-28)

* **Feature**: Updated to latest API model.

# v1.13.0 (2022-01-14)

* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.12.0 (2022-01-07)

* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.11.0 (2021-12-21)

* **Feature**: API Paginators now support specifying the initial starting token, and support stopping on empty string tokens.

# v1.10.1 (2021-12-02)

* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514))
* **Dependency Update**: Updated to the latest SDK module versions

# v1.10.0 (2021-11-19)

* **Feature**: API client updated
* **Dependency Update**: Updated to the latest SDK module versions

# v1.9.0 (2021-11-06)

* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically.
* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.8.0 (2021-10-21)

* **Feature**: API client updated
* **Feature**: Updated  to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.7.2 (2021-10-11)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.7.1 (2021-09-17)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.7.0 (2021-09-02)

* **Feature**: API client updated

# v1.6.0 (2021-08-27)

* **Feature**: Updated API model to latest revision.
* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.5.3 (2021-08-19)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.5.2 (2021-08-04)

* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version.
* **Dependency Update**: Updated to the latest SDK module versions

# v1.5.1 (2021-07-15)

* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.5.0 (2021-06-25)

* **Feature**: Updated `github.com/aws/smithy-go` to latest version
* **Dependency Update**: Updated to the latest SDK module versions

# v1.4.1 (2021-05-20)

* **Dependency Update**: Updated to the latest SDK module versions

# v1.4.0 (2021-05-14)

* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting.
* **Dependency Update**: Updated to the latest SDK module versions

gha_language: Go


text:
# Crypto Portfolio

IN DEVELOPMENT

## Demo
https://coins.jasonemery.co.uk

## Requirements

- Node
- MongoDB
- Gulp

## Running project

```
$ cd src
$ npm i
$ gulp build
$ node ./server
$ navigate to http://<IP_ADDRESS>:8000
```

To run in development mode:
```
$ gulp develop
```

## Decription
Built using React, Node & MongoDB

Data from https://www.cryptocompare.com/api/

gha_language: JavaScript


text:
# Automated Disclosure

Automating the tedious parts of the vulnerability disclosure process.

The goal of this project is to help automate away some of the tedious parts of the vulnerability disclosure process.
In particular, enforcing a consistent disclosure policy in a way that is automated and straightforward.

## How This Repo Works

After lots of time spent dealing with disclosures on HackerOne, BugCrowd, Email, GitHub Security Advisories, Jira, ect... I've finally gotten tired of having to manually keep track of the disclosure deadlines for each respective outstanding report. In my experience, the user experience around GitHub Security Advisories is the most researcher friendly and, with a few bits of automation, the perfect platform for performing  vulnerability disclosure.

This project leverages a few bits of infrastructure to operate.
 - A GitHub account dedicated as a disclosure bot. (eg. [@JLLeitschuh-disclosure-bot](https://github.com/JLLeitschuh-disclosure-bot))
   - This account must have 2FA setup using OTP. This bot will be interfacing with security advisories. 2FA is requited on this account.
 - A GitHub Repository for disclosures (eg. https://github.com/JLLeitschuh/security-research)

### Infrastructure

The goal of this repository is to help a security researcher that leverages GitHub Security Advisories provide regular notifications about an impending disclosure to the organization with the vulnerable component.

repository: JLLeitschuh/automated-disclosure

repo_name: JLLeitschuh/automated-disclosure


text:
Possibly will include:
* Explanation
* De-comment
* Converting from more human-readable code
* Converting to more human-readable code.

View at https://eiim.github.io/DS_ARCodeTools/


text:
---
hrs_structure:
  division: '2'
  volume: '9'
  title: '24'
  chapter: '434'
  section: ''
type: chapter
tags:
  - Business
menu:
  hrs:
    identifier: HRS0434
    parent: title24
    name: Chapter 434 Insurance by Fraternal Benefit Societies--Repealed
weight: 31000
title: Insurance by Fraternal Benefit Societies--Repealed
full_title: Chapter 434 Insurance by Fraternal Benefit Societies--Repealed
---
**CHAPTER 434**

**INSURANCE BY FRATERNAL BENEFIT SOCIETIES**

**REPEALED.** L 1987, c 347, §1.

Cross References

For present provisions, see chapter 432, article 2.

repository: SamMade/BlueAndKrabby

repo_name: SamMade/BlueAndKrabby


text:
# Connecting Rods Inspector – Computer Vision system for the visual inspection of motorcycle connecting rods

Computer Vision system that is able to analyse the dimensions of two different types of connecting rods to allow a vision-guided robot to pick and sort rods based on their type and dimensions.

## Image characteristics
Rods appearing in the images are characterised by the different number of holes: type "A" rods have one hole, whilst type "B" rods have two holes.

### Part 1
We consider that the following simplistic conditions hold for each image:

1. Images contain only connecting rods, which can be of both types and feature significantly diverse dimensions.
2. Connecting rods have been carefully placed within the inspection area so to appear well separated in images (i.e. they do not have any contact point).
3. Images have been taken by the backlighting technique so to render rods easily distinguishable (i.e. much darker) from background. However, for flexibility reasons the system should not require any change to work properly with lighting sources of different power.

### Part 2
We no longer consider the simplistic conditions holding for the previous part:

1. Images may contain other objects (i.e. screws and washers) that need not to be analysed by the system.
2. Rods can have contact points but do not overlap one to another.
3. The inspection area may be dirty due to the presence of scattered iron powder.

## Functional specifications
### Part 1
For each connecting rod appearing in each image, the vision system must provide the following information:

1. Type of rod (A or B).
2. Position and orientation (modulo π).
3. Length (L), Width (W), Width at the barycenter (WB).
4. For each hole, position of the centre and diameter size.

### Part 2
For each image, the following requirements must be met:

1. Distracting objects must be ignored.
2. Touching rods must be recognised separately.
3. Iron powder presence must be managed as to not interfere with the analysis.

## Performances
Performances are calculated as the average observed FPS of 10 000 consecutive software executions on a Intel Core i5 Dual-Core 2,7 GHz processor.

* 33 FPS

## Full demo

## Requirements
The following Python packages must be installed in order to run the software:

* numpy
* opencv-python
* scipy

## Usage
Simply run the "main.py" script from terminal, after making sure it is located in the same directory of the "images" folder:

```bash
python main.py
```

or:

```bash
python3 main.py
```

repository: bobcorn/connecting-rods-inspector

repo_name: bobcorn/connecting-rods-inspector


text:
# SFY2 ready to code

## Setup

### Clone du CMS

```
git clone https://github.com/thomaroger/sfy2.git
```

### setup

```
chmod 755 setup.sh
./setup.sh
```

## Run tests

```
phpunit -c app/
```

## Vhost

```
<Virtualhost *:80>
  ServerName devwww.sfy2.fr
  DocumentRoot "/var/local/webroot/sfy2/web"
  DirectoryIndex app_dev.php
  <Directory "/var/local/webroot/sfy2/web">
    AllowOverride All
    Allow from All
  </Directory>
</VirtualHost>
```


text:
# ofriends

[![Join the chat at https://gitter.im/TheFlies/ofriends](https://badges.gitter.im/TheFlies/ofriends.svg)](https://gitter.im/TheFlies/ofriends?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Tool to track guests visit to my hotels over the time

## Prerequisites

Make sure you have the development environment matches with these notes below so we can mitigate any problems of version mismatch.

- Backend:
  - Go SDK: 1.10 (latest 1.10.8).
    Make sure to set `$GOROOT` and `$GOPATH` correctly.
    You can check those environment variable by typing: `go env`.
  - Install [govendor](https://github.com/kardianos/govendor) for dependency management.
  - MongoDB: 4.1 (latest 4.1.8).

- Frontend:
  - NodeJS: 11.10 (latest 11.10.0).
  - Use `yarn` instead of `npm` is possible.
  - Framework: [VueJS 2.x](https://vuejs.org) (latest 2.6.6).
  - UI components framework: [Element-UI](https://element.eleme.io) (latest 2.5.4).

- Commons:
  - OS: Should use Linux (latest Ubuntu or your choice of distro) if possible.
    Windows does not play well with Docker and some other techs we may use.
    If you still prefer to use Windows, so you may have to cope with problems by yourself later
    since we're assuming everything will be developed and run on Linux.
  - Install [Docker CE](https://docs.docker.com/install/) (latest 18.x) and [docker-compose](https://docs.docker.com/compose/install/).
  - Install [git](https://git-scm.com/) for manage source code.
  - IDE of your choice, recommended `Goland` or `VS Code`.

## Development

#### 1. Clone code to local

```shell
$ go get -u -v github.com/TheFlies/ofriends
or
$ cd $GOPATH/src
$ git clone https://github.com/TheFlies/ofriends.git
```
After this step, source code must be available at `$GOPATH/src/github.com/TheFlies/ofriends`.

#### 2. Start development environment manually

- Start MongoDB service at localhost:27017. The easiest way is to run the Docker as below:

  ```shell
  $ docker run -p 27017:27017 -v /opt/data/mongo_home:/data/db --name mongo -d mongo:4.1.8
  ```

- Start backend API service (Go):

  ```shell
  $ go run main.go
  # Backend service will start on port :8080.
  ```

- Open another terminal and start frontend service (NodeJS):

  ```shell
  $ cd web
  $ yarn install   # Do this only once
  $ yarn serve
  # Frontend service will start at port :8081 and connect to backend service at :8080.
  # Open your browser then head to http://localhost:8081.
  ```

#### 3. Start development environment with Docker

Instead of manually start services like step 2. You can use Docker to start all services at once.
Copy docker-compose.sample into docker-compose.yml and add neccessary information (LDAP information).

```shell
$ copy deployment/dev/docker-compose.sample deployment/dev/docker-compose.yml # Do this only once
$ vim deployment/dev/docker-compose.yml # Do this only once, add your LDAP configuraiton.
$ cd web && yarn install && cd ..   # Do this only once to install frontend modules first
$ make compose
```

After started, services will be available at `localhost` with ports as below:
```
MongoDB: 27017
Backend: 8080 (hot-reload dashboard: 8082)
Frontend: 8081
```

## Notes

- Make sure to run `go fmt`, `go vet`, `go test`, and `go build / go install` before pushing your code to Github.
  Or you can just run `make` before pushing.
- Never commit directly to `master` or `develop` branches (you don't have permission to do so, anyway). Instead, checkout from `develop` branch to a separated branch then work on that.
  Whenever you finish your work, you can create a Pull Request (PR) / Merge Request (MR) to ask for code review and merging your branch back to `develop`.
  `master` branch will be reserved when administrator decide to release a stable version of application.
- All documentations must be written in [Markdown](https://guides.github.com/features/mastering-markdown/) format, recommended to use [Typora](https://typora.io/) as the Markdown editor.

## Tech requirements:

- Authentication:
  - LDAP (AD) (backend authentication)
  - JWT (frontend authentication)
- Database
  - MongoDB
- Frontend
  - Full frontend framework [Vue](https://vuejs.org)
  - Component toolkit: [Element-UI](https://element.eleme.io)

## TODO
Need update

repository: TheFlies/ofriends

branch_name: refs/heads/develop

gha_language: Vue

repo_name: TheFlies/ofriends


text:
# Service Provision

[GitHub](https://github.com/) is used for source code management while [Amazon Web Service](https://aws.amazon.com/) is the hosting provider.
Further information regarding the development- and service provider-environments can be found following these links:

- [https://docs.devland.is/technical-overview/devops](https://docs.devland.is/technical-overview/devops)
- [https://docs.devland.is/apps/services/auth-api](https://docs.devland.is/apps/services/auth-api)
- [https://docs.devland.is/apps/services/auth-admin-api](https://docs.devland.is/apps/services/auth-admin-api)
- [https://github.com/island-is/identity-server.web](https://github.com/island-is/identity-server.web)

## IdentityServer

[IdentityServer](https://identityserver4.readthedocs.io/en/latest/) is an open source-solution in [.NetCore](https://en.wikipedia.org/wiki/.NET_Core). The system is an [OpenID Connect provider](https://openid.net/connect/), i.e. it implements the OpenID Connect and OAuth 2.0 protocols.

## Terminology

- ### User

  A human that is using a registered client to access resources.

- ### Client

  A software that requests tokens from [IdentityServer](https://identityserver4.readthedocs.io/en/latest/) - either for authenticating a user or for accessing a resource. A client must be first registered with [IdentityServer](https://identityserver4.readthedocs.io/en/latest/) before it can request tokens. Clients can for example be web applications, native mobile or desktop applications.

- ### Resources

  Resources are something you want to protect with [IdentityServer](https://identityserver4.readthedocs.io/en/latest/) - either identity data of your users, or APIs:

  - Identity data to identify users, for example names or e-mail addresses.
  - API is an interface which the clients communicate with.

- ### Identity token

  An identity token is created during the authentication procedure of [IdentityServer](https://identityserver4.readthedocs.io/en/latest/). It contains at a bare minimum an identifier for the user (called the _sub_ aka _subject claim_) and information about how and when the user authenticated.

- ### Access token

  An access token allows access to an API resource. Clients request access tokens and forward them to the API. Access tokens contain information about the client and the user which the API uses to authorize access to the resources.

## Authentication flow

1.  The service provider writes a code to connect with [Identity server](https://identityserver.io/)\‘s authentication service. The user’s identity is defined as a sub (_subject claim_) in the code.
2.  When the users’ clients request authentication then [IdentityServer](https://identityserver4.readthedocs.io/en/latest/) receives the _sub_. Accordingly, [IdentityServer](https://identityserver4.readthedocs.io/en/latest/) includes the _sub_ in the identity token which it creates to connect the clients with the resources. During the same procedure [IdentityServer](https://identityserver4.readthedocs.io/en/latest/) also creates the access token.
3.  [IdentityServer](https://identityserver4.readthedocs.io/en/latest/) sends the identity token and the access token to the client.
4.  The client forwards the access token to the API for validation.
5.  When the API has validated the access token then the client gets access to the user’s resources.

![authentication-service-provision-1](assets/authentication-service-provision-1.png)

## Software development process

1. The service-provider’s code is source-controlled in [GitHub](https://github.com/).
2. When there are code changes then the developer commits the new code and pushes to GitHub.
3. The developer creates a ‘pull request’ for his code changes which another developer must accept in order for the code to be merged with the main development branch. This triggers a GitHub-action which builds the code and deploys to the Development-environment.
4. When code is to be released, a release-branch is created by a third party from the main-branch. This triggers a GitHub-action which deploys it to the Staging-environment.
5. When the deployment on Staging has been tested and approved then the code is deployed to the Production-environment by a third party.

![authentication-service-provision-2](assets/authentication-service-provision-2.png)


text:
# mobile-memo
The MemoSaver app manages login credentials such as usernames, passwords, card number, email address, URL and other credentials that the client uses to log on to websites or other computers on a network. It saves To-do as well. The app is built with Xamarin and tested on Android.

You can set a start password for security.

The app has been published on Google Play:

The layout of TabbedPage is changed through TabbedPageRenderer. Here is the Memo Page.
![Screenshot](https://uuware.github.io/mobile-memo/memopage.png)

And other pages

![Screenshot](https://uuware.github.io/mobile-memo/todopage.png)
![Screenshot](https://uuware.github.io/mobile-memo/genpasspage.png)
![Screenshot](https://uuware.github.io/mobile-memo/setpage.png)

It is also a sample for use of SplashScreen:

![Screenshot](https://uuware.github.io/mobile-memo/splash.png)

repository: bubdm/mobile-memo

repo_name: bubdm/mobile-memo


text:
##Origin

Originally created in javascript, converting everything to work in Dart was actually a pleasant suprise. A large amount of javascript code actually didn't need to be touched, and while the DartEditor is not perfect, I had very few issues in my experience with this project. The biggest one was when trying to create multidimentional arrays. Dart doesn't support 2d arrays inherently, but by using preallocated Lists inside a List, it was possible to set up the matrix needed to create the nodes.

## Here's the bread and butter of Polygonz:
```
//create node matrix
    var i, j, x = 0, y = 0, nodeMatrix = new List();
    for (i = 0; i < shapeCountX+1; i++) {
        var nodeMatrixInner = new List(shapeCountY);
        for (j = 0; j < shapeCountY; j++) {
            if(i<1 || i>=shapeCountX || j<1 || j>=shapeCountY-1){
                nodeMatrixInner[j] = [x*shapeWidth, y*shapeHeight];
            }else{
                var rnd = new Random();
                nodeMatrixInner[j] = [(x+distortion*(.5-rnd.nextDouble()))*shapeWidth, (y+distortion*(.5-rnd.nextDouble()))*shapeHeight];
            }
            y=y+1;
        }
        nodeMatrix.add(nodeMatrixInner);
        x=x+1;
        y=0;
    }
```

Comparing to the javascript version:
```
//create node matrix
    var i, j, x = 0, y = 0, nodeMatrix = new Array(shapeCountX);
    for (i = 0; i < shapeCountX+1; i++) {
        nodeMatrix[i] = new Array(shapeCountY);
        for (j = 0; j < shapeCountY; j++) {
            if(i<1 || i>=shapeCountX || j<1 || j>=shapeCountY-1){
                nodeMatrix[i][j] = [x*shapeWidth, y*shapeHeight];
            }else{
                nodeMatrix[i][j] = [(x+distortion*(.5-Math.random()))*shapeWidth, (y+distortion*(.5-Math.random()))*shapeHeight];
            }
            y=y+1;
        }
        x=x+1;
        y=0;
    }
```

The same but different.

repository: ZachNagengast/devart-template

repo_name: ZachNagengast/devart-template


text:
# XYscope

XYScope is a library for Processing to render graphics on a vector display (oscilloscope, laser) by converting them to audio.

This includes most primitive shapes (point, line, rect, ellipse, vertex, ...) by converting those points to waveforms (oscillators with custom wavetables) and generating audio in real time using the Minim library. Vector graphics shine on a vector display and now you can view your generative works like never before! Only tested on MacOS 10.9.5+, but should work on Windows.

## Getting Started

Install as suggested below or

*PENDING* add within Processing from Sketch -> Import Library... -> Add Library...

More details + reference at [teddavis.org/xyscope](http://www.teddavis.org/xyscope)

### Dependencies

This library relies on and is greatly thankful for [Minim](https://github.com/ddf/Minim)

xtra_ examples requires [Geomerative](https://github.com/rikrd/geomerative), [OpenCV for Processing](https://github.com/atduskgreg/opencv-processing), [openkinect](https://github.com/shiffman/OpenKinect-for-Processing), [video](https://github.com/processing/processing-video)

### Installing

Unzip and put the extracted XYscope folder into the libraries folder of your Processing sketches. Reference and examples are included in the XYscope folder.

## Authors

* [Ted Davis](http://teddavis.org)

## License

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

## Acknowledgments

* Thanks to [Just Van Rossum](https://www.instagram.com/justvanrossum/) for the enlightening conversation on my X-Y attempts.
* Thanks to [Stefanie Bräuer](https://mewi.unibas.ch/seminar/personen/profil/portrait/person/stefaniebraeuer/) for feeding the oscilloscope obsession

repository: sebasstrogg/xyscope

repo_name: sebasstrogg/xyscope


text:
# Describe the difference between UCP workers and managers

## Official Docker Documentation
[Under the hood](https://docs.docker.com/datacenter/ucp/2.2/guides/architecture/#under-the-hood)

Components on manager :

- **ucp-agent** : Monitors the node and ensures the right UCP services are running (also on worker only)
- **ucp-dsinfo** : Docker system information collection script to assist with troubleshooting (also on worker only)
- **ucp-reconcile** : When ucp-agent detects that the node is not running the right UCP components, it starts the ucp-reconcile container to converge the node to its desired state. It is expected for the ucp-reconcile container to remain in an exited state when the node is healthy. (also on worker only)
- **ucp-auth-api** : The centralized service for identity and authentication used by UCP and DTR
- **ucp-auth-store** : Stores authentication configurations and data for users, organizations, and teams
- **ucp-auth-worker** : Performs scheduled LDAP synchronizations and cleans authentication and authorization data
- **ucp-client-root-ca** : A certificate authority to sign client bundles
- **ucp-cluster-root-ca** : A certificate authority used for TLS communication between UCP components
- **ucp-controller** : The UCP web server
- **ucp-dsinfo** : Docker system information collection script to assist with troubleshooting
- **ucp-kv** : Used to store the UCP configurations. Don’t use it in your applications, since it’s for internal use only
- **ucp-metrics** : Used to collect and process metrics for a node, like the disk space available
- **ucp-proxy** : A TLS proxy. It allows secure access to the local Docker Engine to UCP components
- **ucp-swarm-manager** : Used to provide backwards-compatibility with Docker Swarm

Components on worker :

- **ucp-agent** : same as manager
- **ucp-dsinfo** : same as manager
- **ucp-reconcile** : same as manager
- **ucp-proxy** : A TLS proxy. It allows secure access to the local Docker Engine to UCP components

repository: onepoint-tech/dca-prep-guide

repo_name: onepoint-tech/dca-prep-guide


text:
---
layout: post
title: Split
tags: [60min, Intermediate, Personal]
excerpt_separator: <!--more-->
---

A split sequence will build up towards those front and middle splits.
<!--more-->

| Section | Asana | Pose | Notes |
| ------ | ------ | ------ | ------ |
| Breathing | Bhastrika | Bellow’s breathe
| Warm up | Surya Namaskar A | Sun Salutation A | 5 times |
| | Surya Namaskar B | Sun Salutation B | 5 times |
| Standing | Padangusthasana | Big Toe pose
| | Virabhadrasana 1 | Warrior 1
| | Virabhadrasana 3 | Warrior 3 | Balance
| | Urdhva Prasarita Eka Padasana | One legged Standing Split | Balance
| | Parsvottanasana | Single leg bend forward
| | Virabhadrasana 1 | Warrior 1
| | Virabhadrasana 2 | Warrior 2
| | Ardha Chandrasana | Half moon pose | Balance
| | Trikonasana | Triangle
| | Parivrtta Trikonasana | Revolved Triangle
| | Prasarita Padottanasana | Spread leg bend forward pose
| | Virabhadrasana 2 | Warrior 2
| | Parshva Konasana | Side Angle pose
| | Baddha Parshva Konasana | Bound Side Angle pose
| | Swarga Dwidasana | Bird of Paradise
| | Virabhadrasana 2 | Warrior 2
| | Baddha Virabhadrasana | Humble Warrior
| Seated | Malasana | Garland
| | Baddha Malasana | Bound Garland
| | Malasana with heels and toes together | Malasana variation with heels and toes together |
| | Skandasana | Side lunge pose
| | Baddha Skandasana | Bound side lunge pose
| | Paschimottanasana | Seated forward bend
| | Ardha Upavistha Konasana | Half Front split
| | Janu Sirsasana | Half forward bend
| | Gomukhasana | Cow face pose | Counter
| | Baddha Konasana | Bound angle |
| Prone | Anjaneyasana | Low lunge
| | Anjaneyasana with quad stretch | Low lunge with quad stretch
| | Ardha Hanumanasana | Half money god pose
| | Balasana | Child Pose | Counter
| | Utthan Pristhasana | Lizard
| | Eka Pada Rajakapotasana | One legged sleeping pigeon
| | Utthita Shishosana | Puppy pose
| | Ardha Bhekasana | Half frog pose
| | Anantasana | Side-Reclining Leg Lift
| Supine | Ardha Supta Virasana | Half reclined hero
| | Ananda Balasana | Happy baby pose
| | Supta Padangusthasana | Supine hand to toe pose
| | Parshva Supta Padangusthasana | Side supine hand to toe pose
| | Pavanamukhtasana | Wind relieving pose
| | Supta Matsyendrasana | Supine Twist
| Inversion | Supta Konasana | Supine bound angle
| | Sirsasana | Head stand
| Cool down | Savasana | Corpse

repository: sayanee/yoga

gha_language: HTML

repo_name: sayanee/yoga


text:
Welcome to the **Extended XML Documentation Comments Completion Provider** project.

* [Get the current release](https://github.com/EWSoftware/ExtendedDocCommentsProvider/releases)
* [Ask a question or open an issue](https://github.com/EWSoftware/ExtendedDocCommentsProvider/issues)
* [Getting Started](https://ewsoftware.github.io/ExtendedDocCommentsProvider/html/141160ac-ba6a-4f6d-a802-1110aadea932.htm)
* [System Requirements and Building the Code](https://ewsoftware.github.io/ExtendedDocCommentsProvider/html/3BBB6221-417C-4F5C-B89A-563A8052CE35.htm)
* [Contributing](https://ewsoftware.github.io/ExtendedDocCommentsProvider/html/C60519F2-A2F7-4EB1-883F-96C51073CEB3.htm)

This project is an editor extension that augments the standard C# XML documentation comments elements with
custom elements, attributes, and attribute values supported by the Sandcastle Help File Builder and other
documentation tools.

license: MS-PL

repository: EWSoftware/ExtendedDocCommentsProvider

repo_name: EWSoftware/ExtendedDocCommentsProvider


text:
---
title: Refactoring
subtitle: Keep your code solid, dry, and easy to maintain.
accent: primary
icon: fas fa-sync
---

Refactoring is a process of improving your source code without creating a new functionality.
It helps you keep your code solid, dry, and easy to maintain.

## See Also
- [Refactoring and Cleaning Up Code](https://www.jetbrains.com/help/rider/Refactoring_and_Cleaning_Code.html)
- [Inplace Refactorings](https://www.jetbrains.com/help/rider/Refactorings__Inplace_Refactorings.html#change_signature)


text:
# Chapter 5: Detail Component

Currently the `HeroesComponent` displays both the list of heros and the deatails of a hero. Not only the component is bigger, but also it is hard to reuse. You may want to display hero details in other places but it is part of another component.

Once the problem is identified, the solution is straightforward: just put the hero details into a new component.

## 1 Create a New Component

As before, use Angular CLI to generate a component: `ng generate component hero-detail`. The command creates a `src/app/hero-detail` folder and the three files of the new component: the class file `hero-detail.component.ts`, the html file `hero-detail.component.html`, and the style file `hero-detail.component.css`.

## 2 Add an Input

To display the details of a hero, the hero detail component needs to take a hero as its input. Angular uses `@Input()` to mark a class property as the input of the component.

The `@Input()` is called a decorator. All decorators have a `@` prefix to distinguish it from other classes/functions. The `hero-detail.component.ts` has the following content:

```ts
import { Component, OnInit, Input } from '@angular/core'
import { Hero } from '../hero'

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css'],
})
export class HeroDetailComponent implements OnInit {
  @Input()
  hero: Hero

  constructor() {}

  ngOnInit() {}
}
```

## 3 Write the HTML Template

You cut the hero detail elements from the `HeroesComponent` and paste it to the `HeroDetailComponent`. Becuase only one hero is displayed in the hero detail component, revise the html template as the following:

```html
<div *ngIf="hero">
  <h2>{{hero.name | uppercase}} Details</h2>
  <div><span>id: </span>{{hero.id}}</div>
  <div>
    <label>name:
      <input [(ngModel)]="hero.name" placeholder="name"/>
    </label>
  </div>
</div>
```

## 4 Use the Component

To use the new component, it is similar to use an html element. Remove hero detail elements from the `heroes.component.html` and add this line: `<app-hero-detail [hero]="selectedHero"></app-hero-detail>`.

The `app-hero-detail` is the value of the `selector` metadata of the hero detail component. The `[hero]` means that the attribute value of `hero`, i.e., the `"selectedHero"` should be evaluated as a TS expression. The square brackets `[]` around an element attribute means that the attribute value is a TS expression, not a regular string. The value is TS code to be evaluated. In this example, the `selectedHero` is a property of heros component and its value is the current selected hero.

There is nothing changed in the UI but you have a reusable hero detail component that can be used in other places.

## 5 [], (), and [()]

You have seen all three types of symbols around an elment attribute.

The square bracket `[someAttribute]="something"` means that the attribute `someAttribute`'s value, `someting`, is a TS expression that will be evaluated and its result will be used as the value of `someAttribute`. To compare this with the version `someAttribute="something"` that doesn't have square bracket, the `someAttribute` is assigned a value of `something`, just a regular HTML attribute assignment.

The parenthesis `(someEvent)="eventListener"` is used to define an event listner.

The box of bananas `[()]` defines a two-way binding between an attribute and a component property.


text:
# Elsa's Farm
A nice farm in Riverwood to serve as a player home. This mod does not require any DLC and can be used with Vanilla Skyrim Special Edition.

I created the farm as a player home for one of my characters who happens to be named Elsa. I decided to create the farm for using [Alternate Start - Live Another Life](https://www.nexusmods.com/skyrimspecialedition/mods/272) where I could be a patron at an Inn. The sensible place to start would be the Sleeping Giant Inn in Riverwood.

You can install this from NexusMods here: [Elsa's Farm](https://www.nexusmods.com/skyrimspecialedition/mods/19671)

## Changes

### 1.2.0

* Removed armor crafting bench from lower level.
* Added armor crafting bench outside of house.
* Added sharpening wheel outside of house.
* Added forge (anvil) outside of house.
* Added smelter outside of house.
* Added tanning rack outside of house.

### 1.1.0
* Added a Shrine to Dibella and a necklace of Dibella.
* Added a rug near door with boots.
* Added a couple of outfits on top of bed.

repository: brotherhoodpaladin/ElsaFarm

repo_name: brotherhoodpaladin/ElsaFarm


text:
## 2.0.3
- Added `textKey` parameter

## 2.0.2+1
- Fixed screenshots

## 2.0.2
- Fixed bug where `textScaleFactor` was not taken into account (thanks @Kavantix)

## 2.0.1
- Allow fractional font sizes again
- Fixed bug with `wrapWords` not working

## 2.0.0+2
- Added logo

## 2.0.0
- Significant performance improvements
- Prevent word wrapping using `wordWrap: false`
- Replacement widget in case of text overflow: `overflowReplacement`
- Added `strutStyle` parameter from `Text`
- Fixed problem in case the `AutoSizeTextGroup` changes
- Improved documentation
- Added many more tests

## 1.1.2
- Fixed bug where system font scale was applied twice (thanks @jeffersonatsafe)

## 1.1.1
- Fixed bug where setting the style of a `TextSpan` to null in `AutoSizeText.rich` didn't work (thanks @Koridev)
- Allow `minFontSize = 0`

## 1.1.0
- Added `group` parameter and `AutoSizeGroup` to synchronize multiple `AutoSizeText`s
- Fixed bug where `minFontSize` was not used correctly
- Improved documentation

## 1.0.0
- Library is used in multiple projects in production and is considered stable now.
- Added more tests

## 0.3.0
- Added textScaleFactor property with fallback to `MediaQuery.textScaleFactorOf()` (thanks @jeroentrappers)

## 0.2.2
- Fixed tests
- Improved documentation

## 0.2.1
- Fixed problem with `minFontSize` and `maxFontSize` (thanks @apaatsio)

## 0.2.0
- Added support for Rich Text using `AutoSizeText.rich()` with one or multiple `TextSpan`s.
- Improved text size calculation (using `textScaleFactor`)

## 0.1.0
- Fixed documentation (thanks @g-balas)
- Added tests

## 0.0.2
- Fixed documentation
- Added example

## 0.0.1
- First Release


text:
---
title: Higher-Order Functions
date: 2018-04-23
headerImg: books.jpg
---

## Plan for this week

**Last week:**

  * user-defined *data types*
    - and how to manipulate them using *pattern matching* and *recursion*
  * how to make recursive functions more efficient with *tail recursion*

**This week:**

  * code reuse with *higher-order functions* (HOFs)

  * some useful HOFs: `map`, `filter`, and `fold`

## Recursion is good...

- Recursive code mirrors recursive data

    - Base constructor -> Base case
    - Inductive constructor -> Inductive case (with recursive call)

- But it can get kinda repetitive!

## Example: evens

Let's write a function `evens`:

```haskell
-- evens []        ==> []
-- evens [1,2,3,4] ==> [2,4]
```

```haskell
evens       :: [Int] -> [Int]
evens []     = ...
evens (x:xs) = ...
```

## Example: four-letter words

Let's write a function `fourChars`:

```haskell
-- fourChars [] ==> []
-- fourChars ["i","must","do","work"] ==> ["must","work"]
```

```haskell
fourChars :: [String] -> [String]
fourChars []     = ...
fourChars (x:xs) = ...
```

## Yikes, Most Code is the Same

Lets rename the functions to `foo`:

```haskell
foo []            = []
foo (x:xs)
  | x mod 2 == 0  = x : foo xs
  | otherwise     =     foo xs

foo []            = []
foo (x:xs)
  | length x == 4 = x : foo xs
  | otherwise     =     foo xs
```

Only difference is **condition**

- `x mod 2 == 0` vs `length x == 4`

## Moral of the day

**D.R.Y.** Don't Repeat Yourself!

Can we

  * *reuse* the general pattern and
  * *substitute in* the custom condition?

## HOFs to the rescue!

General **Pattern**

  - expressed as a *higher-order function*
  - takes customizable operations as *arguments*

Specific **Operation**

  - passed in as an argument to the HOF

## The "filter" pattern

![The `filter` Pattern](/static/img/filter-pattern.png)

General Pattern

- HOF `filter`
- Recursively traverse list and pick out elements that satisfy a predicate

Specific Operations

- Predicates `isEven` and `isFour`

![`filter` instances](/static/img/filter-pattern-instance.png)

**Avoid duplicating code!**

## Let's talk about types

```haskell
-- evens [1,2,3,4] ==> [2,4]
evens :: [Int] -> [Int]
evens xs = filter isEven xs
  where
    isEven :: Int -> Bool
    isEven x  =  x `mod` 2 == 0
```

```haskell
filter :: ???
```

```haskell
-- fourChars ["i","must","do","work"] ==> ["must","work"]
fourChars :: [String] -> [String]
fourChars xs = filter isFour xs
  where
    isFour :: String -> Bool
    isFour x  =  length x == 4
```

```haskell
filter :: ???
```

So what's the type of `filter`?

```haskell
filter :: (Int -> Bool) -> [Int] -> [Int] -- ???

filter :: (String -> Bool) -> [String] -> [String] -- ???
```

* It *does not care* what the list elements are

    * as long as the predicate can handle them

* It's type is **polymorphic** (generic) in the type of list elements

```haskell
-- For any type `a`
--   if you give me a predicate on `a`s
--   and a list of `a`s,
--   I'll give you back a list of `a`s
filter :: (a -> Bool) -> [a] -> [a]
```

## Example: all caps

Lets write a function `shout`:

```haskell
-- shout []                    ==> []
-- shout ['h','e','l','l','o'] ==> ['H','E','L','L','O']
```

```haskell
shout :: [Char] -> [Char]
shout []     = ...
shout (x:xs) = ...
```

## Example: squares

Lets write a function `squares`:

```haskell
-- squares []        ==> []
-- squares [1,2,3,4] ==> [1,4,9,16]
```

```haskell
squares :: [Int] -> [Int]
squares []     = ...
squares (x:xs) = ...
```

## Yikes, Most Code is the Same

Lets rename the functions to `foo`:

```haskell
-- shout
foo []     = []
foo (x:xs) = toUpper x : foo xs

-- squares
foo []     = []
foo (x:xs) = (x * x)   : foo xs
```

Lets **refactor** into the **common pattern**

```haskell
pattern = ...
```

## The "map" pattern

![The `map` Pattern](/static/img/map-pattern.png)

General Pattern

- HOF `map`
- Apply a transformation `f` to each element of a list

Specific Operations

- Transformations `toUpper` and `\x -> x * x`

```haskell
map f []     = []
map f (x:xs) = f x : map f xs
```

Lets refactor `shout` and `squares`

```haskell
shout   = map ...

squares = map ...
```

![`map` instances](/static/img/map-pattern-instance.png)

## QUIZ

What is the type of `map`?

```haskell
map f []     = []
map f (x:xs) = f x : map f xs
```

**(A)** `(Char -> Char) -> [Char] -> [Char]`

**(B)** `(Int -> Int) -> [Int] -> [Int]`

**(C)** `(a -> a) -> [a] -> [a]`

**(D)** `(a -> b) -> [a] -> [b]`

**(E)** `(a -> b) -> [c] -> [d]`

```haskell
-- For any types `a` and `b`
--   if you give me a transformation from `a` to `b`
--   and a list of `a`s,
--   I'll give you back a list of `b`s
map :: (a -> b) -> [a] -> [b]
```

**Type says it all!**

* The only meaningful thing a function of this type can do is apply its first argument to elements of the list

* Hoogle it!

Things to try at home:

  * can you write a function `map' :: (a -> b) -> [a] -> [b]` whose behavior is different from `map`?

  * can you write a function `map' :: (a -> b) -> [a] -> [b]`
    such that `map' f xs` returns a list whose elements are not in `map f xs`?

## QUIZ

What is the value of `quiz`?

```haskell
map :: (a -> b) -> [a] -> [b]

quiz = map (\(x, y) -> x + y) [1, 2, 3]
```

**(A)** `[2, 4, 6]`

**(B)** `[3, 5]`

**(C)** Syntax Error

**(D)** Type Error

**(E)** None of the above

(I) final

    *Answer:* D (list elements are integers, but operation expects a pair)

## Don't Repeat Yourself

Benefits of **factoring** code with HOFs:

- Reuse iteration pattern

    - think in terms of standard patterns

    - less to write

    - easier to communicate

- Avoid bugs due to repetition

## Recall: length of a list

```haskell
-- len []      ==> 0
-- len ["carne","asada"] ==> 2
len :: [a] -> Int
len []     = 0
len (x:xs) = 1 + len xs
```

## Recall: summing a list

```haskell
-- sum []      ==> 0
-- sum [1,2,3] ==> 6
sum :: [Int] -> Int
sum []     = 0
sum (x:xs) = x + sum xs
```

## Example: string concatenation

Let's write a function `cat`:

```haskell
-- cat [] ==> ""
-- cat ["carne","asada","torta"] ==> "carneasadatorta"
cat :: [String] -> String
cat []     = ...
cat (x:xs) = ...
```

## Can you spot the pattern?

```haskell
-- len
foo []     = 0
foo (x:xs) = 1 + foo xs

-- sum
foo []     = 0
foo (x:xs) = x + foo xs

-- cat
foo []     = ""
foo (x:xs) = x ++ foo xs
```

```haskell
pattern = ...
```

## The "fold-right" pattern

![The `foldr` Pattern](/static/img/foldr-pattern.png)

General Pattern

- Recurse on tail
- Combine result with the head using some binary operation

```haskell
foldr f b []     = b
foldr f b (x:xs) = f x (foldr f b xs)
```

Let's refactor `sum`, `len` and `cat`:

```haskell
sum = foldr ...  ...

cat = foldr ...  ...

len = foldr ...  ...
```

Factor the recursion out!

![`foldr` instances](/static/img/foldr-pattern-instance.png)

You can write it more clearly as

```haskell
sum = foldr (+) 0

cat = foldr (++) ""
```

## The "fold-right" pattern

```haskell
foldr f b [a1, a2, a3, a4]
  ==> f a1 (foldr f b [a2, a3, a4])
  ==> f a1 (f a2 (foldr f b [a3, a4]))
  ==> f a1 (f a2 (f a3 (foldr f b [a4])))
  ==> f a1 (f a2 (f a3 (f a4 (foldr f b []))))
  ==> f a1 (f a2 (f a3 (f a4 b)))
```

Accumulate the values from the **right**

For example:

```haskell
foldr (+) 0 [1, 2, 3, 4]
  ==> 1 + (foldr (+) 0 [2, 3, 4])
  ==> 1 + (2 + (foldr (+) 0 [3, 4]))
  ==> 1 + (2 + (3 + (foldr (+) 0 [4])))
  ==> 1 + (2 + (3 + (4 + (foldr (+) 0 []))))
  ==> 1 + (2 + (3 + (4 + 0)))
```

## QUIZ

What does this evaluate to?

```haskell
foldr f b []     = b
foldr f b (x:xs) = f x (foldr f b xs)

quiz = foldr (\x v -> x : v) [] [1,2,3]
```

**(A)** Type error

**(B)** `[1,2,3]`

**(C)** `[3,2,1]`

**(D)** `[[3],[2],[1]]`

**(E)** `[[1],[2],[3]]`

```haskell
foldr (:) [] [1,2,3]
  ==> (:) 1 (foldr (:) [] [2, 3])
  ==> (:) 1 ((:) 2 (foldr (:) [] [3]))
  ==> (:) 1 ((:) 2 ((:) 3 (foldr (:) [] [])))
  ==> (:) 1 ((:) 2 ((:) 3 []))
  ==  1 : (2 : (3 : []))
  ==  [1,2,3]
```

## QUIZ

What is the most general type of `foldr`?

```haskell

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f b []     = b
foldr f b (x:xs) = f x (foldr f b xs)
```

**(A)** `(a -> a -> a) -> a -> [a] -> a`

**(B)** `(a -> a -> b) -> a -> [a] -> b`

**(C)** `(a -> b -> a) -> b -> [a] -> b`

**(D)** `(a -> b -> b) -> b -> [a] -> b`

**(E)** `(b -> a -> b) -> b -> [a] -> b`

(I) final

    *Answer:* D

## Tail Recursion

Recursive call is the *top-most* sub-expression in the function body

  - i.e. no computations allowed on recursively returned value

  - i.e. value returned by the recursive call == value returned by function

### QUIZ: Is this function tail recursive?

```haskell
fac :: Int -> Int
fac n
  | n <= 1    = 1
  | otherwise = n * fac (n - 1)
```

fac 10000
  ==> 10000 * (fac 9999)
  ==> 10000 * 9999 * (fac 9998)

facTR 10000
  ==> loop 1 10000
  ==> loop 10000 (9999)
  ==> loop (10000 * 9999) (9998)
  ==> loop (10000 * 9999 * 9998) (9997)

**A.** Yes

**B.** No

(I) final

    *Answer:* B

## Tail recursive factorial

Let's write a tail-recursive factorial!

(I) lecture

```haskell
facTR :: Int -> Int
facTR n = loop 1 n
  where
    loop acc n
      | 1 <= n    = loop (acc * n) (n - 1)
      | otherwise = acc
```

```python
def fac(n):
  acc = 1
  while (1 <= n):
    acc = acc * n
    n   = n - 1
  return acc
```

(I) final

    ```haskell
    facTR :: Int -> Int
    facTR n = loop 1 n
      where
        loop :: Int -> Int -> Int
        loop acc n
          | n <= 1    = acc
          | otherwise = loop (acc * n) (n - 1)
    ```

Lets see how `facTR` is evaluated:

```haskell
facTR 4
  ==> loop 1  4     -- call loop 1 4
  ==> loop 4  3     -- rec call loop 4 3
  ==> loop 12 2     -- rec call loop 12 2
  ==> loop 24 1     -- rec call loop 24 1
  ==> 24            -- return result 24!
```

Each recursive call **directly** returns the result

  - without further computation

  - no need to remember what to do next!

  - no need to store the "empty" stack frames!

## Why care about Tail Recursion?

Because the _compiler_ can transform it into a _fast loop_

```haskell
facTR n = loop 1 n
  where
    loop acc n
      | n <= 1    = acc
      | otherwise = loop (acc * n) (n - 1)
```

```javascript
function facTR(n){
  var acc = 1;
  while (true) {
    if (n <= 1) { return acc ; }
    else        { acc = acc * n; n = n - 1; }
  }
}
```

- Tail recursive calls can be optimized as a **loop**

    - no stack frames needed!

- Part of the language specification of most functional languages

    - compiler **guarantees** to optimize tail calls

## Tail Recursive Fold

```haskell
foldr f b []     = b
foldr f b (x:xs) = f x (foldr f b xs)
```

Is `foldr` **tail recursive**?

(I) final

    *Answer:* No! It calls the binary operations on the results of the recursive call

## What about tail-recursive versions?

Let's write tail-recursive `sum`!

```haskell
sumTR :: [Int] -> Int
sumTR = ...
```

Lets run `sumTR` to see how it works

```haskell
sumTR [1,2,3]
  ==> helper 0 [1,2,3]
  ==> helper 1   [2,3]    -- 0 + 1 ==> 1
  ==> helper 3     [3]    -- 1 + 2 ==> 3
  ==> helper 6      []    -- 3 + 3 ==> 6
  ==> 6
```

**Note:** `helper` directly returns the result of recursive call!

Let's write tail-recursive `cat`!

```haskell
catTR :: [String] -> String
catTR = ...
```

Lets run `catTR` to see how it works

```haskell
catTR                 ["carne", "asada", "torta"]

  ==> helper ""       ["carne", "asada", "torta"]

  ==> helper "carne"           ["asada", "torta"]

  ==> helper "carneasada"               ["torta"]

  ==> helper "carneasadatorta"                 []

  ==> "carneasadatorta"
```

**Note:** `helper` directly returns the result of recursive call!

## Can you spot the pattern?

```haskell
-- sumTR
foo xs                = helper 0 xs
  where
    helper acc []     = acc
    helper acc (x:xs) = helper (acc + x) xs

-- catTR
foo xs                = helper "" xs
  where
    helper acc []     = acc
    helper acc (x:xs) = helper (acc ++ x) xs
```

```haskell
pattern = ...
```

## The "fold-left" pattern

![The `foldl` Pattern](/static/img/foldl-pattern.png)

General Pattern

- Use a helper function with an extra accumulator argument
- To compute new accumulator, combine current accumulator with the head using some binary operation

```haskell
foldl f b xs          = helper b xs
  where
    helper acc []     = acc
    helper acc (x:xs) = helper (f acc x) xs
```

Let's refactor `sumTR` and `catTR`:

```haskell
sumTR = foldl ...  ...

catTR = foldl ...  ...
```

Factor the tail-recursion out!

## QUIZ

What does this evaluate to?

```haskell
foldl f b xs          = helper b xs
  where
    helper acc []     = acc
    helper acc (x:xs) = helper (f acc x) xs

quiz = foldl (\xs x -> x : xs) [] [1,2,3]
```

**(A)** Type error

**(B)** `[1,2,3]`

**(C)** `[3,2,1]`

**(D)** `[[3],[2],[1]]`

**(E)** `[[1],[2],[3]]`

(I) final

    *Answer:* C

```
foldl f b (x1: x2: x3 : [])
  ==> helper b (x1: x2: x3 : [])
  ==> helper (f x1 b)  (x2: x3 : [])
  ==> helper (f x2 (f x1 b))  (x3 : [])
  ==> helper (f x3 (f x2 (f x1 b)))  []
  ==> ( x3 :  (x2 : (x1 : [])))
```

## The "fold-left" pattern

```haskell
foldl f b                     [x1, x2, x3, x4]
  ==> helper b                [x1, x2, x3, x4]
  ==> helper (f b x1)             [x2, x3, x4]
  ==> helper (f (f b x1) x2)          [x3, x4]
  ==> helper (f (f (f b x1) x2) x3)       [x4]
  ==> helper (f (f (f (f b x1) x2) x3) x4)  []
  ==> (f (f (f (f b x1) x2) x3) x4)
```

Accumulate the values from the **left**

For example:

```haskell
foldl (+) 0                   [1, 2, 3, 4]
  ==> helper 0                [1, 2, 3, 4]
  ==> helper (0 + 1)             [2, 3, 4]
  ==> helper ((0 + 1) + 2)          [3, 4]
  ==> helper (((0 + 1) + 2) + 3)       [4]
  ==> helper ((((0 + 1) + 2) + 3) + 4)  []
  ==> ((((0 + 1) + 2) + 3) + 4)
```

## Left vs. Right

```haskell
foldl f b [x1, x2, x3]  ==> f (f (f b x1) x2) x3  -- Left

foldr f b [x1, x2, x3]  ==> f x1 (f x2 (f x3 b))  -- Right
```

For example:

```haskell
foldl (+) 0 [1, 2, 3]  ==> ((0 + 1) + 2) + 3  -- Left

foldr (+) 0 [1, 2, 3]  ==> 1 + (2 + (3 + 0))  -- Right
```

Different types!

```haskell
foldl :: (b -> a -> b) -> b -> [a] -> b  -- Left

foldr :: (a -> b -> b) -> b -> [a] -> b  -- Right
```

## Higher Order Functions

Iteration patterns over collections:

- **Filter** values in a collection given a *predicate*
- **Map** (iterate) a given *transformation* over a collection
- **Fold** (reduce) a collection into a value, given a *binary operation* to combine results

HOFs can be put into libraries to enable modularity

- Data structure **library** implements `map`, `filter`, `fold` for its collections

    - generic efficient implementation

    - generic optimizations: `map f (map g xs) --> map (f.g) xs`

- Data structure **clients** use HOFs with specific operations

    - no need to know the implementation of the collection

Crucial foundation of

- "big data" revolution e.g. _MapReduce_, _Spark_, _TensorFlow_

- "web programming" revolution e.g. _Jquery_, _Angular_, _React_


text:
# Dijkstraruby

Here we have the implementation of dijkstra algorithm in ruby

## Installation

Add this line to your application's Gemfile:

    gem 'dijkstraruby'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install dijkstraruby

## Usage

Using the rake task

    $ rake get_path

## Contributing

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

repository: heridev/shorthest-path-ruby

repo_name: heridev/shorthest-path-ruby