text:
# Under One Roof

## Project Summary:
=================================================================

This is a full stack web application that allows for a household to create a unique account, add roommates as users with important contact information, create a chore list and fairly delegate them out, add expenses and dynamically update a household budget, and add events for important dates and reminders. Each user has their own homepage that aggregates the information pertinent to them. The stack used is Sequelize, Express, React, and Node.

[DeployedSite]()

![IMAGE](https://github.com/profjjk/under-one-roof/blob/main/client/public/assets/README/UnderOneRoofDEMO.gif)

## Table of Contents:
=================================================================

* [Technologies Used](##technologies-used:)
* [Installation](##installation:)
* [Process](##process:)
    - [SignUp Validation with React](###signup-validation-with-react)
    - [Login Validation with React](###login-validation-&-jwt-creation)
* [Authors](##authors:)
* [License](##license:)
* [Acknowledgements](##acknowledgements:)

## Technologies Used:
=================================================================

- [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML)
- [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS)
- [Bootstrap](https://getbootstrap.com/)
- [JavaScript](https://www.javascript.com/)
- [jQuery](https://jquery.com/)
- [JSON](https://www.json.org/json-en.html)
- [MySQL](https://www.mysql.com/)
- [Sequelize](https://sequelize.org/)
- [Express.js](https://expressjs.com/)
- [React](https://reactjs.org/)
- [Node.js](https://nodejs.org/en/)
- [bcryptjs](https://www.npmjs.com/package/bcryptjs)
- [react-calendar](https://www.npmjs.com/package/react-calendar)
- [react-dayjs](https://www.npmjs.com/package/react-dayjs)
- [react-dom](https://reactjs.org/docs/react-dom.html)
- [react-router-dom](https://reactrouter.com/web/guides/quick-start)
- [react-scripts](https://www.npmjs.com/package/react-scripts)
- [react-table](https://www.npmjs.com/package/react-table)
- [react-validation](https://www.npmjs.com/package/react-validation)
- [react-vis](https://uber.github.io/react-vis/)
- [JWT](https://jwt.io/)
- [Day.js](https://day.js.org/)
- [mysql2](https://www.npmjs.com/package/mysql2)
- [Visual Studio Code](https://code.visualstudio.com/)

## Installation:
=================================================================

On the server side, run these command lines in the terminal:

```
npm i axios bcryptjs cors dayjs express if-env jsonwebtoken mysql2 path react react-table react-vis sequelize
```

On the client side, run these command lines

```
npm i @testing-library/jest-dom @testing-library/react @testing-library/user-event dayjs moment react react-calendar react-dayjs react-dom react-router-dom react-scripts react-table react-validation sequelize web-vitals
```

## Process:
=================================================================

### SignUp Validation with React

We used the react-validation library to validate forms. It is not easy to validate forms in react due to the one-way flow of data. We can't affect forms from the inputs in an easy way. React-validation provides several components which are 'connected' to the form via the input's method attached by the Form component.

![IMAGE](https://github.com/profjjk/under-one-roof/blob/main/client/public/assets/README/RequiredFieldsSignUp.png)

![IMAGE](https://github.com/profjjk/under-one-roof/blob/main/client/public/assets/README/SignUpFormValidation.png)

```javascript
import React, { useState, useRef } from "react";
import Form from "react-validation/build/form";
import Input from "react-validation/build/input";
import CheckButton from "react-validation/build/button";
import { isEmail } from "validator";

import AuthService from "../services/auth.service";

const required = (value) => {
  if (!value) {
    return (
      <div className="alert alert-danger" role="alert">
        This field is required!
      </div>
    );
  }
};

const validEmail = (value) => {
  if (!isEmail(value)) {
    return (
      <div className="alert alert-danger" role="alert">
        This is not a valid email.
      </div>
    );
  }
};

const vusername = (value) => {
  if (value.length < 3 || value.length > 40) {
    return (
      <div className="alert alert-danger" role="alert">
        The address or nickname must be between 3 and 40 characters.
      </div>
    );
  }
};

const vpassword = (value) => {
  if (value.length < 6 || value.length > 40) {
    return (
      <div className="alert alert-danger" role="alert">
        The password must be between 6 and 40 characters.
      </div>
    );
  }
};
```

![IMAGE](https://github.com/profjjk/under-one-roof/blob/main/client/public/assets/README/SuccessfulSignUp.png)

For the SignUp page, we used the message response from this form validation to trigger a ternary operator. A failed response returns an alert-danger with the message. A successful response returns a success alert with the message and redirect link to the Login page.

```javascript
{message && (
<div className="form-group">
    <div
    className={ successful ? "alert alert-success" : "alert alert-danger" }
    role="alert"
    >
    {message}
    </div>
    <div className="d-flex justify-content-center">
    <a href="/login">
        <img src="/assets/img/Login/loginICON-72.png" alt="Login button image" />
    </a>
    </div>
</div>
)}
```

### Login Validation & JWT Creation

![IMAGE](https://github.com/profjjk/under-one-roof/blob/main/client/public/assets/README/LoginValidation.jpg)

In this example, we validate the login credentials on the server side and grant a JWT for authentication only if the user is found with a corresponding hashed password. This token has a 24hr expiration for access.

```javascript
exports.signin = (req, res) => {
    // Sign in from Database
    Home.findOne({
        where: {
            username: req.body.username
        }
    })
        .then(user => {
            if (!user) {
                return res.status(404).send({ message: "User Not found." });
            }

            var passwordIsValid = bcrypt.compareSync(
                req.body.password,
                user.password
            );

            if (!passwordIsValid) {
                return res.status(401).send({
                    accessToken: null,
                    message: "Invalid Password!"
                });
            }

            var token = jwt.sign({ id: user.id }, config.secret, {
                expiresIn: 86400 // 24 hours
            });

            res.status(200).send({
                id: user.id,
                username: user.username,
                email: user.email,
                accessToken: token
            });
        })
        .catch(err => {
            res.status(500).send({ message: err.message });
        });
};
```

### Expense Model & Budget/Expenses Pages

To run a shared budget and payments analysis within our application, we needed to add a model instance in our database that could contain details about an expense. This model also includes a boolean paid descriptor, and if the instance of the model has been paid, there needs to be an associated paid by name.

We instantiated this model as belonging to the Home model, which is our overarching login model.  With this relationship, we are able to restrict the data that is presented to an individiual home to only their own data.

```javascript
const currentUser = AuthService.getCurrentUser();

// Data Retrieval Functions
const getHomeId = () => {
    const HomeId = currentUser.id;
    return HomeId;
}

let HomeId = getHomeId();

const getExpenses = (data) => {
    let id = data;
    API.getExpenses(id)
    .then(results => {
        sortExpenses(results.data)
        dispatch({
            type: GET_EXPENSES,
            expenses: results.data
        });
    })
}

useEffect (async () =>  {
  await getExpenses(HomeId);
}, []);
```

Beyond this, we used react-vis to populate our pie and bar charts on the Budget page, which required formatting our stately variable data into the highly specific parameters for the react-vis built in components.

```javascript
const pieDataFormat = (data) => {
  // Create totals variables
  let rentSum = 0;
  let utilitiesSum = 0;
  let otherSum = 0;

  for (var i = 0; i < data.expenses.length; i++) {
      if (data.expenses[i].expenseType === "rent" || data.expenses[i].expenseType === "Rent") {
          rentSum += parseInt(data.expenses[i].expenseAmount);
      } else if (data.expenses[i].expenseType === "utilities" || data.expenses[i].expenseType == "Utilities") {
          utilitiesSum += parseInt(data.expenses[i].expenseAmount);
      } else {
          otherSum += parseInt(data.expenses[i].expenseAmount);
      }
  }

  const pieChart = [];
  pieChart.push({angle: rentSum, label: rentSum});
  pieChart.push({angle: utilitiesSum, label: utilitiesSum});
  pieChart.push({angle: otherSum, label: otherSum});
  return pieChart;
};
const pieData = pieDataFormat(state);

<div className="col-lg-7 chart d-flex justify-content-center">
  <RadialChart
  data={pieData}
  radius={125}
  width={300}
  height={300} />
</div>
```

Finally to create the reactive table at the bottom of the Budget page, we utilized the react-table package to create a clean manipulable table.

```javascript
<table className="table" border="1" {...getTableProps()} style={{textAlign: "center"}}>
  <thead className="table-header">
      {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map(column =>(
                  <th {...column.getHeaderProps(column.getSortByToggleProps())}>
                      {column.render("Header")}
                      <span>
                          {column.isSorted
                              ? column.isSortedDesc
                                  ? "🔽"
                                  : "🔼"
                              : ""}
                      </span>
                  </th>
              ))}
          </tr>
      ))}
  </thead>
  <tbody {...getTableBodyProps()}>
      {rows.map(row => {
          prepareRow(row)
          return (
              <tr {...row.getRowProps()}>
                  {row.cells.map(cell => {
                      return (
                          <td {...cell.getCellProps()} >
                              {cell.render("Cell")}
                          </td>
                      )
                  })}
              </tr>
          )
      })}
  </tbody>
</table>
```

## Authors

- Ryan Kirkland
    - [GitHub](https://github.com/RyanKirkland86)
    - [LinkedIn](https://www.linkedin.com/in/ryan-kirkland-619942200/)
- Jordan Kelly
    - [GitHub](https://github.com/profjjk)
    - [LinkedIn](https://www.linkedin.com/in/the-real-jordan-kelly/)
- Shaun Limbeek
    - [GitHub](https://github.com/slimbeek6)
    - [LinkedIn](https://www.linkedin.com/in/shaun-limbeek/)

## License

This Project is licensed under the MIT License.

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Acknowledgements

A special thanks to our instructors Jerome, Mahi, and Manuel for all of your help and support. You guys are the best!
- [UC Berkeley](https://bootcamp.berkeley.edu/coding/)


text:
---
layout: page
title : Projects
permalink: /projects/
---

#### [GitHub Package Registry](https://help.github.com/en/articles/about-github-package-registry)

GitHub Package Registry is a software package hosting service, similar to npmjs.org, rubygems.org, or hub.docker.com, that allows you to host your packages and code in one place. You can host software packages privately or publicly and use them as dependencies in your projects.

#### [GitHub Actions](https://developer.github.com/actions/)

GitHub Actions allow you to implement custom logic without having to create an app to perform the task you need. You can combine GitHub Actions to create workflows using an action defined in your repository, a public repository on GitHub, or a published Docker container image. GitHub Actions are customizable and can use the GitHub API and any publicly available third-party APIs to interact with a repository. For example, an action can publish npm modules, send SMS alerts when urgent issues are created, or deploy production ready code. You can discover, create, and share your GitHub Actions with the GitHub community.

#### [GitHub Dependency Graph & Security Alerts](https://help.github.com/articles/listing-the-packages-that-a-repository-depends-on/)

 With security vulnerability alerts, organization owners and repository admins receive a notification when any of their projects has a dependency with a known vulnerability. Organization owners can also share the responsibility by selecting additional individuals and teams to receive notifications when a vulnerability occurs.

#### [HPE Helion Code Engine](https://docs.hpcloud.com/stackato/index.html#stackato/ops/quickstart_hce.html)

HPE Helion Cloud Engine allows enterprise developers to automate the build/test/deploy cycle triggered by checkins into Git repositories and into our Cloud Foundry runtime, with intermediate artifacts that are pushed to the Docker Hub or an organization’s Docker Trusted Registry. In addition, HPE Helion Code Engine also integrates HPE Software’s StormRunner tool for load testing a microservice once it’s been deployed to a staging environment—so out of the box, we not only streamline the process, we simplify the load testing, a common and needed safety check in an enterprise CI/CD process.

#### [KhanAcademyJS](https://github.com/Phanatic/KhanAcademyJS/)
Node.JS SDK for interacting with Khan Academy APIs

#### Deploy Now to HP Helion

Designed, developed & delivered a one-click button to deploy applications from Github onto HP Helion aPaaS clusters.

#### [Eclipse plugin for Cloud Foundry](https://github.com/cloudfoundry-attic/eclipse-integration-cloudfoundry/commits?author=Phanatic)

Eclipse Tools for Cloud Foundry (CFT) provide an extensible framework and common UI to deploy applications to different Cloud Foundry targets, and it is a framework that closely integrates with Web Tools Platform (WTP) and Eclipse.

#### [pkgcloud](https://github.com/pkgcloud/pkgcloud/commits?author=Phanatic)

pkgcloud is a standard library for node.js that abstracts away differences among multiple cloud providers.

#### [pkgcloud-cli](https://github.com/pkgcloud/pkgcloud-cli/commits?author=Phanatic)

pkgcloud-cli is a command line interface to interact with multiple cloud providers.

#### [OData](http://www.odata.org/)
An open protocol to allow the creation and consumption of queryable and interoperable RESTful APIs in a simple and standard way.

#### [Azure HDInsight](https://docs.microsoft.com/en-us/azure/hdinsight/hdinsight-hadoop-introduction)

HDInsight is a cloud distribution on Microsoft Azure of the rapidly expanding Apache Hadoop technology stack for big data analysis. It includes implementations of Apache Spark, HBase, Kafka, Storm, Pig, Hive, Interactive Hive, Sqoop, Oozie, Ambari, and so on.

#### [Project Barcelona](https://blogs.technet.microsoft.com/mspfe/2012/05/10/project-barcelona-a-revolution-in-enterprise-metadata-management-part-2/)

Project Barcelona is designed to help IT immediately garner the benefit of metadata management with minimal initial investment, which means there will be no up-front planning, modeling and ongoing maintenance required when using this product.  Simply setup the product and configure the appropriate security account, and Project Barcelona will automatically start crawling and showing the results.

license: MIT

branch_name: refs/heads/master

extension: md

gha_language: HTML

gha_license_id: MIT

license_type: permissive


text:
---
permalink: /awareness-program/deliverables/i-am-here-now/
title: ""I'm here now" deliverable"
excerpt: "T-shirt design that makes people aware how they are absorbed in their smartphone."
last_modified_at: 2019-05-24T13+02:00
sidebar:
  nav: "activities"
custom_pagination:
  prev: /awareness-program/deliverables/
  next: /awareness-program/deliverables/
---

<!-- Please fill in the information below each header according to the instructions.

       - Do NOT remove section headers. Instead add the placeholder text if the section is not needed.
       - You can leave the comments. They can be helpful when editing the issue later on.
       - Replace brackets with appropriate information (unless part of a link), leaving formatting intact.
       - The non-comments texts below provide examples, unless they are placeholder text

    Note: You will not be wasting your time documenting all this. The information in this issue
          should be copied to the Deliverable README.md after your feedback is incorporated.
-->

## Info

<!-- Provide short name, which is actual title that is used when publishing. Also add the link to community forum topic that is used for general discussion.

The deliverable type is , in this case, 'Video'. For other deliverables this can be anything, such as Website, Image, Blog, Press Release, Meetup, Advert, etc.
-->

- Name: **I'm Here Now**
- Type: **T-Shirt**
- Campaign: [Goodies](/awareness-campaigns/campaigns/goodies/)
- Status: Preparing
- Affiliation: Official
- Original idea: [@micheleminno](https://community.humanetech.com/u/micheleminno/summary)
- Coordinator: TBD
- General discussion: [forum topic](https://community.humanetech.com/t/im-here-now-t-shirt-project/3153)
- Open issues: [github](https://github.com/humanetech-community/awareness-program/issues?q=is%3Aissue+is%3Aopen+label%3Aim-here-now)

## Summary

<!-- Clear and concise explanation in 1-3 lines of text. -->

T-shirt design that makes people aware how they are absorbed in their smartphone.

## Goals

<!-- Bullet list of the intended effects of the deliverable, separated by empty lines. -->

- Create a cool t-shirt that draws attention to the fact smartphone use is not always very social.

- Promote the [Humane Tech Community](https://community.humanetech.com) and [Center for Humane Technology](https://humanetech.com) at the same time.

## Concept

Concept designs for this deliverable where first created by [@micheleminno](https://community.humanetech.com/u/micheleminno/summary), as part of the [Humane Technology Design Contest](https://community.humanetech.com/t/join-the-cht-design-contest-and-win-and-please-give-us-your-vote/1868) that started on April 2018.

![I'm here now, Concept on black t-shirt](https://raw.githubusercontent.com/humanetech-community/humanetech-community-artwork/master/design-contest/submissions/im-here-now/humane-tech_im-here-now-shirt.jpg)

Two T-shirt designs, one in [black](https://raw.githubusercontent.com/humanetech-community/humanetech-community-artwork/master/design-contest/submissions/im-here-now/humane-tech_im-here-now-black.jpg) and one in [white](https://raw.githubusercontent.com/humanetech-community/humanetech-community-artwork/master/design-contest/submissions/im-here-now/humane-tech_im-here-now-white.jpg) background. The person wearing it will show the solution to the problem simply walking and being aware of the world and the people around her or him,
in contrast to what is depicted on the front of t-shirt.

People around her/him will be caught by the optical effect of the same person both walking eyes up and sucked on the phone,
and they will realize the augmented value of the person not being on their smartphone, but **being here in that moment**.

This could also be used as part of a viral campaign, maybe with hashtag **#imherenow**, combined with pictures taken by people while being present in the here and now and aware of the beauty of the world around them (e.g. like this person [on Instagram]( https://www.instagram.com/p/BhsdxSeAywj/?taken-by=energyisgod)).

The t-shirt can also be used as a gift to active community members, and reward in future crowdfunding campaigns.

## Status

Most of the online printing webshops can print only in a square in the fore and the back of the t-shirt ([here](https://community.humanetech.com/t/humane-tech-apparel-webshop-list-wiki-post/3172)'s the list).
A few of them provide 'all over' printing service, but it's not clear how much it would cost per unit and the time needed to print and ship the units or they ship only to US (i.e. [this one](https://www.scrappyapparel.com)).

A number of things need to be done, for the t-shirt to become available. You can see the open issues [here](https://github.com/humanetech-community/awareness-program/issues?q=is%3Aissue+is%3Aopen+label%3Aim-here-now).

## Resources

- Artwork files for the T-shirt design can be found here in the [Github Artwork repository](https://github.com/humanetech-community/humanetech-community-artwork/tree/master/design-contest/submissions/im-here-now)

- Reference to the Humane Tech Design Contest [forum topic](https://community.humanetech.com/t/-/1868) and [Github location](https://github.com/humanetech-community/humanetech-community-artwork/tree/master/design-contest).

- Design contest [Discussion topic](https://community.humanetech.com/t/cht-artwork-goodies-contest-general-discussion/1803) containing [first draft](https://community.humanetech.com/t/cht-artwork-goodies-contest-general-discussion/1803/12?u=aschrijver) of the design.

repository: humanetech-community/community-hub

gha_language: JavaScript

repo_name: humanetech-community/community-hub


text:
# Server Guide

The most barebones echo server:

```js
var restify = require('restify');

function respond(req, res, next) {
  res.send('hello ' + req.params.name);
  next();
}

var server = restify.createServer();
server.get('/hello/:name', respond);
server.head('/hello/:name', respond);

server.listen(8080, function() {
  console.log('%s listening at %s', server.name, server.url);
});
```

Try hitting that with the following curl commands to get a feel for
what restify is going to turn that into:

```sh
$ curl -is http://localhost:8080/hello/mark -H 'accept: text/plain'
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 10
Date: Mon, 31 Dec 2012 01:32:44 GMT
Connection: keep-alive

hello mark

$ curl -is http://localhost:8080/hello/mark
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 12
Date: Mon, 31 Dec 2012 01:33:33 GMT
Connection: keep-alive

"hello mark"

$ curl -is http://localhost:8080/hello/mark -X HEAD -H 'connection: close'
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 12
Date: Mon, 31 Dec 2012 01:42:07 GMT
Connection: close
```

Note that by default, curl uses `Connection: keep-alive`. In order to make the HEAD
method return right away, you'll need to pass `Connection: close`.

Since curl is often used with REST APIs, restify provides a plugin to work around
this idiosyncrasy in curl. The plugin checks whether the user agent is curl. If it
is, it sets the Connection header to "close" and removes the "Content-Length" header.

```js
server.pre(restify.pre.userAgentConnection());
```

See the [pre](#pre) method for more information.

## Creating a Server

Creating a server is straightforward, as you simply invoke the
`createServer` API, which takes an options object with the options listed
below (and `listen()` takes the same arguments as node's
[http.Server.listen](http://nodejs.org/docs/latest/api/http.html#http_server_listen_port_hostname_backlog_callback)):

```js
var restify = require('restify'),
fs = require('fs');

var server = restify.createServer({
  certificate: fs.readFileSync('path/to/server/certificate'),
  key: fs.readFileSync('path/to/server/key'),
  name: 'MyApp',
});

server.listen(8080);
```

|Option|Type|Description|
|----------|--------|---------------|
|certificate|String|If you want to create an HTTPS server, pass in the path to PEM-encoded certificate and key|
|key|String|If you want to create an HTTPS server, pass in the path to PEM-encoded certificate and key|
|formatters|Object|Custom response formatters for `res.send()`|
|handleUncaughtExceptions|Boolean|When true (default is false) restify will use a domain to catch and respond to any uncaught exceptions that occur in it's handler stack|
|log|Object|You can optionally pass in a [bunyan](https://github.com/trentm/node-bunyan) instance; not required|
|name|String|By default, this will be set in the `Server` response header, default is `restify` |
|spdy|Object|Any options accepted by [node-spdy](https://github.com/indutny/node-spdy)|
|version|String|Array|A default version to set for all routes|
|handleUpgrades|Boolean|Hook the `upgrade` event from the node HTTP server, pushing `Connection: Upgrade` requests through the regular request handling chain; defaults to `false`|
|httpsServerOptions|Object|Any options accepted by [node-https Server](http://nodejs.org/api/https.html#https_https). If provided the following restify server options will be ignored: spdy, ca, certificate, key, passphrase, rejectUnauthorized, requestCert and ciphers; however these can all be specified on httpsServerOptions.|
|reqIdHeaders|Array|an optional array of request id header names that will be used to set the request id (i.e., the value for req.getId())|
|strictRouting|Boolean|(Default=`false`). If set, Restify will treat "/foo" and "/foo/" as different paths.|

## Common handlers: server.use()

A restify server has a `use()` method that takes handlers of
the form `function (req, res, next)`.   Note that restify runs
handlers in the order they are registered on a server, so if you want
some common handlers to run before any of your routes, issue calls to
`use()` before defining routes.

Note that in all calls to `use()` and the routes below, you can pass
in any combination of direct functions (`function(res, res, next)`) and
arrays of functions (`[function(req, res, next)]`).

## Routing

restify routing, in 'basic' mode, is pretty much identical to express/sinatra,
in that HTTP verbs are used with a parameterized resource to determine
what chain of handlers to run.  Values associated with named
placeholders are available in `req.params`. Note that values will be
URL-decoded before being passed to you.

```js
function send(req, res, next) {
  res.send('hello ' + req.params.name);
  return next();
}

server.post('/hello', function create(req, res, next) {
  res.send(201, Math.random().toString(36).substr(3, 8));
  return next();
});
server.put('/hello', send);
server.get('/hello/:name', send);
server.head('/hello/:name', send);
server.del('hello/:name', function rm(req, res, next) {
  res.send(204);
  return next();
});
```

You can also pass in a [RegExp](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp)
object and access the capture group with `req.params` (which will not
be interpreted in any way):

```js
server.get(/^\/([a-zA-Z0-9_\.~-]+)\/(.*)/, function(req, res, next) {
  console.log(req.params[0]);
  console.log(req.params[1]);
  res.send(200);
  return next();
});
```

Here any request like:

```sh
$ curl localhost:8080/foo/my/cats/name/is/gandalf
```

Would result in `req.params[0]` being `foo` and `req.params[1]` being
`my/cats/name/is/gandalf`.  Basically, you can do whatever you want.

Note the use of `next()`.  You are responsible for calling `next()` in
order to run the next handler in the chain.  As below, you can pass an
Error object in to have restify automatically return responses to the client.

You can pass in  `false` to not error, but to stop the handler
chain.  This is useful if you had a `res.send` in an early filter, which is
not an error, and you possibly have one later you want to short-circuit.

Lastly, you can pass in a string `name` to `next()`, and restify will lookup
that route, and assuming it exists will run the chain *from where you left
off*.  So for example:

```js
var count = 0;

server.use(function foo(req, res, next) {
    count++;
    next();
});

server.get('/foo/:id', function (req, res, next) {
   next('foo2');
});

server.get({
    name: 'foo2',
    path: '/foo/:id'
}, function (req, res, next) {
   assert.equal(count, 1);
   res.send(200);
   next();
});
```

Note that `foo` only gets run once in that example.  A few caveats:

- If you provide a name that doesn't exist, restify will 500 that request.
- Don't be silly and call this in cycles.  restify won't check that.
- Lastly, you cannot "chain" `next('route')` calls; you can only delegate the
  routing chain once (this is a limitation of the way routes are stored
  internally, and may be revisited someday).

### Chaining Handlers

Routes can also accept more than one handler function. For instance:

```js
server.get(
    '/foo/:id',
    function(req, res, next) {
        console.log('Authenticate');
        return next();
    },
    function(req, res, next) {
        res.send(200);
        return next();
    }
);
```

### Hypermedia

If a parameterized route was defined with a string (not a regex), you can render it from other places in the server. This is useful to have HTTP responses that link to other resources, without having to hardcode URLs throughout the codebase. Both path and query strings parameters get URL encoded appropriately.

```js
server.get({name: 'city', path: '/cities/:slug'}, /* ... */);

// in another route
res.send({
  country: 'Australia',
  // render a URL by specifying the route name and parameters
  capital: server.router.render('city', {slug: 'canberra'}, {details: true})
});
```

Which returns:

```js
{
  "country": "Australia",
  "capital": "/cities/canberra?details=true"
}
```

### Versioned Routes

Most REST APIs tend to need versioning, and restify ships with support
for [semver](http://semver.org/) versioning in an `Accept-Version`
header, the same way you specify NPM version dependencies:

```js
var restify = require('restify');

var server = restify.createServer();

function sendV1(req, res, next) {
  res.send('hello: ' + req.params.name);
  return next();
}

function sendV2(req, res, next) {
  res.send({hello: req.params.name});
  return next();
}

var PATH = '/hello/:name';
server.get({path: PATH, version: '1.1.3'}, sendV1);
server.get({path: PATH, version: '2.0.0'}, sendV2);

server.listen(8080);
```

Try hitting with:

```sh
$ curl -s localhost:8080/hello/mark
{"hello":"mark"}
$ curl -s -H 'accept-version: ~1' localhost:8080/hello/mark
"hello: mark"
$ curl -s -H 'accept-version: ~2' localhost:8080/hello/mark
{"hello":"mark"}
$ curl -s -H 'accept-version: ~3' localhost:8080/hello/mark | json
{
  "code": "InvalidVersion",
  "message": "GET /hello/mark supports versions: 1.1.3, 2.0.0"
}
```

In the first case, we didn't specify an `Accept-Version` header
at all, so restify treats that like sending a `*`. Much as not sending
an `Accept` header means the client gets the server's choice. Restify
will choose this highest matching route.
In the second case, we explicitly asked for for V1, which got
us response a response from the version 1 handler function,
but then we asked for V2 and got back JSON.  Finally,
we asked for a version that doesn't exist and got an error (notably,
we didn't send an `Accept` header, so we got a JSON response).  Which
segues us nicely into content negotiation.

You can default the versions on routes by passing in a version field at
server creation time.  Lastly, you can support multiple versions in the API
by using an array:

```js
server.get({path: PATH, version: ['2.0.0', '2.1.0', '2.2.0']}, sendV2);
```

In this case you may need to know more information such as what the
original requested version string was, and what the matching
version from the routes supported version array was. Two methods make
this info available:

```js
var PATH = '/version/test';
server.get({path: PATH, version: ['2.0.0', '2.1.0', '2.2.0']}, function (req) {
  res.send(200, {
    requestedVersion: req.version(),
    matchedVersion: req.matchedVersion()
  });
});
```

Hitting this route:

```sh
$ curl -s -H 'accept-version: <2.2.0' localhost:8080/version/test | json
{
  "requestedVersion": "<2.2.0",
  "matchedVersion": "2.1.0"
}
```

In response to the above

## Upgrade Requests

Incoming HTTP requests that contain a `Connection: Upgrade` header are treated
somewhat differently by the node HTTP server.  If you want restify to push
Upgrade requests through the regular routing chain, you need to enable
`handleUpgrades` when creating the server.

To determine if a request is eligible for Upgrade, check for the existence of
`res.claimUpgrade()`.  This method will return an object with two properties:
the `socket` of the underlying connection, and the first received data `Buffer`
as `head` (may be zero-length).

Once `res.claimUpgrade()` is called, `res` itself is marked unusable for
further HTTP responses; any later attempt to `send()` or `end()`, etc, will
throw an `Error`.  Likewise if `res` has already been used to send at least
part of a response to the client, `res.claimUpgrade()` will throw an `Error`.
Upgrades and regular HTTP Response behaviour are mutually exclusive on any
particular connection.

Using the Upgrade mechanism, you can use a library like
[watershed](https://github.com/jclulow/node-watershed) to negotiate WebSockets
connections.  For example:

```js
var ws = new Watershed();
server.get('/websocket/attach', function upgradeRoute(req, res, next) {
  if (!res.claimUpgrade) {
    next(new Error('Connection Must Upgrade For WebSockets'));
    return;
  }

  var upgrade = res.claimUpgrade();
  var shed = ws.accept(req, upgrade.socket, upgrade.head);
  shed.on('text', function(msg) {
    console.log('Received message from websocket client: ' + msg);
  });
  shed.send('hello there!');

  next(false);
});
```

## Content Negotiation

If you're using `res.send()` restify will automatically select the
content-type to respond with, by finding the first registered
`formatter` defined.  Note in the examples above we've not defined any
formatters, so we've been leveraging the fact that restify ships with
`application/json`,  `text/plain` and `application/octet-stream`
formatters.  You can add additional formatters to restify by passing
in a hash of content-type -> parser at server creation time:

```js
var server = restify.createServer({
  formatters: {
    'application/foo': function formatFoo(req, res, body, cb) {
      if (body instanceof Error)
        return body.stack;

      if (Buffer.isBuffer(body))
        return cb(null, body.toString('base64'));

      return cb(null, util.inspect(body));
    }
  }
});
```

You can do whatever you want, but you probably want to check the type
of `body` to figure out what type it is, notably for
Error/Buffer/everything else.  You can always add more formatters
later by just setting the formatter on `server.formatters`, but it's
probably sane to just do it at construct time.   Also, note that if a
content-type can't be negotiated, the default is
`application/json`.  Of course, you can always explicitly set
the content-type:

```js
res.setHeader('content-type', 'application/foo');
res.send({hello: 'world'});
```

Note that there are typically at least three content-types supported by
restify: json, text and binary.  When you override or append to this, the
"priority" might change; to ensure that the priority is set to what you
want, you should set a `q-value` on your formatter definitions, which will
ensure sorting happens the way you want:

```js
restify.createServer({
  formatters: {
    'application/foo; q=0.9': function formatFoo(req, res, body, cb) {
      if (body instanceof Error)
        return cb(body);

      if (Buffer.isBuffer(body))
        return cb(null, body.toString('base64'));

      return cb(null, util.inspect(body));
    }
  }
});
```

Lastly, you don't have to use any of this magic, as a restify response
object has all the "raw" methods of a node
[ServerResponse](http://nodejs.org/docs/latest/api/http.html#http.ServerResponse)
 on it as well.

```js
var body = 'hello world';
res.writeHead(200, {
  'Content-Length': Buffer.byteLength(body),
  'Content-Type': 'text/plain'
});
res.write(body);
res.end();
```

## Error handling

You can handle errors in restify a few different ways.  First, you can
always just call `res.send(err)`.  You can also shorthand this in a
route by doing:

```js
server.get('/hello/:name', function(req, res, next) {
  return database.get(req.params.name, function(err, user) {
    if (err)
      return next(err);

    res.send(user);
    return next();
  });
});
```

If you invoke `res.send()` with an error that has a `statusCode`
attribute, that will be used, otherwise a default of 500 will be used
(unless you're using `res.send(4xx, new Error('blah'))`).

Alternatively, restify 2.1 supports a `next.ifError` API:

```js
server.get('/hello/:name', function(req, res, next) {
  return database.get(req.params.name, function(err, user) {
    next.ifError(err);
    res.send(user);
    next();
  });
});
```

Sometimes, for all requests, you may want to handle an error condition the same
way. As an example, you may want to serve a 500 page on all
`InternalServerErrors`. In this case, you can add a listener for the
`InternalServer` error event that is always fired when this Error is
encountered by Restify as part of a `next(error)` statement. This gives you a
way to handle all errors of the same class identically across the server. You
can also use a generic `restifyError` event which will catch errors of all types.

```js
server.get('/hello/:name', function(req, res, next) {
  // some internal unrecoverable error
  var err = new restify.errors.InternalServerError('oh noes!');
  return next(err);
});

server.get('/hello/:foo', function(req, res, next) {
  // resource not found error
  var err = new restify.errors.NotFoundError('oh noes!');
  return next(err);
});

server.on('NotFound', function (req, res, err, cb) {
  // do not call res.send! you are now in an error context and are outside
  // of the normal next chain. you can log or do metrics here, and invoke
  // the callback when you're done. restify will automtically render the
  // NotFoundError as a JSON response.
  return cb();
});

server.on('InternalServer', function (req, res, err, cb) {
  // if you don't want restify to automatically render the Error object
  // as a JSON response, you can customize the response by setting the
  // `body` property of the error
  err.body = '<html><body>some custom error content!</body></html>';
  return cb();
});

server.on('restifyError', function (req, res, err, cb) {
  // this listener will fire after both events above!
  // `err` here is the same as the error that was passed to the above
  // error handlers.
  return cb();
});
```

### HttpError

Now the obvious question is what that exactly does (in either case).
restify tries to be programmer-friendly with errors by exposing all
HTTP status codes as a subclass of `HttpError`.  So, for example, you can
do this:

```js
server.get('/hello/:name', function(req, res, next) {
  return next(new restify.ConflictError("I just don't like you"));
});

$ curl -is -H 'accept: text/*' localhost:8080/hello/mark
HTTP/1.1 409 Conflict
Content-Type: text/plain
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Api-Version
Access-Control-Expose-Headers: Api-Version, Request-Id, Response-Time
Connection: close
Content-Length: 21
Content-MD5: up6uNh2ejV/C6JUbLlvsiw==
Date: Tue, 03 Jan 2012 00:24:48 GMT
Server: restify
Request-Id: 1685313e-e801-4d90-9537-7ca20a27acfc
Response-Time: 1

I just don't like you
```

Alternatively, you can access the error classes via `restify.errors`. We can do this with a simple change to the previous example:

```js
server.get('/hello/:name', function(req, res, next) {
  return next(new restify.errors.ConflictError("I just don't like you"));
});
```

The core thing to note about an `HttpError` is that it has a numeric
code (statusCode) and a `body`.  The statusCode will automatically
set the HTTP response status code, and the body attribute by default
will be the message.

All status codes between 400 and 5xx are automatically converted into
an HttpError with the name being 'PascalCase' and spaces removed.  For
the complete list, take a look at the
[node source](https://github.com/joyent/node/blob/v0.6/lib/http.js#L152-205).

From that code above `418: I'm a teapot` would be `ImATeapotError`, as
an example.

### RestError

Now, a common problem with REST APIs and HTTP is that they often end
up needing to overload 400 and 409 to mean a bunch of different
things.  There's no real standard on what to do in these cases, but in
general you want machines to be able to (safely) parse these things
out, and so restify defines a convention of a `RestError`.  A
`RestError` is a subclass of one of the particular `HttpError` types,
and additionally sets the body attribute to be a JS object with the
attributes `code` and `message`.  For example, here's a built-in RestError:

```js
var server = restify.createServer();
server.get('/hello/:name', function(req, res, next) {
  return next(new restify.InvalidArgumentError("I just don't like you"));
});

$ curl -is localhost:8080/hello/mark | json
HTTP/1.1 409 Conflict
Content-Type: application/json
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Api-Version
Access-Control-Expose-Headers: Api-Version, Request-Id, Response-Time
Connection: close
Content-Length: 60
Content-MD5: MpEcO5EQFUZ2MNeUB2VaZg==
Date: Tue, 03 Jan 2012 00:50:21 GMT
Server: restify
Request-Id: bda456dd-2fe4-478d-809c-7d159d58d579
Response-Time: 3

{
  "code": "InvalidArgument",
  "message": "I just don't like you"
}
```

The built-in restify errors are:

* BadRequestError (400 Bad Request)
* UnauthorizedError (401 Unauthorized)
* PaymentRequiredError (402 Payment Required)
* ForbiddenError (403 Forbidden)
* NotFoundError (404 Not Found)
* MethodNotAllowedError (405 Method Not Allowed)
* NotAcceptableError (406 Not Acceptable)
* ProxyAuthenticationRequiredError (407 Proxy Authentication Required)
* RequestTimeoutError (408 Request Time-out)
* ConflictError (409 Conflict)
* GoneError (410 Gone)
* LengthRequiredError (411 Length Required)
* PreconditionFailedError (412 Precondition Failed)
* RequestEntityTooLargeError (413 Request Entity Too Large)
* RequesturiTooLargeError (414 Request-URI Too Large)
* UnsupportedMediaTypeError (415 Unsupported Media Type)
* RequestedRangeNotSatisfiableError (416 Requested Range Not Satisfiable)
* ExpectationFailedError (417 Expectation Failed)
* ImATeapotError (418 I'm a teapot)
* UnprocessableEntityError (422 Unprocessable Entity)
* LockedError (423 Locked)
* FailedDependencyError (424 Failed Dependency)
* UnorderedCollectionError (425 Unordered Collection)
* UpgradeRequiredError (426 Upgrade Required)
* PreconditionRequiredError (428 Precondition Required)
* TooManyRequestsError (429 Too Many Requests)
* RequestHeaderFieldsTooLargeError (431 Request Header Fields Too Large)
* InternalServerError (500 Internal Server Error)
* NotImplementedError (501 Not Implemented)
* BadGatewayError (502 Bad Gateway)
* ServiceUnavailableError (503 Service Unavailable)
* GatewayTimeoutError (504 Gateway Time-out)
* HttpVersionNotSupportedError (505 HTTP Version Not Supported)
* VariantAlsoNegotiatesError (506 Variant Also Negotiates)
* InsufficientStorageError (507 Insufficient Storage)
* BandwidthLimitExceededError (509 Bandwidth Limit Exceeded)
* NotExtendedError (510 Not Extended)
* NetworkAuthenticationRequiredError (511 Network Authentication Required)
* BadDigestError (400 Bad Request)
* BadMethodError (405 Method Not Allowed)
* InternalError (500 Internal Server Error)
* InvalidArgumentError (409 Conflict)
* InvalidContentError (400 Bad Request)
* InvalidCredentialsError (401 Unauthorized)
* InvalidHeaderError (400 Bad Request)
* InvalidVersionError (400 Bad Request)
* MissingParameterError (409 Conflict)
* NotAuthorizedError (403 Forbidden)
* RequestExpiredError (400 Bad Request)
* RequestThrottledError (429 Too Many Requests)
* ResourceNotFoundError (404 Not Found)
* WrongAcceptError (406 Not Acceptable)

You can always add your own by subclassing `restify.RestError` like:

```js
var restify = require('restify');
var util = require('util');

function MyError(message) {
  restify.RestError.call(this, {
    restCode: 'MyError',
    statusCode: 418,
    message: message,
    constructorOpt: MyError
  });
  this.name = 'MyError';
};
util.inherits(MyError, restify.RestError);
```

Basically, a `RestError` takes a statusCode, a restCode, a message,
and a "constructorOpt" so that V8 correctly omits your code
from the stack trace (you don't *have* to do that, but you probably
want it).  In the example above, we also set the name property so
`console.log(new MyError());` looks correct.

## Socket.IO

To use [socket.io](http://socket.io/) with restify, just treat your restify
server as if it were a "raw" node server:

```js
var server = restify.createServer();
var io = socketio.listen(server.server);

server.get('/', function indexHTML(req, res, next) {
    fs.readFile(__dirname + '/index.html', function (err, data) {
        if (err) {
            next(err);
            return;
        }

        res.setHeader('Content-Type', 'text/html');
        res.writeHead(200);
        res.end(data);
        next();
    });
});

io.sockets.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
            console.log(data);
    });
});

server.listen(8080, function () {
    console.log('socket.io server listening at %s', server.url);
});
```

repository: nicolasartman/node-restify

repo_name: nicolasartman/node-restify


text:
---
title: AEM Forms tutorials and videos
description: Browse our videos and tutorials for AEM Forms, with resources and documentation to answer your queries.
topic: Development
role: Developer
sub-product: Experience Manager Forms
exl-id: c1972937-56c5-47af-9232-f31bdf69dfbe
---
# AEM Forms tutorials and videos {#overview}

Adobe Experience Manager (AEM) provides an easy-to-use solution to create, manage, publish, and update complex digital forms while integrating with back-end processes, business rules, and data. This user guide contains videos and tutorials on the many features and capabilities of AEM Forms

## What's new

* **[Handling Error Messages in Invoke Form Data Model Service Step](./adaptive-forms/handling-error-messages-in-invoke-fdm-step.md)**
    *A variable in a workflow model is a way to store a value based on its data type*

* **[Multi-Series Charts in Interactive Communication Documents(Video)](./interactive-communications/multiseriescharts.md)**
    *Plot more than one series in the same chart. The multiple series charts are typically used in association with Line, Bar, Column chart type.*

* **[Creating reusable workflow models](./adaptive-forms/re-usable-aem-forms-workflow-models-article.md)**
    *Create workflow models not tied to a specific form*

## Staff picks

    Create your first Adaptive Form

    Adaptive forms are new-generation forms that are dynamic and responsive. You can use Adaptive forms to deliver personalized experiences

    Create your first Print Channel Document

    Interactive Communications centralizes and manages the creation, assembly, and delivery of secure, personalized, and interactive correspondences such as business correspondence, documents, statements, benefit notices, marketing mails, bills, and welcome kits.

    Using Form Data Model in AEM Workflow

    Invoke Form Data Model's service as a step in AEM Workflow

## Additional resources

* [AEM Sites Authoring documentation](https://experienceleague.adobe.com/docs/experience-manager-65/authoring/home.html)
* [AEM Sites Developing documentation](https://experienceleague.adobe.com/docs/experience-manager-65/developing/home.html)
* [AEM Sites Administering documentation](https://experienceleague.adobe.com/docs/experience-manager-65/administering/home.html)
* [AEM Sites Deploying documentation](https://experienceleague.adobe.com/docs/experience-manager-65/deploying/home.html)
* [AEM as a Cloud Service tutorials](/help/cloud-service/overview.md)
* [AEM Assets tutorials](/help/assets/overview.md)
* [AEM Forms tutorials](/help/forms/overview.md)
* [AEM Foundation tutorials](/help/foundation/overview.md)

branch_name: refs/heads/main

gha_language: SCSS


text:
---
layout: page
title: Python Language Overview
---

[Ipython Notebook]()

## Reading
[Course reading](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2011/readings/)
[How to Think Like a Computer Scientist](http://www.greenteapress.com/thinkpython/thinkCSpy/thinkCSpy.pdf)
     - Chapters 1 and 2

## References
[MIT OPEN COURSEWARE: A Gentle Introduction to Programming Using Python](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-189-a-gentle-introduction-to-programming-using-python-january-iap-2011/readings/)


text:
---
name: Spock and I-Chaya
rarity: 5
series: tas
memory_alpha:
bigbook_tier: 4
events: 50
in_portal: true
date: 08/09/2021
obtained: Giveaway
mega: false
published: true
---

All eyes are on SpockBearPig's mouth-watering skill set and thus his voyage work, but it's probably better to think of Spock and Itchy as an event and collection piece who moonlights as a voyager.

With poor debut voyage power that will sink faster than most releases, you'll be counting on that vaunted skill order and accompanying traits to buoy his effectiveness. Due to the scarcity of the CMD/MED pairing, he should find at least minimal work on every roster for the immediate future, but cannot provide broader usability across different voyage combos like a power crew will.

More abiding are a pair of variant-best bases (not easy to do for a man with as many faces as Spock) and a quartet of collections. He may end up performing like a 2-skiller sooner than you'd think, but has all the supplementary tools to overcome poor base and voyage numbers and contribute.

repository: joshurtree/datacore-website

gha_language: TypeScript

repo_name: joshurtree/datacore-website


text:
---
layout: post
title:  "Cerebral Ray"
date:   2017-01-01
source: From the Arcane Archive
tags: [channeler, sorcerer, warlock, witch, wizard, level1, enchantment, hb, fan]
---

**1st-level enchantment**

**Casting Time**: 1 action

**Range**: 60 feet

**Components**: V, S

**Duration**: Instantaneous

A translucent beam of violet light streaks toward a creature within range. Make a ranged spell attack against the target. On a hit, the target takes 2d10 psychic damage and has disadvantage on ability checks until the beginning of your next turn.

**At Higher Levels.** When you cast this spell using a spell slot of 2nd level or higher, the damage increases by 1d10 for each slot level above 1st

repository: Teamdael/spellbook

extension: markdown

repo_name: Teamdael/spellbook


text:
EDIT 1: # This version of the static executor is deprecated:
Static executor has been implemented as a separate library here https://github.com/nobleo/static_executor with the following added features:
* Semi-dynamic (changes at runtime are allowed)
* Subscribers, Timers, Clients, Services and Waitables are supported
* Eloquent version is also available

Effort is currently focused on getting the static executor into the Foxy release with this PR: https://github.com/ros2/rclcpp/pull/873. This version of the static executor would be integrated into rclcpp and would come default with a ROS2 install (if approved). If you want to use the PR version right now, you will have to replace your entire rclcpp with the version here: https://github.com/nobleo/rclcpp/tree/nobleo/feature/static_executor. This version will have the latest changes and bug fixes, but requires more effort to use/install. Depending on future developments changes and bug fixes may or may not be applied to https://github.com/nobleo/static_executor as well.

EDIT 2:
The full functionality has been merged into the Foxy Release with additional optimizations. It is recommended to upgrade to Foxy and use the improved executor there.

# rclcpp
ROS2 dashing diademata rclcpp extended with a static executor POC

## Package goal
Provide a **proof of concept** of a static executor to show how much CPU overhead can be reduced. This executor was made in response to the findings here https://github.com/nobleo/ros2_performance and the discussion here https://discourse.ros.org/t/singlethreadedexecutor-creates-a-high-cpu-overhead-in-ros-2. The static executor is not yet ready to be used in actual products. Feel free to use it with your applications for testing. If you perform tests using this package please share your results on the discourse post. If we collect more data, we will be able to push for changes to the core ROS2 stack.

## Test Results
Depends on:
- this version of rclcpp
- https://github.com/nobleo/ros2_performance/tree/master
- https://github.com/nobleo/ros2_performance/tree/static_executor

| Binary  | publishers | subscribers | ROS | ROS nodes | ROS timers | DDS participants |
| ------------- | ------------- |------------- |------------- |------------- |------------- |------------- |
| ros | 20  | 200 | yes | 10 | 10 | 10 |
| rosonenode | 20 | 200 | yes | 1 | 1 | 1 |
| FastRTPS | 20 | 200 | no | 0 | 0 | 1 |

For all binaries:
- Message frequency: 50Hz
- Message type: String
- Message content: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
- QOS: depth = 10, reliability = best effort, durability = transient local

![Alt text](/images/Static_executor_docker_stats.png?raw=true "Docker comparison between SingleThreadedExecutor, StaticExecutor and pure FastRTPS")

## How to recreate test results
It is possible to git clone this repository, build the workspace using colcon build and inspect the CPU usage with top or a similar program for each binary individually. It is however much easier to give each binary its own container (make sure to separate their networks or give them a unique ROS_DOMAIN_ID) and measure the usage of each container.
If you don't have docker and docker compose installed first follow online tutorials on how to install these: https://docs.docker.com/install/ https://docs.docker.com/compose/install/ .

Assuming you replaced the existing rclcpp package in your ROS2 environment with this version perform the following steps:

1. Go to the repository with the dockerfiles
```
cd ~/ros2_ws/src/ros2/rclcpp/Dockerfiles
```
2. Build the images using the following names (building ROS2 from source will take along time! ~1 hour):
```
cd dashing_source
docker build -t ros:dashing_source .
cd ../ros2_performance_ste_executor
docker build -t ros2_performance:ste_executor .
cd ../ros2_performance_static_executor
docker build -t ros2_performance:static_executor .
cd ../ros2_performance_let_executor
docker build -t ros2_performance:let_executor .
```

3. Run the compose file
```
cd ../compose/0
docker-compose up
```
4. Inspect the results in a new terminal (ctrl+alt+t)
```
docker stats --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.PIDs}}"
```

## How to use
Replace your rclcpp folder with this version (Make sure you rebuild!).
You can then use the static executor by using:
```
rclcpp::executors::StaticExecutor exec;
```
in source code instead of using the default:
```
rclcpp::executors::SingleThreadedExecutor exec;
```
no other changes to the source code are required.
You can not use the StaticExecutor with rclcpp::spin(node), in this case the default SingleThreadedExecutor will be used.
You have to explicitly create a static executor as follows:

```
rclcpp::executors::StaticExecutor exec;
auto node = std::make_shared<rclcpp::Node>("node_");
...
do other stuff
...
exec.add_node(node);
exec.spin();
...
rclcpp::shutdown();
return 0;
```

## Assumptions
The static executor makes the following assumptions:
1. The system does not change during runtime. This means that all nodes, callbackgroups, timers, subscriptions etc. are created before .spin() is called.
2. Happy flow. Since this is a proof of concept not much has been added yet in the form of checks and catches.

## Current functionality
The static executor has been tested with subscribers and timers. The other features such as clients, services and waitables are still being implemented and tested and may not function as expected.

## Inner workings of the SingleThreadedExecutor
During initialization handles to nodes, callbackgroups, timers, subscriptions etc. are created in RCL and RMW.
The SingleThreadedExecutor works as follows:

**"Init:"**

1. The executor finds nothing to execute
2. The executor performs collect_entities (gets handles from RCL)
3. The executor creates a wait_set using these handles
4. The executor communicates with RMW -> DDS layer to see what callbacks are ready to execute (put NULL if not ready in the wait_set)
5. The NULL handles are removed from the wait_set -> a wait_set containing handles corresponding to executables that need to be executed is left

**Loop:**

6. The executor looks for the next thing to execute in the following order: timers, subscriptions, services, clients, waitables
7. The executor walks through a tree of weak_ptrs to nodes which contain callbackgroups that contain timers, subscriptions etc.
8. The executor checks if the handle inside the node inside the callbackgroup inside the timer corresponds to a handle in the wait_set
9. If a handle is found that is in the wait_set the corresponding callback is executed and the callbackgroup is updated.
10. As long as there are still things to execute repeat 6 till 9, if nothing is left to execute go to 1

This process is visualized in the following flowchart:
![Alt text](/images/STE_flowchart.png?raw=true "STE flowchart")

## Changes in the StaticExecutor
The StaticExecutor works as follows:

**Init:**

1. The executor creates a struct with all executables with the same index as the handles in the wait_set by walking the tree of weak_ptrs ***ONCE***
2. The executor performs collect_entities (gets handles from RCL) ***ONCE***

**Loop:**

3. The executor adds RCL handles to the wait_set
4. The executor communicates with RMW -> DDS layer to see what callbacks are ready to execute (put NULL if not ready in the wait_set)
5. The executor walks over the wait_set, if it finds a NULL nothing happens, if a handle is found the executable is executed at the same index in the executables struct
6. Go to 3

This process is visualized in the following flowchart:
![Alt text](/images/StaticExecutor_flowchart.png?raw=true "STE flowchart")

repository: nobleo/rclcpp-static-executor

repo_name: nobleo/rclcpp-static-executor


text:
# Rust Webpack ESLint React Bootstrap Typescript Sass Template

Template to generate a React Web application, including React Bootstrap, styled with Sass, typed by
Typescript, checked with ESLint, with Rust-generated WebAssembly and Webpack, all without publishing
your wasm to NPM.

Forked from and based on [zephyo/Rust-Webpack-React-Sass-Template](https://github.com/zephyo/Rust-Webpack-React-Sass-Template),
which in turn was forked from and based on [rustwasm/rust-webpack-template](https://github.com/rustwasm/rust-webpack-template).

Differences from zephyo's are that this template comes with dependence on ESLint and the Typescript
plugin, using the "recommended" ESLint, Typescript and React configurations to validate the
React TSX files in `js/react`. Warnings will be presented, and errors will cause build failures.
Errors include implicit *any* types, so `js/index.d.ts` needs to contain a declaration for a
`Wasm` type, bundling the compiled and exported Wasm function that you intend to use in your
React app, which the `Root` component property parameter must be declared as having.

```js
// in js/index.d.ts
type Wasm = {
    hello: (string) => string,
};

// in js/react/Root.tsx
export default function Root(props: { wasm: Wasm }): Element { // ...
```

---

## 🚴 Using This Template

1. Clone or fork this template
2. `cd template`
3. `yarn install`
4. `yarn start`

For more information and tutorials, read the [README.md](https://github.com/rustwasm/rust-webpack-template) at the original repo.

---

## 🚵 Usage Details

### How to install

```sh
yarn install
```

### How to run in debug mode

```sh
# Builds the project and opens it in a new browser tab. Auto-reloads when the project changes.
yarn start
```

### How to build in release mode

```sh
# Builds the project and places it into the `dist` folder.
yarn run build
```

### How to run unit tests

```sh
# Runs tests in Firefox
yarn test -- --firefox

# Runs tests in Chrome
yarn test -- --chrome

# Runs tests in Safari
yarn test -- --safari
```

### What does each file do?

- `Cargo.toml`
  contains the standard Rust metadata. You put your Rust dependencies in here. You must change this
  file with your details (name, description, version, authors, categories)
- `package.json`
  contains the standard yarn metadata. You put your JavaScript dependencies in here. You must change
  this file with your details (author, name, version)
- `webpack.config.js`
  contains the Webpack configuration. You shouldn't need to change this, unless you have very
  special needs.
- The `js` folder contains your JavaScript code (`index.js` is used to hook everything into Webpack, you don't need to change it).
- The `src` folder contains your Rust code.
- The `static` folder contains any files that you want copied as-is into the final build. It contains an `index.html` file which loads the `index.js` file.
- The `tests` folder contains your Rust unit tests.


text:
---
layout: post
title: Completing the UBC Master of Data Science Program (with Survival Tips)
date: 2019-07-06 11:35:41 +0000
permalink: /mds-grad/
tags: post
---

Ten months ago, I quit my job and embarked on an adventure. That adventure saw me don a backpack once again. Before you think I set off to the backcountry of Europe to recreate my own "eat pray love" moments and partake in deep soul-searching, I'll interject and say some soul-searching did happen but I was firmly planted in Vancouver (on the UBC campus, in fact) and I proudly donned a backpack...as a full-time student.

I started the [Master of Data Science program at UBC](https://masterdatascience.ubc.ca/) in September of last year. This adventure was no fanciful whim in the park, however, as it'd been something I had been planning for almost a year. Financially, professionally and even emotionally, it was a big decision for me to go back to school after working full-time for six years. It required preparation and self-reflection, but I knew it would be the right step for me. Fastforward ten months later, I've completed the program and live to tell the tale with no regrets.

![](assets/images/mds_yearend.jpg)
*The 2018-19 UBC MDS cohort*

Near the end of my studies, I did an interview with the program to talk about my experience in MDS. The questions in that interview got me thinking about main takeaways and tips I have that could be helpful to prospective students considering or about to start the program. In this blog post, I share some of my answers to questions in those areas. Hopefully, this might be useful for some of you out there!

**What have been the top benefits of the program?**

>1) Learning a range of highly relevant material that has been carefully designed and curated into one package, taught by professors who are experts in their field.
>
>2) Being in an immersive environment where you live and breathe data science everyday, surrounded by peers who are just as motivated as you are to learn.
>
>3) The capstone project at the end of the program offers a great opportunity to apply what was learned in the classroom to real business problems faced by companies today.

**Your Top 3 tips on succeeding in the program?**

>1)  The program is fast-paced and requires that you commit to staying on top of assignments. If you were a procrastinator in school, don't fall back to these procrastinating ways! Your future self will thank you.
>
>2) Talk to your peers and instructors if you don't understand something or get stuck. Don't suffer silently! Take advantage of the resources available, including the career-related events organized specifically by the program.
>
>3) When things get hectic, this often goes out the window but don't forget to take care of yourself - eat well, exercise and get some sleep. It's hard to understand what a neural network is when your own neural network is operating on coffee and no sleep.


text:
# Pirozynskiella costaricensis (Speg.) S. Hughes, 2007 SPECIES

#### Status
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 99(4): 633 (2007)

#### Original name
Dendryphion costaricense Speg., 1919

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone


text:
# RelativelyResizable
* `resize` should call all childrens' resizes
* `setRelativeSize` should call `relayout`

# RelativelyLocated
* 'relocate' should call all childrens' relocates

# RelativelyLayouted
* Should call 'relayout' in constructor
* Should call 'super.relayout'
* Should not change the size of self

# CanSizeSelf
* Should not set location of any elements
* Should call 'super.sizeSelf'

repository: NotLebedev/Course-Planer

repo_name: NotLebedev/Course-Planer


text:
# cuda-timelock
[![License](http://img.shields.io/badge/License-MIT-brightgreen.svg)](./LICENSE)
[![Build Status](http://spice.dancline.net:8080/buildStatus/icon?job=cuda-timelock%2Fmaster)](http://spice.dancline.net:8080/job/cuda-timelock/job/master/)
<!-- [![Build Status](http://spice.dancline.net:8080/job/cuda-timelock/job/master/badge/icon)](http://spice.dancline.net:8080/job/cuda-timelock/job/master/) -->

cuda-timelock is code to solve timelock puzzles in parallel, using a GPU.
While a GPU is not the best in terms of latency for each individual multiple precision operation, the goal is to increase throughput on traditional hardware.

## Requirements
 * [GMP](https://gmplib.org)
 * [CGBN](https://github.com/NVlabs/CGBN)
 * [Google Test Framework](https://github.com/google/googletest)
 * A graphics card

repository: Rjected/cuda-timelock

repo_name: Rjected/cuda-timelock


text:
## Getting Started

                        _|   |_                     _|   |_
                        | ... |_._._._._._._._._._._| ... |
                        | ||| |  o NATIONAL BANK o  | ||| |
                        | """ |  """    """    """  | """ |
                    ())  |[-|-]| [-|-]  [-|-]  [-|-] |[-|-]|  ())
                  (())) |     |---------------------|     | (()))
                  (())())| """ |  """    """    """  | """ |(())())
                  (()))()|[-|-]|  :::   .-"-.   :::  |[-|-]|(()))()
                  ()))(()|     | |~|~|  |_|_|  |~|~| |     |()))(()
                    ||  |_____|_|_|_|__|_|_|__|_|_|_|_____|  ||
                  ~ ~^^ @@@@@@@@@@@@@@/=======\@@@@@@@@@@@@@@ ^^~ ~
                      ^~^~                                ~^~^

THE ATM

    A program ran in IRB/PRY to print out a Clients balance

    Explore the docs »

    View Demo
    ·
    Report Bug
    ·
    Request Feature

To get a local copy up and running follow these simple steps.

## Table of Contents

* [About the Project](#about-the-project)
* [Installation](#installation)
* [Usage](#usage)
* [License](#license)
* [Contact](#contact)
* [Specification](#specification)

## About The Project

A project that creates a client who can deposit and withdraw money. The client can then using the (ATM class) call a print out to STDOUT of their statements.

The project has 100% test coverage.

### Installation

1. Clone the repo
```sh
git clone https://github.com/Walker-TW/Bank_Tech_Test
```
2. Install Gem dependencies
```sh
bundle install
```

## Usage

First navigate to the directory the files are kept in. Then enter IRB
```sh
irb
```
Then require the app file from the root
```sh
irb : 001 >require './lib/atm.rb'
```
Create a Client and then withdraw/deposit the money that you need
```sh
irb : 002 > x = Client.new
irb : 003 > x.deposit(300)
irb : 004 > x.withdraw(300)
```
Finally you can print out the statement by;
```sh
irb : 005 > x.print
To run tests please..
```sh
rspec
```
## License

Distributed under the MIT License. See `LICENSE` for more information.

## Specification

### Requirements

* You should be able to interact with your code via a REPL like IRB or the JavaScript console. (You don't need to implement a command line interface that takes input from STDIN.)

* Deposits, withdrawal.

* Account statement (date, amount, balance) printing.

* Data can be kept in memory (it doesn't need to be stored to a database or anything).

### Acceptance criteria

**Given** a client makes a deposit of 1000 on 10-01-2012

**And** a deposit of 2000 on 13-01-2012

**And** a withdrawal of 500 on 14-01-2012

**When** she prints her bank statement

**Then** she would see

```
date || credit || debit || balance
14/01/2012 || || 500.00 || 2500.00
13/01/2012 || 2000.00 || || 3000.00
10/01/2012 || 1000.00 || || 1000.00
```

gha_language: Ruby


text:
# InferIDE
This project integrates the static analyzer [Facebook Infer](https://github.com/facebook/infer) into IDEs and editors with the [MagpieBridge](https://github.com/MagpieBridge/MagpieBridge) framework.
InferIDE executes infer in the background and displays analysis results directly in IDEs which support the Language Server Protocol.
Currently, only analyzing Java Projects is supported. For VS Code user, simply install [inferide](https://marketplace.visualstudio.com/items?itemName=LinghuiLuo.inferide) from the VS Code Marktplace.
![infer.gif](https://github.com/MagpieBridge/InferIDE/blob/master/doc/infer.gif)
**Figure 1: Infer warnings in VS Code**
# Usage
## Execution environment
* Make sure java 8 is installed on your machine and it is the default java runtime. This is important, since inferIDE uses MagpieBridge and other libraries which are written java 8. Using higher java version might lead to Exceptions.

## Install infer
* MacOS `brew install infer`
* Linux
  - see [infer documentation](https://fbinfer.com/docs/getting-started/) for the latest version.
  - At time of this writing you can use the following command to install version 0.17.0:
  ```bash
  VERSION=0.17.0; \
  curl -sSL "https://github.com/facebook/infer/releases/download/v$VERSION/infer-linux64-v$VERSION.tar.xz" \
  | sudo tar -C /opt -xJ && \
  ln -s "/opt/infer-linux64-v$VERSION/bin/infer" /usr/local/bin/infer
  ```
* Windows
  - Infer does not run natively on windows, but you can use [docker](https://docs.docker.com/docker-for-windows/install/)
* Docker
  - If Docker is installed and infer is not found on the system, InferIDE will use docker to start a container that has infer installed
  - By default, InferIDE will use the docker image [jonasmanuel/inferdocker](https://hub.docker.com/r/jonasmanuel/inferdocker) from dockerhub. It is built from the [dockerfile](inferdocker/Dockerfile) in this repository
  - If you want to use your own image you can supply the image using the command line option -i <dockerImage>
  - if the image is not yet installed on your system, docker will pull it on the first run
    - otherwise you can install it beforehand using `docker pull jonasmanuel/inferdocker`

## Use InferIDE in VS Code
Simply install [inferide](https://marketplace.visualstudio.com/items?itemName=LinghuiLuo.inferide) from the VS Code Marktplace or the latest [InferIDE VS code extension](https://github.com/MagpieBridge/InferIDE/releases/download/0.0.1/inferide-0.0.1.vsix) from the release page.
## Use InferIDE in the online editor --- GitPod
Configure `.gitpod.yml` for your project as in [this file](https://github.com/MagpieBridge/MagpieBridge/blob/develop/.gitpod.yml
), namely
```
image: jonasmanuel/inferdocker
vscode:
  extensions:
    - LinghuiLuo.inferide@0.0.1:reNHu3/GfefVx26yvbo/sg==
```
![gitpod](https://github.com/MagpieBridge/InferIDE/blob/master/doc/gitpod.gif)
**Figure 2: Infer warnings in Gitpod**

## Use InferIDE in Eclipse, IntelliJ/Android Studio, Sublime Text, Vim, Emacs
- Download the [inferIDE jar file](https://github.com/MagpieBridge/InferIDE/releases/download/0.0.1/inferIDE-0.0.1.jar) from the release page.
- Use the command `java -jar inferIDE-0.0.1.jar -a 5` or simply `java -jar inferIDE-0.0.1.jar` to configure the language server for Java in your desired IDE. Details are explained in [this tuturial](https://github.com/MagpieBridge/MagpieBridge/wiki/Tutorial-11.-Configure-different-IDEs-to-use-your-MagpieBridge-based-server) for all listed IDE and editors. InferIDE supports the following options:
```
 -a,--auto <arg>          enables auto mode and sets the timeout in
                          minutes for starting the automatic tool analysis
                          default timeout is 5
 -i,--dockerImage <arg>   dockerImage to use when running infer in docker
                          default is `jonasmanuel/inferdocker`
 -p,--port <arg>          sets the port for socket mode, standard port is
                          5007
 -s,--socket              run in socket mode, standard port is 5007
 ```
For editors like sublime, make sure you open the root path of your testing Java project at first, then any Java source file. This way the editors can notify InferIDE the project root path and execute infer from there.
![eclipse](https://github.com/MagpieBridge/InferIDE/blob/master/doc/eclipse.gif)
**Figure 3: Infer warnings in Eclipse**
![intellij](https://github.com/MagpieBridge/InferIDE/blob/master/doc/intellij.gif)
**Figure 4: Infer warnings in IntelliJ**

## When is infer running?
These are two ways how infer can be triggered by InferIDE:
- Fully automated (default): The default way is fully based on user interactions in the IDE. Infer will be triggered when the user opens a source file for the first time in a project. Moreover, InferIDE detects if the user is idle in the IDE (not typing for a given amout of time, e.g. 5 minutes) and triggers infer.  The InferIDE command used is `java -jar inferIDE-0.0.1.jar -a 5`
- User-controlled: InferIDE displays a HTML page (see screenshot below) in your web browser which allows you configure commands for infer to run and a click button to trigger infer. The InferIDE command used is `java -jar inferIDE-0.0.1.jar`
Default build-in commands are :
- Maven Project:
  - `infer run --reactive -- mvn clean compile` (first run)
  - `infer run --reactive -- mvn compile`

- Gradle Project:
  - `infer run --reactive -- ./gradlew clean build` (first run)
  - `infer run --reactive -- ./gradlew build`

 <img src="https://github.com/MagpieBridge/InferIDE/blob/master/doc/htmlpage.png" width="600">

## How to build InferIDE by yourself?
- Make sure you have set up your personal access token for GitHub package by following [these instructions](https://github.com/MagpieBridge/MagpieBridge/wiki/Tutorial-3.-How-To-Install-a-GitHub-Maven-Package), since MagpieBridge is deployed as GitHub Package.
- Use maven to build, simply `mvn install`
- For VS Code Extension, after build navigate to the directory vscode, execute the following commands:
```
        - npm install #(if the first time)
        - npm install -g vsce #(if the first time)
        - vsce package #(this will create vscode extension under vscode directory)
 ```

## Get Involved
- Pull requests are welcome!
- Submit github issues for any feature enhancements, bugs or documentation problems

## Contact
✉ linghui[at]outlook.de

repository: RSMuthu/InferIDE

repo_name: RSMuthu/InferIDE


text:
---
layout: post
title: SpaDES as a musical conductor
author: Eliot McIntire
date: March 9, 2016
tags: [SpaDES, modules, conductor]
comments: true
---

[What is SpaDES?](https://www.dropbox.com/s/dykatrdiewhlahu/LandWeb%20-%20SpaDES%20presentation%20-%20Nov%2017%2C%202015.pdf?dl=1) Powerful tools sometimes don't lead to easy explanations of how they work. I recently got a room full of foresters, government researchers and policy people to sing some nursery rhymes to help explain it. [See the talk here.](https://www.dropbox.com/s/dykatrdiewhlahu/LandWeb%20-%20SpaDES%20presentation%20-%20Nov%2017%2C%202015.pdf?dl=1)

branch_name: refs/heads/gh-pages


text:
# CourseEnrollmentPortal-JavaRMI

-->Run YP2Server.java
It creates a RMI Registry at port 1099(you can specify your own Registered port number 1024-49151).
Implements the Remote Interface

-->Run YP2Service.java
This is the interface implementation which extends UnicastRemoteObject

-->Run YP2Client.java(Run it on different compputer)
Enter only valid username and password.
Then Enter 1 or 2 ( 1 for enrollment of course and 2 for dropping the course)
If the user selects 1 he will be displayed with the courses left for the enrollment.
If the user selects 2 he will be displayed with the courses he already enrolled.

If the capacity of the course exceeds 5 then the YP2Service removes the course object from the Registry and
creates a new object for the same course


text:
---
title: "ALB Ingress Controller"
weight: 10
---

## Creating an Application Load Balancer to connect to the AIS Helm chart XNAT Implementation

We will be following this AWS Guide:

https://docs.aws.amazon.com/eks/latest/userguide/alb-ingress.html

{{% alert title="Before we begin" %}}
One thing that you need to know when we want to create new ALB from EKS is service spec type can only support LoadBalancer and NodePort. It won't support `ClusterIP`.
{{% /alert %}}

The Charts Repo has the service defined as `ClusterIP` so some changes need to be made to make this work. We will get to that later after we have created the ALB and policies.

In this document we create a Cluster called xnat in ap-southeast-2. Please update these details for your environment.

Create an IAM OIDC provider and associate with cluster:
```bash
eksctl utils associate-iam-oidc-provider --region ap-southeast-2 --cluster xnat --approve
```

Download the IAM Policy:
```bash
curl -o iam-policy.json https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/main/docs/install/iam_policy.json
```

Create the IAM policy and take a note of the ARN:
```bash
aws iam create-policy --policy-name AWSLoadBalancerControllerIAMPolicy --policy-document file://iam-policy.json
```

Create the service account using ARN from the previous command (substitute your ARN for the XXX):
```bash
eksctl create iamserviceaccount --cluster=xnat --namespace=kube-system --name=aws-load-balancer-controller --attach-policy-arn=arn:aws:iam::XXXXXXXXX:policy/AWSLoadBalancerControllerIAMPolicy --override-existing-serviceaccounts --approve
```

Install `TargetGroupBinding`:
```bash
kubectl apply -k "github.com/aws/eks-charts/stable/aws-load-balancer-controller//crds?ref=master"
```

Download the EKS Helm Chart and update repo information:
```
helm repo add eks https://aws.github.io/eks-charts
helm repo update
```

Install the AWS Load Balancer Controller:
```bash
helm upgrade -i aws-load-balancer-controller eks/aws-load-balancer-controller --set clusterName=xnat --set serviceAccount.create=false --set serviceAccount.name=aws-load-balancer-controller -n kube-system
```

Confirm it is installed:
```bash
kubectl get deployment -n kube-system aws-load-balancer-controller
```

You should see - `READY 1/1` if it is installed properly

In order to apply this to the XNAT Charts Helm template update the `charts/xnat/values.yaml` file to remove the Nginx ingress parts and add the ALB ingress parts.

Added to values file:
```yaml
      kubernetes.io/ingress.class: alb
      alb.ingress.kubernetes.io/scheme: internet-facing
      alb.ingress.kubernetes.io/group.name: xnat
      alb.ingress.kubernetes.io/target-type: ip
```

{{% alert %}}
NB. Although you can specify ip or instance for the target-type, you need to specify ip or autoscaling won't function correctly. This is because stickiness isn't honoured for target-type instance so you have the known issue where XNAT database thinks you are logged in but instance / pod knows you are not and then it logs you out again.
{{% /alert %}}

For more ALB annotations / options, please see article at the bottom of the page.

Commented out / removed:
```yaml
      kubernetes.io/ingress.class: "nginx"
      kubernetes.io/tls-acme: "true"
      nginx.ingress.kubernetes.io/whitelist-source-range: "<IP_ADDRESS>/16 <IP_ADDRESS>/8"
      nginx.ingress.kubernetes.io/proxy-connect-timeout: "150"
      nginx.ingress.kubernetes.io/proxy-send-timeout: "100"
      nginx.ingress.kubernetes.io/proxy-read-timeout: "100"
      nginx.ingress.kubernetes.io/proxy-buffers-number: "4"
      nginx.ingress.kubernetes.io/proxy-buffer-size: "32k"
```

As pointed out `ClusterIP` as service type does not work with ALB. So you will have to make some further changes to `charts/xnat/charts/xnat-web/values.yaml`:

Change:
```yaml
service:
  type: ClusterIP
  port: 80
```
to:
```yaml
service:
  type: NodePort
  port: 80
```

In `xnat/charts/xnat-web/templates/service.yaml` remove the line:

```yaml
clusterIP: None
```

Then create the Helm chart with the usual command (after building dependencies - just follow README.md). If you are updating an existing xnat installation it will fail so you will need to create a new application.

```bash
helm upgrade xnat . -nxnat
```

It should now create a Target Group and Application Load Balancer in AWS EC2 Services. I had to make a further change to get this to work.

On the Target Group I had to change health check code from **`200`** to **`302`** to get a healthy instance because it redirects.

You can fix this by adding the following line to values file:
```yaml
      # Specify Health Checks
      alb.ingress.kubernetes.io/healthcheck-path: "/"
      alb.ingress.kubernetes.io/success-codes: "302"
```
Troubleshooting and make sure ALB is created:
```bash
watch kubectl -n kube-system get all
```

Find out controller name in pod. In this case - `pod/aws-load-balancer-controller-98f66dcb8-zkz8k`

Make sure all are up.

Check logs:
```bash
kubectl logs -n kube-system aws-load-balancer-controller-98f66dcb8-zkz8k
```

When updating ALB is often doesn't update properly so you will need to delete and recreate the ALB:
```bash
kubectl delete deployment -n kube-system aws-load-balancer-controller
helm upgrade -i aws-load-balancer-controller eks/aws-load-balancer-controller --set clusterName=xnat --set serviceAccount.create=false --set serviceAccount.name=aws-load-balancer-controller -n kube-system
```

Change the stickiness of the Load Balancer:
It is important to set a stickiness time on the load balancer or you can get an issue where the Database thinks you have logged in but the pod you connect to knows you haven’t so you can’t login. Setting stickiness reasonably high – say 30 minutes, can get round this.
```yaml
alb.ingress.kubernetes.io/target-group-attributes: stickiness.enabled=true,stickiness.lb_cookie.duration_seconds=1800
```

Change the Load Balancing Algorithm:
```yaml
alb.ingress.kubernetes.io/target-group-attributes: load_balancing.algorithm.type=least_outstanding_requests
```

Increase the timeout to 5 minutes from 1. When using the Compressed Image Uploader you can sometimes get a 504 Gateway timeout error message. This will fix that issue.
You can read more about it here:
https://aws.amazon.com/premiumsupport/knowledge-center/eks-http-504-errors/

```yaml
alb.ingress.kubernetes.io/load-balancer-attributes: "idle_timeout.timeout_seconds=300"
```

## Add SSL encryption to your Application Load Balancer

Firstly, you need to add an SSL certificate to your ALB annotations. Kubernetes has a built in module: Cert Manager, to deal with cross clouds / infrastructure.

https://cert-manager.io/docs/installation/kubernetes/

However, in this case, AWS has a built in Certificate Manager that creates and a renews SSL certificates for free so we will be using this technology.

You can read more about it here:

https://aws.amazon.com/certificate-manager/getting-started/#:~:text=To%20get%20started%20with%20ACM,certificate%20from%20your%20Private%20CA.

This assumes you have a valid certificate created through AWS Certificate Manager and you know the ARN.

These are additional annotations to add to values file and explanations above:

Listen on port 80 and 443:
```yaml
      alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}, {"HTTPS":443}]'
```

Specify the ARN of your SSL certificate from AWS Certificate Manager (change for your actual ARN):
```yaml
      alb.ingress.kubernetes.io/certificate-arn: "arn:aws:acm:XXXXXXX:certificate/XXXXXX"
```

Specify AWS SSL Policy:
```yaml
      alb.ingress.kubernetes.io/ssl-policy: "ELBSecurityPolicy-TLS-1-2-Ext-2018-06"
```

For more details see here of SSL policy options:

https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html

Finally, for this to successfully work you need to change the host path to allow any path or the Tomcat URL will be sent to a 404 by the Load Balancer. Put a wildcard in the paths to allow any eventual URL (starting with xnat.example.com in this case):

```yaml
    hosts:
      - host: xnat.example.com
        paths: [ "/*" ]
```

### Redirect HTTP to HTTPS:

This does not work on Kubernetes 1.19 or above as the “use-annotation” command does not work. There is seemingly no documentation on the required annotations to make this work.

Add the following annotation to your values file below the ports to listen on (see above):

```yaml
     alb.ingress.kubernetes.io/actions.ssl-redirect: '{"Type": "redirect", "RedirectConfig": {"Protocol": "HTTPS", "Port": "443", "StatusCode": "HTTP_301"}}'
```

You must then update the Rules section of `ingress.yaml` found within the `releases/xnat/charts/xnat-web/templates` directory to look like this when using Ingress apiVersion of networking.k8s.io/v1beta1 on Kuberbetes version prior to v1.22:

```yaml
  rules:
    {{- range .Values.ingress.hosts }}
    - host: {{ .host | quote }}
      http:
        paths:
          {{- range .paths }}
          - path: {{ .path }}
            backend:
              serviceName: {{ $fullName }}
              servicePort: {{ $svcPort }}
          {{- end }}
    {{- end }}

```

For Ingress apiVersion of networking.k8s.io/v1 on Kubernetes version >= v1.22:

```yaml
  rules:
    {{- range .Values.ingress.hosts }}
    - host: {{ .host | quote }}
      http:
        paths:
          {{- range .paths }}
            backend:
              service:
                name: {{ $fullName }}
                port:
                  number: {{ $svcPort }}
          {{- end }}
    {{- end }}

```

This will redirect HTTP to HTTPS on Kubernetes 1.18 and below.

Full `values.yaml` file ingress section:

```yaml
  ingress:
    enabled: true
    annotations:
      kubernetes.io/ingress.class: alb
      alb.ingress.kubernetes.io/scheme: internet-facing
      alb.ingress.kubernetes.io/target-type: ip
      alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}, {"HTTPS":443}]'
      alb.ingress.kubernetes.io/actions.ssl-redirect: '{"Type": "redirect", "RedirectConfig": {"Protocol": "HTTPS", "Port": "443", "StatusCode": "HTTP_301"}}'
      alb.ingress.kubernetes.io/healthcheck-path: "/"
      alb.ingress.kubernetes.io/success-codes: "302"
      alb.ingress.kubernetes.io/certificate-arn: "arn:aws:acm:XXXXXXX:certificate/XXXXXX"
      alb.ingress.kubernetes.io/ssl-policy: "ELBSecurityPolicy-TLS-1-2-Ext-2018-06"
      alb.ingress.kubernetes.io/target-group-attributes: "stickiness.enabled=true,stickiness.lb_cookie.duration_seconds=1800,load_balancing.algorithm.type=least_outstanding_requests"
      alb.ingress.kubernetes.io/load-balancer-attributes: "idle_timeout.timeout_seconds=300"
```

Further Reading:

* https://medium.com/devops-dudes/running-the-latest-aws-load-balancer-controller-in-your-aws-eks-cluster-9d59cdc1db98

Troubleshooting EKS Load Balancers:

* https://aws.amazon.com/premiumsupport/knowledge-center/eks-load-balancers-troubleshooting/
* https://medium.com/@ManagedKube/kubernetes-troubleshooting-ingress-and-services-traffic-flows-547ea867b120

ALB annotations:

* https://kubernetes-sigs.github.io/aws-load-balancer-controller/guide/ingress/annotations/

repository: Australian-Imaging-Service/charts

gha_language: Smarty

repo_name: Australian-Imaging-Service/charts


text:
# DataExtractor

This is the second phase of OPVDB project.

This DataExtractor is built on ChemDataExtractor (CDE) version 1.3.0 by Matt Swain and paper-parser (pp) by Christian Chang and contributors.

The challenge faced by data mining in research and academia is the application of a pipeline in certain field of study and output a systematic database that can feed back and benefit the research.

Both CDE and pp provide excellent platforms of allowing users to customize items by themselves and perform data mining. pp stops at extracting information, and we believe we can perform the information extraction in more areas and build a organized and systematic database based on extracted information. Thus this project focuses on practical use of a data mining pipeline, including literature collection, data parsing, data exhibition and database creation.

## Description

The overall workflow of this project should follow this graph:
![workflow](project_xmind.png)

1. Data Collection

    Data Collection in this project focuses on scraping academic papers from major publishers, such as Elsvier, Springer, arXiv-eprints, etc. Using the API they provide to export sufficient number of literature to perform information extraction by using NLP model.

    [Scraper](https://github.com/Zhangjt9317/Scraper.git)

2. Information Extraction and Database

    We can focus on more fields of study, including peroskite solar cell, which is already done by pp, organic photovoltaic materials, which can be another topic to study, thermosetting resins, and thermal properties of materials. Basically any field that is experiment-heavy can benefit from this project and the database we created.

    [DataExtractor](https://github.com/Zhangjt9317/DataExtractor.git)

3. Exhibition

    After performing information extraction, the processed data can be further cleaned and organized, and then a Django-based platform can be built to exhibit researchers information of materials reported on literature. Given a good example, refer to this paper: [dye-sensitized solar cell database](https://www.ncbi.nlm.nih.gov/pubmed/29616364)

    [OPVDB](https://github.com/Zhangjt9317/OPVDB.git)

## Installation

In order to set up the necessary environment:

1. create an environment for `DataExtractor` with the help of [conda],
   ```
   conda env create -f environment.yaml
   ```
2. activate the new environment with
   ```
   conda activate DataExtractor
   ```
3. install `DataExtractor` with:
   ```
   python setup.py install # or `develop`
   ```

Optional and needed only once after `git clone`:

4. install several [pre-commit] git hooks with:
   ```
   pre-commit install
   ```
   and checkout the configuration under `.pre-commit-config.yaml`.
   The `-n, --no-verify` flag of `git commit` can be used to deactivate pre-commit hooks temporarily.

5. install [nbstripout] git hooks to remove the output cells of committed notebooks with:
   ```
   nbstripout --install --attributes notebooks/.gitattributes
   ```
   This is useful to avoid large diffs due to plots in your notebooks.
   A simple `nbstripout --uninstall` will revert these changes.

Then take a look into the `scripts` and `notebooks` folders.

## Dependency Management & Reproducibility

1. Always keep your abstract (unpinned) dependencies updated in `environment.yaml` and eventually
   in `setup.cfg` if you want to ship and install your package via `pip` later on.
2. Create concrete dependencies as `environment.lock.yaml` for the exact reproduction of your
   environment with:
   ```
   conda env export -n DataExtractor -f environment.lock.yaml
   ```
   For multi-OS development, consider using `--no-builds` during the export.
3. Update your current environment with respect to a new `environment.lock.yaml` using:
   ```
   conda env update -f environment.lock.yaml --prune
   ```
## Project Organization

```
├── AUTHORS.rst             <- List of developers and maintainers.
├── CHANGELOG.rst           <- Changelog to keep track of new features and fixes.
├── LICENSE.txt             <- License as chosen on the command-line.
├── README.md               <- The top-level README for developers.
├── configs                 <- Directory for configurations of model & application.
├── data
├── docs                    <- Directory for Sphinx documentation in rst or md.
├── environment.yaml        <- The conda environment file for reproducibility.
├── models                  <- Trained and serialized models, model predictions,
│                              or model summaries.
├── notebooks               <- Jupyter notebooks. Naming convention is a number (for
│                              ordering), the creator's initials and a description,
│                              e.g. `1.0-fw-initial-data-exploration`.
├── references              <- Data dictionaries, manuals, and all other materials.
├── reports                 <- Generated analysis as HTML, PDF, LaTeX, etc.
│   └── figures             <- Generated plots and figures for reports.
├── scripts                 <- Analysis and production scripts which import the
│                              actual PYTHON_PKG, e.g. train_model.
├── setup.cfg               <- Declarative configuration of your project.
├── setup.py                <- Make this project pip installable with `pip install -e`
│                              or `python setup.py develop`.
├── src
│   └── dataextractor       <- Actual Python package where the main functionality goes.
├── tests                   <- Unit tests which can be run with `py.test` or
│                              `python setup.py test`.
├── .coveragerc             <- Configuration for coverage reports of unit tests.
├── .isort.cfg              <- Configuration for git hook that sorts imports.
└── .pre-commit-config.yaml <- Configuration of pre-commit git hooks.
```

## Note

This project has been set up using PyScaffold 3.2.1. For details and usage
information on PyScaffold see https://pyscaffold.org/.

[conda]: https://docs.conda.io/
[pre-commit]: https://pre-commit.com/
[Jupyter]: https://jupyter.org/
[nbstripout]: https://github.com/kynan/nbstripout
[Google style]: http://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings

# Contributors
Jingtian Zhang
Edwin Jiang
Luna Huang
Fumio Ohuchi

# Acknowledgements

Great thanks to people who provide resources for this project and contributors who contribute to it. Details refer to the list of contributors in this publication: [iamthearticle]


text:
# Photometric_Consistency-Estimator
OpenCV 3.1 project. Count photometric consistency of specified set of images. Project created in Visual Studio 2015. Configuration taken from http://dogfeatherdesign.com/opencv-3-0-microsoft-visual-studio-2015-cmake-and-c/ (very important!).

#HOWTO
* Create folder 'Images' and 'Results'
* Copy all your images to 'Images' folder and create here 'Images.txt' file with list of your images in rows
* Create folder 'Results' in root directory
* Build and Run


text:
# ControllerServiceAPI

## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**type** | **String** | The fully qualified name of the service interface. |  [optional]
**bundle** | [**Bundle**](Bundle.md) | The details of the artifact that bundled this service interface. |  [optional]


text:
# WiiCam

Wii remote camera usage in embedded environment

Why? The Wii remote provides a low-cost camera with built in blob tracking of up to 4 points all over I2C, enabling easy motion tracking for an embedded system.

## Instructions

At it's most basic:

1. Extract camera from Wiimote
2. Solder into breakout board
3. Insert into standard Arduino board
4. Utilize included library to get point data
5. Make awesome tracking application. Track those IR LEDs!

### thx

Inspired by [Johnny Lee's](http://johnnylee.net/projects/wii/) Wii related projects utilizing the Wii remote IR camera for tracking applications.

repository: eric-yx-ma/wiicam

repo_name: eric-yx-ma/wiicam