text:
[Back to Main README](../README.md)

# Full GitHub Authorization with the `torii-provider`

This guide walks through the process of authenticating and authorizing an Ember app with
and for use against GitHub using `ember-simple-auth` and `torii` including a registered
GitHub application, an unauthenticated login route, an authenticated content route, a
token exchange service, and use of an authorizer to inject the token into
requests. We'll use the [ember-data-github](https://github.com/elwayman02/ember-data-github)
addon so we don't need to create our own GitHub models, serializers, and adapters.

The overall flow, concerns, and approach are the same for all OAuth2 explicit grant flow
mechanisms like Facebook, Google, etc. The differences could be as small as changing some
configuration and base classes. For GitHub specifically, the authentication flow works like this:

1. When the user clicks the login button, the Ember application contacts
   `https://github.com/login/oauth/authorize` with the app’s `client_id`.
   GitHub presents a new window asking the user to authorize access to their
   GitHub account from the app. The user grants this.
2. GitHub redirects back to the app with an `authorizationCode`. This is
   proof of authorization, but the app still doesn’t know _who_ the user is
   (so it cannot connect to a `User` model, for example).
3. The app sends the `authorizationCode` to a server maintained by the app's author,
   which in turn `POST`s the code to
   `https://github.com/login/oauth/access_token`. In development, this can be
   mocked. In production, it must be a separate server, about which more
   below.
4. GitHub responds to the `POST` with an `access_token`, which the
   server forwards to the app.
5. The app uses the `access_token` in an `Authorization: Bearer
   <access_token>` header request to, say, `https://api.github.com/user`,
   which returns the GitHub user’s user info, at which point it can be matched to the app's own `User` model.

You can find a sequence diagram for the full flow [here](./assets/esa-initial-flow.svg).

This guide assumes you know how to start an Ember app and are familiar with the various
files and concepts.

## Registering your app with GitHub

After logging in to GitHub, go to your [developer
settings](https://github.com/settings/developers) and, in the “OAuth Apps”
section, click on “New OAuth App.” Fill in the form much like in this image.
The first three fields can be filled out per your wishes, but take care with
the Authorization callback URL.

![Registering an OAuth Application with
GitHub](./assets/github-registering-oauth-application.png)

You will likely want to register different application keys for development
and production, as the authorization callback URL will be different in both
cases. For development, `http://localhost:4200/torii/redirect.html` is
sufficient. For production, it will be
`http://<your-great-app-domain>/torii/redirect.html`.

Once you register your application, you will have a chance to add an
application logo.  Most importantly, you will be given a client ID and a
client secret. _The client secret must be kept secret and should never be
included in the Ember application's source!_ You will use the client ID in
your web application and the client secret in your back end token exchange
service.

## Authenticating the Ember app

OAuth is officially an authorization protocol, but is commonly used also for
authentication when the initial authorization code is obtained over `https`. GitHub uses
the OAuth [authorization code grant type](https://tools.ietf.org/html/rfc6749#section-4.1),
which requires two steps. The first step uses your client ID to get a temporary
authorization code. The temporary authorization code acts as a single use bridge
to authorization. The second step takes that authorization code and sends it to
your token exchange service which combines it with your client secret to obtain
an authorization token. That token is effectively your unique password to use
the GitHub APIs as long as it is valid.

### Installing the addons

Install `ember-simple-auth` and `torii`.

```
ember install ember-simple-auth
ember install torii
```

Here, `ember-simple-auth` provides the underlying authentication layer, which
includes `session`, an [Ember
service](https://guides.emberjs.com/release/applications/services/) that
provides authentication persistence even when the server is restarted.
`torii` provides the abstraction needed to write the GitHub-specific
authorization provider.

### Configuration

The next step is to set up the configuration.  THIS IS THE EFFECTIVE RESULT.

var ENV = {
  ...

  torii: {
    sessionServiceName: 'session',
    providers: {
      'github-oauth2': {
        apiKey: 'YOUR_API_KEY',
        redirectUri: 'http://localhost:4200/torii/redirect.html',
        scope: 'repo user'
      }
    }
  }
};
```

`YOUR_API_KEY` is the client ID supplied when you registered your GitHub application.

However, this API key is probably specific to your development environment, as is the value given for `redirectUri`
above. This is fine while your app is in development, but as your application approaches production, you'll need to
break some of it out.

Additionally, it can be considered bad practice to distribute all of your API keys in your source code. Let's add a
little complexity and address this concern by using `ember-cli-dotenv` to put our key in an external file that will be
injected at build time. Install the package

```js
ember install ember-cli-dotenv
```

`ember-cli-dotenv` requires the preexistence of a configuration file before it will
install, so create the new file, `config/dotenv.js`:

```javascript
// config/dotenv.js
module.exports = function() {
  return {
    clientAllowedKeys: [
      "GITHUB_REDIRECT_URI",
      "GITHUB_CLIENT_ID",
      "AUTH_TOKEN_EXCHANGE_URL"
    ],
    failOnMissingKey: false
  };
};
```

and create a `.env` file in the root of your project like

```
GITHUB_CLIENT_ID=<your GitHub client id created above>
GITHUB_REDIRECT_URI=http://localhost:4200/torii/redirect.html
```

replacing `<YOUR_API_KEY>` with the client ID from your application registration. Add `/.env` to your `.gitignore` file
so it will not be committed.

Add the configuration for Torii to the `environment.js` like so:

```js
  var ENV = {
    ...

    torii: {
      sessionServiceName: "session",
      providers: {
        "github-oauth2": {
          scope: "repo user",
          apiKey: process.env.GITHUB_CLIENT_ID,
          redirectUri: process.env.GITHUB_REDIRECT_URI
        }
      }
    },
  };
```

### The Basic App

Let's give ourselves an app to secure. We'll keep it simple. We'll have a login route for authentication and use the
application index route to display the authenticated user's data, an operation that gives a 401 if you aren't
authenticated.

```
ember g route application
ember g controller application
ember g route index
ember g route login
```

Ember-cli will ask about overwriting app/templates/application.hbs. It's fine to do so.

Also, now is a good time to remove `ember-welcome-page` from your `package.json`.

Let's put some content in our templates. First, our `application.hbs` will give a friendly greeting and some useful
information so we know things are working as we proceed.

```handlebars
{{!-- app/templates/application.hbs --}}

My Ember Octane App

Secret API Key: {{this.config.apiKey}}

  {{#if this.session.isAuthenticated}}
    Authenticated

    <button {{on "click" this.logout}}>Log Out</button>
  {{else}}
    Unauthenticated
  {{/if}}

{{outlet}}
```

```js
// app/controllers/application.js

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import config from '../config/environment';

export default class ApplicationController extends Controller {
  @service session;
  config = config.torii.providers['github-oauth2'];
}
```

For the `index.hbs` let's put a placeholder until we're ready to fill in real data.

```handlebars
{{!-- app/templates/index.hbs --}}

Index Route

{{#if this.session.data.authenticated.authorizationCode}}

Authorization Code: {{this.session.data.authenticated.authorizationCode}}

{{/if}}
```

Finally, we'll put a placeholder in `login.hbs`. We'll give it behavior shortly.

```handlebars
{{!-- app/templates/login.hbs --}}

Login Route

<button>Log in to GitHub</button>
```

We can ignore the rest of the generated files for this step.

When you spin up the server again with `ember serve`, you should see, at
`http://localhost:4200`, something like this:

![Initial Ember Octane App page](./assets/initial-ember-octane-app-page.png)

### Adding Authentication

First, we'll designate the `index` route as an authenticated route using the
session service's
[requireAuthentication](http://ember-simple-auth.com/api/classes/SessionService.html#method_requireAuthentication)
method. This will make the route inaccessible until we finish the
authentication. It will automatically redirect you to the specified login
route, if you are not authenticated.

```js
// app/routes/index.js
import Route from '@ember/routing';
import { inject as service } from '@ember/service';

export default IndexRoute extends Route {
  @service session;

  beforeModel(transition) {
    this.get('session').requireAuthentication(transition, 'login');
  },
}
```

If you're still running the app when you save this, you will see it redirect to the `login` route.

We'll also designate the `login` route as available for unauthenticated access only by calling the session service's
[prohibitAuthentication](http://ember-simple-auth.com/api/classes/SessionService.html#method_prohibitAuthentication).
This will redirect you to the `index` route.

Next, we'll create and set up our torii authenticator to start.

```sh
ember g authenticator torii
```

```js
// app/authenticators/torii.js

import { inject as service } from '@ember/service';
import Torii from 'ember-simple-auth/authenticators/torii';

export default class ToriiAuthenticator extends Torii {
  @service torii;
}
```

We also need to define a Torii provider. Because Torii doesn't provide a generator, we need to create the `app/torii-providers`
directory ourselves and create the following `github.js` inside it.

```js
// app/torii-providers/github.js

import GitHubOAuth2 from 'torii/providers/github-oauth2';

export default class GithubToriiProvider extends GitHubOAuth2 {
  fetch(data) {
    return data;
  }
}
```

There's only one more piece in this step, connecting our "Log in" button to the authentication mechanism. First, add a
`login` controller with an action.

```
ember g controller login
```

```js
// app/controllers/login.js

import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';

export default class LoginController extends Controller {
  @service session;

  @action
  login() {
    this.session.authenticate('authenticator:torii', 'github');
  }
}
```

Finally, change your `login` template to send the action when the button is pressed.

```handlebars
{{!-- app/templates/login.hbs --}}

<button {{on "click" this.login}}>Log in to GitHub</button>
```

We've now established the mechanism to obtain an authorization code from GitHub. This doesn't authorize us fully to use
the GitHub APIs, although `ember-simple-auth` considers us authenticated at this point, but we can add some information
to our `application` template that at least verifies things work so far. Add the following line to your `application.hbs`
after the `API Key` line. When you attempt to login, you should see a popup asking your permission for the app to access
your account and it will show the authorization code. It will only ask your permission the first time. After that, the
popup will flash quickly unless you revoke the application's access through GitHub.

```handlebars
Authorization Code: {{session.data.authenticated.authorizationCode}}

```

### Logging Out

Before we finish the authentication, let's add the ability to log out. This will help us reset our application so we can
test it as we go.

First, we'll add a logout button to our `application` template right after the text "Authenticated". This seems a
reasonable place since it serves as our application's rudimentary menu bar and should only show when the user is
authenticated.

```handlebars
{{!-- add to app/templates/application.hbs --}}

    <button {{on "click" this.logout}}>Log Out</button>
```

Next, add the `logout` action to your `application` controller.

```js
// add to app/controllers/application.js

  @actions
  logout() {
    this.session.invalidate();
  }
```

Clicking the "Log Out" button will take you back to the login state.

### Obtaining an Access Token

The final step in the process is to exchange your authorization code for an API access token. This can only be done
securely through a back end service because it needs to know your client secret. Right now, our app looks like
it's authenticated, but it is not _authorized_ to use the GitHub APIs. Let's add `ember-fetch` and `ember-data-github` and make our
index page show some data about the currently logged in user.

```
ember install ember-fetch
ember install ember-data-github
```

If you still have your `ember serve` running, you will probably want to stop and restart it to make sure the new models
are loaded from the addon.

Next, we'll add a `model` hook to our `index` route to load the user data.

```js
// add to app/routes/index.js

  model() {
    return this.store.findRecord('github-user', '#');
  }
```

The `ember-data-github` addon uses "#" as a special ID value to indicate the current user.

While "Me" may have been truthful in the description of the current user, it doesn't require an API call to GitHub and
isn't very informative. Change the contents of your `index` template to show some model attributes.

```handlebars
{{!-- app/templates/index.hbs --}}

Login: {{this.model.login}}

Full Name: {{this.model.name}}
```

If you log in to GitHub through the app now with the console open, you will see that you are not fully authorized. The
page will be blank (we didn't do any real error handling) and the console will tell you you received a
`401 (Unauthorized)` for an API call to `https://api.github.com/user`. This particular API uses the identity associated
with the authorized user to return the profile for that user, which it can't do if you're not authorized. Now that we
have evidence that we're not truly authorized, let's fix it.

We need to have a token exchange service, a service that takes an authorization code and returns an access token. You
can implement this in any language and stack you want for writing APIs. This guide explains how to implement the service as
an Ember `http-mock` or using [Gatekeeper](prose/gatekeeper).

#### Using an `http-mock`

Because it's a `POST` request, we need to add the `body-parser` package to parse
the request body.

```
ember g http-mock token
npm install --save-dev body-parser
```

To keep our client secret secret, we'll add the following setting to the `.env` file.

```
GITHUB_CLIENT_SECRET=<YOUR CLIENT SECRET>
GITHUB_USER_AGENT=<YOUR APPLICATION NAME>
```

In production, you'll want to have these settings and your client ID deployed with your service. You may want to
change the key names in the `.env` file and the code depending on how you distinguish development from production.

We can now implement our back end token exchange service.

```js
// server/mocks/token.js

module.exports = function(app) {
  const express = require('express');
  const tokenRouter = express.Router();
  const https = require('https');

  tokenRouter.post('/', function(req, res) {
    const body = req.body;

    const payload = {
      'client_id': process.env.GITHUB_CLIENT_ID,
      'client_secret': process.env.GITHUB_CLIENT_SECRET,
      'code': body.authorizationCode
    };
    if (body.state) {
      payload.state = body.state;
    }

    const data = JSON.stringify(payload);

    const options = {
      hostname: 'github.com',
      port: 443,
      path: '/login/oauth/access_token',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(data),
        'Accept': 'application/json',
        'User-Agent': process.env.GITHUB_USER_AGENT
      }
    };

    const ghReq = https.request(options, (ghRes) => {
      let body = '';
      ghRes.setEncoding('utf8');
      ghRes.on('data', (chunk) => body += chunk);
      ghRes.on('end', () => {
        res.writeHead(200, {
          'Content-Type': 'application/json'
        });
        res.write(JSON.stringify(body));
        res.end();
      });
    });
    ghReq.on('error', (error) => {
      console.error(error);
      res.status(500).end();
    });
    ghReq.write(data);
    ghReq.end();
  });

  app.use('/api/token', require('body-parser').json());
  app.use('/api/token', tokenRouter);
};
```

It creates a payload out of the `authorizationCode` and optionally `state` sent to it as well as the `client_id` and
`client_secret` taken from your `.env`. It sends them to the `/login/oauth/access_token` endpoint,
takes GitHub's response and returns it verbatim. The resulting access token will be in an `access_token` property of
the JSON. We aren't going to run this through Ember Data, so the result does not need to be JSONAPI.

#### Using Gatekeeper

This aspect of the guide takes place outside of the context of your Ember app,
because GitHub will not permit token exchange to happen on a client-side
application. Luckily, spinning up a separate gatekeeper server is somewhat
straightforward, and there even is a Node application,
[Gatekeeper](prose/gatekeeper), designed to make the process even easier.

In short, the server must receive the authorization code your Ember app receives
from GitHub and forward it back to GitHub in a `POST` request, wait for a
response, and send it back to your Ember app.

Gatekeeper expects the authorization code to come at the end of a URL in the
format of `http://<gatekeeper-server>/authenticate/<authorization-code>`,
which is why we set the value of `AUTH_TOKEN_EXCHANGE_URL` to
`http://localhost:9999/authenticate` in the `.env` file. This is the URL we
will shortly be using.

##### Build the Gatekeeper Server

Outside of your Ember app’s directory, clone and prepare the Gatekeeper
server:

```sh
git clone https://github.com/prose/gatekeeper.git
cd gatekeeper
npm install
npm install dotenv
echo ".env" >> .gitignore
```

Now, as with the `.env` file in the Ember app, create a similar one in the
`gatekeeper` directory:

```sh
OAUTH_CLIENT_ID=<your GitHub client id created above>
OAUTH_CLIENT_SECRET=<your GitHub client secret created above>
```

Note that for the token exchange, you need both the client id _and_ the client
secret. These are the environment variable names Gatekeeper is expecting, so
do not change them. Finally, make the Gatekeeper server aware of the
environment variables by adding, at the very top of `index.js`:

```javascript
require("dotenv").config();
```

Start the Gatekeeper server with:

```sh
node index.js
```

The server should report to the console something like this:

```
Configuration
oauth_client_id: 5cb***
oauth_client_secret: 429***
oauth_host: github.com
oauth_port: 443
oauth_path: /login/oauth/access_token
oauth_method: POST
Gatekeeper, at your service: http://localhost:9999
```

The lines for the `oauth_client_id` and `oauth_client_secret` should look
similar to your client id and client secret. If they read `GIT***`, then the
environment variables did not catch. Make sure you added the `dotenv`
configuration line at the top of `index.js`.

#### Connecting the Torii authenticator

Our application will need to know the URL of the token exchange API. While this is not an established part of the Torii
configuration, that is a reasonable place to put it. Add `AUTH_TOKEN_EXCHANGE_URL=http://localhost:4200/api/token` to your
`.env` and the following to the development section of your `environment.js`. __Note that you should use `https` for the
token exchange service in production!__

```js
// change config/environment.js

  var ENV = {
    ...

    torii: {
      sessionServiceName: "session",
      providers: {
        "github-oauth2": {
          scope: "repo user",
          apiKey: process.env.GITHUB_CLIENT_ID,
          redirectUri: process.env.GITHUB_REDIRECT_URI,
          tokenExchangeUri = process.env.AUTH_TOKEN_EXCHANGE_URL
        }
      }
    },
  };
```

Now that we've set up a token exchange service, let's use it. Replace your `torii` authenticator with

```js
// app/authenticators/torii.js

import { inject as service } from '@ember/service';
import Torii from 'ember-simple-auth/authenticators/torii';
import config from '../config/environment';

export default class ToriiAuthenticator extends Torii {
  @service torii;

  async authenticate() {
    const tokenExchangeUri = config.torii.providers['github-oauth2'].tokenExchangeUri;
    let data = await super.authenticate(...arguments);
    const response = await fetch(tokenExchangeUri, {
      // Adding method type
      method: "POST",
      // no-cors, *cors, same-origin
      mode: 'cors',
      // Adding body or contents to send
      body: JSON.stringify({
        authorizationCode: data.authorizationCode
      }),
      // Adding headers to the request
      headers: {
        'Content-Type': 'application/json'
      }
    });

    return {
      access_token: JSON.parse(response).access_token,
      provider: data.provider
    };
  }
}
```

This makes a `POST` request to your service and gives the response back to Ember Simple Auth. Notice that it returns the `access_token`
and the `provider` but omits the `authorizationCode`. The authorization code is a one-time use token and is not valid
after being exchanged.

We're getting close now. We have an access token. We just need to use it.

### Using The Access Token

The trick now is to get the access token into the `Authorization` header for every HTTP request. If you look at GitHub's documentation,
they say you need to send your token with the HTTP header `Authentication: token OAUTH-TOKEN`. This can be done in an Ember Data adapter.
If GitHub is the only data source we need for the application or at least the one we want to consider primary, we can create an `application`
adapter. If we consider it the secondary data source, then we need to create an adapter per model. Because `ember-data-github` has several
per-model adapters, we'll create the `github-user` adapter to start us off.

```
ember g adapter github-user
```

```js
// app/adapters/github-user.js

import { computed } from '@ember/object';
import GitHubUserAdapter from 'ember-data-github/adapters/github-user';
import { inject as service } from '@ember/service';

export default class GithubUserAdapter extends GitHubUserAdapter {
  @service session;

  @computed("session.data.authenticated.access_token")
  get headers() {
    const headers = {};
    if (this.session.isAuthenticated) {
      headers.Authorization = `token ${
        this.session.data.authenticated.access_token
      }`;
    }

    return headers;
  }
}
```

This adapter injects an authorization header into the GitHub request now.

### Wrapping Up

So that's it! You should be able to log in to GitHub, see your avatar and some data about yourself, and log out.

The app certainly lacks polish. The UI is crude and, as we saw, there are opportunities for better error handling.

## Useful Links

In addition to the documentation and source code for `ember-simple-auth` and `torii`, the
following posts and projects were helpful in assembling the full story presented in this
guide.

* [simple-auth-torii-github-demo](https://github.com/srvance/simple-auth-torii-github-demo) is a repo created to follow
the steps of this guide. All elements of the guide except the token exchange service are contained here. The demo project uses pre-Octane Ember patterns.
* [@muziejus/ember-simple-auth-github-octane](http://github.com/muziejus/ember-simple-auth-github-octane) is another demo following the steps
in this guide but using Ember Octane patterns.
* [github-stars](https://github.com/hawkup/github-stars) has multiple implementations of the
same app to display your starred repos in various web app frameworks. The `emberjs`
directory contains the implementation for Ember.
* [GitHub Social Authentication with Ember Simple Auth and Torii](https://disjoint.ca/til/2016/03/21/github-social-authentication-with-ember-simple-auth-and-torii/)
addresses some very specific issues but has a helpful overall recipe to get things working.
* [Real-world Authentication with Ember Simple Auth](https://emberigniter.com/real-world-authentication-with-ember-simple-auth/)
adds `ember-simple-auth` to the application developed in its preceding post.
* The [GitHub OAuth Web Application Flow](https://developer.github.com/v3/oauth/#web-application-flow)
tells you what GitHub expects of your app.


text:
---
layout: single
title: Reviewing Pull Requests
sidebar:
  nav: community
---

{% include toc %}

# Review a Pull request

Anyone can review a documentation pull request (PR). Visit the [**Pull requests**](https://github.com/spinnaker/spinnaker.github.io/pulls) section in the Spinnaker website repository to see a list of all currently open pull requests.

Reviewing documentation pull requests is a great way to get started contributing to the Spinnaker community. It helps you to learn the code base and builds rapport with other contributors.

# Before you begin

Before reviewing documentation, do the following:

Read the [documentation style guide](/community/contributing/docs/docs-style-guide/) so that you can leave informed feedback.

1. Review the [code of conduct](https://github.com/spinnaker/spinnaker.github.io/blob/master/community/contributing/code-of-conduct.md) and ensure that you abide by it at all times.
2. Be polite, helpful, and considerate of others.
3. Comment on positive aspects of a PR, as well as changes.
4. Be empathetic and mindful of how your changes or review may be received.
5. Ask clarifying questions if something in a PR is unclear.
6. Assume positive intent.
7. If you are an experienced contributor, consider pairing with new contributors whose work requires extensive changes.
8. Be mindful of the needs of contributors that are neurodivergent or have a learning disability. Ask your fellow contributors how they work best and what communication style they prefer.

# Start the review process

1. Go to (<https://github.com/spinnaker/spinnaker.github.io/pulls>) to see a list of all current open PRs in the Spinnaker repository.

2. Filter the open PRs using one or all of the following labels:

  - Beginner friendly
  - Help wanted
  - Questions
  - no-lifecycle

  PRs have two states, one is **ready for review** and the other is a **draft Pull request**

  If a PR is classified as a [draft pull request](https://github.blog/2019-02-14-introducing-draft-pull-requests/), this means the contributor would like feedback on their PR throughout the review process, and that the PR is **not ready for review or merging**.

  Reviewers should encourage new contributors to make use of **draft PRs** when appropriate.

  If a PR is **ready for review**, reviewers should proceed to the next step in the review process.

  - Once you've found a PR to review, understand the change by:

    - Reading the PR description to learn why the PR was made, and read any linked issues attached to the PR
    - Reading comments left by other reviewers
    - Clicking the **Files changed** tab to see any files and lines changed

3. Go to the **Files changed** tab and begin your review

  - Click on the + symbol beside the line you want to comment on.
  - Fill in any comments you have about the line in question, and click either, **Add a single comment** (if you have only one comment to make on the PR) or **Start a review** (if you have multiple comments)
  - When you've finished reviewing the PR, click **Review changes** at the top of the page. Here, you can add a summary of your review (and leave some positive comments and thanks for the contributor!), approve the PR, comment or request changes as needed. New contributors should always choose **Comment**.

# Reviewing checklist

When reviewing a PR, use the following questions as a starting point:

- Are there any obvious errors in grammar or language?
- Is there a better way to phrase something?
- Are there words, phrases, or terms that should be replaced with a non-discriminatory alternative?
- Does the word choice, punctuation, and capitalization follow the [style guide](/community/contributing/docs/docs-style-guide/)?
- Are there long sentences which could be shorter or made less complex?
- Are there long paragraphs which would work better as a bulleted list or table?

# Other

For small issues with a PR, like typos or whitespace, prefix your comments with "nit:". This lets the author know the issue is non-critical.

license: MIT

branch_name: refs/heads/master

extension: md

gha_license_id: MIT

license_type: permissive


text:
# DevCAr

![GitHub](https://img.shields.io/github/license/gilrsantana/DevCar)

# About The Project

https://devcar.netlify.app/

DevCar is a frontend project that was build with a youtube video at https://youtu.be/WzO5QlkjVLA.
The project show a model of a rental car website.

## Layout Mobile
![mobile1](Img/Views/mobile-view.png)

![mobile2](Img/Views/mobile-view2.png)

![mobile3](Img/Views/mobile-view3.png)

![mobile4](Img/Views/mobile-view4.png)

![mobile5](Img/Views/mobile-view5.png)

## Layout Web
![web](Img/Views/website-view.png)

![web2](Img/Views/website-view2.png)

![web3](Img/Views/website-view3.png)

![web4](Img/Views/website-view4.png)

![web5](Img/Views/website-view5.png)

## Technologies

### HTML

Semantic HTML

### CSS

Style in elements, FlexBox layout, KeyFrames, Transition, Position.

### JS

Smooth scroll with JS using cferdinandi smooth-scroll CDN
https://github.com/cferdinandi/smooth-scroll

# Autor

Gilmar Ribeiro Santana

https://www.linkedin.com/in/gilmarribeirosantana/

repository: gilrsantana/DevCAr

branch_name: refs/heads/main

repo_name: gilrsantana/DevCAr


text:
## Book Library
A book library where you can add, edit and delete books - part of TheOdinProject Projects

## Installation

open index.html in browser  .. . to edit, open the folder in your favorite code editor

```bash
cd odin-library and open index.html
```

## Technologies Used
- HTML
- CSS
- JavaScript

## Hosted
[Hosted on GitHub Page]( https://mysuulola.github.io/odin-library/)

```

## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

## License
[MIT](https://choosealicense.com/licenses/mit/)

repository: suulola/odin-library

repo_name: suulola/odin-library


text:
---
title: "Cross Compile OpenMP for IOS"
author: Guihao Liang
date: 2019-12-17 14:15:32
tags: ['cpp', 'clang']
categories: ['compile', 'cpp', 'ios']
---

## Generate XCode project

In order to use `xcodebuild` to build targets for IOS device, we need to provide `.xcodeproj`, which can be generated through `configure` at [Turicreate][0] root directory. Under the hood, the `.xcodeproject` is generated by `CMake` which uses `XCode` as the underlying generator.

```bash
cd <turicreate_root>
./configure --no-visualization --no-python --no-remotefs --target=iphoneos --arch=arm64 --with-capi --builder=xcode
```

Try to build [TuriCreate](0) with debug mode for ios12, with command

```bash
cd debug
xcodebuild -j 8 -project Turi.xcodeproj/ -target Recommender -arch arm64 only_active_arch=no -quiet
```

Not a long time waiting, the error message says:

```bash
cd /Users/guihaoliang/Work/guicreate-2/deps/build/libomp/src/ex_libomp && make
[  5%] Built target libomp-needed-headers
[  8%] Building CXX object runtime/src/CMakeFiles/omp.dir/kmp_alloc.cpp.o
[ 11%] Building CXX object runtime/src/CMakeFiles/omp.dir/kmp_atomic.cpp.o
[ 14%] Building CXX object runtime/src/CMakeFiles/omp.dir/kmp_csupport.cpp.o
[ 17%] Building CXX object runtime/src/CMakeFiles/omp.dir/kmp_debug.cpp.o
[ 20%] Building CXX object runtime/src/CMakeFiles/omp.dir/kmp_itt.cpp.o
[ 23%] Building CXX object runtime/src/CMakeFiles/omp.dir/kmp_environment.cpp.o
/Users/guihaoliang/Work/guicreate-2/deps/build/libomp/src/ex_libomp/runtime/src/kmp_environment.cpp:62:10: fatal error: 'crt_externs.h' file not found
#include <crt_externs.h>
         ^~~~~~~~~~~~~~~
1 error generated.
make[3]: *** [runtime/src/CMakeFiles/omp.dir/kmp_environment.cpp.o] Error 1
make[2]: *** [runtime/src/CMakeFiles/omp.dir/all] Error
```

Having a glance at  the related [OpenMP source code](https://github.com/llvm-mirror/openmp/blob/56d941a8cede7c0d6aa4dc19e8f0b95de6f97e1b/runtime/src/kmp_platform.h#L34),

```cpp
#if KMP_OS_DARWIN
#include <crt_externs.h>
#define environ (*_NSGetEnviron())
#else
extern char **environ;
#endif
```

It needs `<crt_externs.h>` when `KMP_OS_DARWIN` is defined, which means it compiles against `darwin` OS (`uname -s` to get codename for OS).

```cpp
#if (defined __APPLE__ && defined __MACH__)
#undef KMP_OS_DARWIN
#define KMP_OS_DARWIN 1
#endif
```

After googling, the fix should be fairly simple. Either copy source file of [crt_externs.h][cert-h] or inline expanding `#include <crt_externs.h>` to actual implementation code, which is about 5 lines.

But wait for a minute, I'm building binary for ios, and why there's a [compiler pre-defined macro](https://sourceforge.net/p/predef/wiki/OperatingSystems/) `__MACH__`? Shouldn't `__MACH__` refers to the laptop [Machintosh](https://en.wikipedia.org/wiki/Macintosh)? After a little bit research, `__MACH__` stands for the kernel called `machintosh`, which is the kernel that the successor kernel `darwin` builds on top of.

## Build with ARM architecture specified

The issue is that it runs the code to determine the compiler architecture before setting up the conditional compiler flags, in order to later pass preprocessor flags to source code. What wse need to do is to __explicitly__ add compile flags `-arch arm64` to tell compiler (`clang`) which architecture we want to compile for. `arm64` or `aarch64` is used here due to the fact that IOS is using ARM architecture.

For more details, feel free to check my another post about [compiler architecture flags](19-12-17-clang-compiler-arch-flag.md).

After the `arm64` is set, let's compile the project again,

```bash
[ 97%] Building C object runtime/src/CMakeFiles/omp.dir/z_Linux_asm.S.o
/Users/guihaoliang/Work/guicreate-2/deps/build/libomp/src/ex_libomp/runtime/src/z_Linux_asm.S:1546:5: error: unknown directive
error: unknown directive
    .size __kmp_unnamed_critical_addr,8
```

Tracing the error message, I found `asm` code causing trouble below.

```c
#if KMP_ARCH_ARM || KMP_ARCH_MIPS
    .data
    .comm .gomp_critical_user_,32,8
    .data
    .align 4
    .global __kmp_unnamed_critical_addr
__kmp_unnamed_critical_addr:
    .4byte .gomp_critical_user_
    .size __kmp_unnamed_critical_addr,4
#endif /* KMP_ARCH_ARM */

#if KMP_ARCH_PPC64 || KMP_ARCH_AARCH64 || KMP_ARCH_MIPS64
    .data
    .comm .gomp_critical_user_,32,8
    .data
    .align 8
    .global __kmp_unnamed_critical_addr
__kmp_unnamed_critical_addr:
    .8byte .gomp_critical_user_
    .size __kmp_unnamed_critical_addr,8 /** line 1546 **/
#endif /* KMP_ARCH_PPC64 || KMP_ARCH_AARCH64 */
```

Looking at line __1546__, clang already knows we intend to cross compile for __ARM__ but the clang we used here is specifically tailored for `XCode`,

```bash
CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
```

which doesn't support `.size` instruction.

## Summary

At this stage, I can do nothing but give up the attempt to integrate OpenMP into IOS devices.

IMO, it is pretty reasonable for XCode team to make this decision because IOS computing resources are quite limited and much much less powerful than laptops, and enabling OpenMP probably won't provide much benefit. What's more, OpenMP makes multi-threading much easier and convenient to use, developers may end up abusing multi-threading in their Apps, causing overall IOS slowdowns.

[0]: https://github.com/apple/turicreate
[cert-h]: https://opensource.apple.com/source/Libc/Libc-319/include/crt_externs.h.auto.html

repository: guihao-liang/my-blog-notes

repo_name: guihao-liang/my-blog-notes


text:
---
layout: post
title: "Stanford AI Lab Papers and Talks at CoRL 2020"
summary: "All the great work from the Stanford AI Lab accepted at CoRL 2020, all in one place."
short-summary: "All the great work from the Stanford AI Lab accepted at CoRL 2020, all in one place."
feature-img: "assets/img/posts/2020-11-16-corl-2020/logo_small.png"
thumbnail: "assets/img/posts/2020-11-16-corl-2020/logo_small.png"
author: Compiled by Annie Xie
tags: [CoRL, conference, publication, video]
---

{% figure %}

{% endfigure %}

The [Conference on Robot Learning](https://www.robot-learning.org/) (CoRL) 2020 is being hosted virtually from November 16th - November 18th. We're excited to share all the work from SAIL that's being presented, and you'll find links to papers, videos and blogs below. Feel free to reach out to the contact authors directly to learn more about the work that's happening at Stanford!

## List of Accepted Papers

#### [Learning 3D Dynamic Scene Representations for Robot Manipulation](https://arxiv.org/pdf/2011.01968.pdf)

**Authors**: Zhenjia Xu, Zhanpeng He, Jiajun Wu, Shuran Song

**Contact**<EMAIL_ADDRESS>
**Links:** [Paper](https://arxiv.org/pdf/2011.01968.pdf) \| [Video](https://www.youtube.com/watch?v=GQjYG3nQJ80) \| [Website](https://dsr-net.cs.columbia.edu/)

**Keywords**: scene representations, 3d perception, robot manipulation

#### [Learning Latent Representations to Influence Multi-Agent Interaction](https://drive.google.com/file/d/1_ezqLLEv4HLtj9vflRj0sq3PNOhaSnJm/view)

**Authors**: Annie Xie, Dylan P. Losey, Ryan Tolsma, Chelsea Finn, Dorsa Sadigh

**Contact**<EMAIL_ADDRESS>
**Links:** [Paper](https://drive.google.com/file/d/1_ezqLLEv4HLtj9vflRj0sq3PNOhaSnJm/view) \| [Blog Post](https://ai.stanford.edu/blog/lili/) \| [Website](https://sites.google.com/view/latent-strategies)

**Keywords**: multi-agent systems, human-robot interaction, reinforcement learning

#### [Learning Object-conditioned Exploration using Distributed Soft Actor Critic](https://arxiv.org/pdf/2007.14545.pdf)

**Authors**: Ayzaan Wahid (Google), Austin Stone (Google), Brian Ichter (Google Brain), Kevin Chen (Stanford), Alexander Toshev (Google)

**Contact**<EMAIL_ADDRESS>
**Links:** [Paper](https://arxiv.org/pdf/2007.14545.pdf)

**Keywords**: object navigation, visual navigation

#### [MATS: An Interpretable Trajectory Forecasting Representation for Planning and Control ](https://arxiv.org/abs/2009.07517)

**Authors**: Boris Ivanovic, Amine Elhafsi, Guy Rosman, Adrien Gaidon, Marco Pavone

**Contact**<EMAIL_ADDRESS>
**Links:** [Paper](https://arxiv.org/abs/2009.07517) \| [Video](https://www.youtube.com/watch?v=q6hMY2y-BcQ)

**Keywords**: trajectory forecasting, learning dynamical systems, motion planning, autonomous vehicles

#### [Model-based Reinforcement Learning for Decentralized Multiagent Rendezvous](https://arxiv.org/abs/2003.06906)

**Authors**: Rose E. Wang, J. Chase Kew, Dennis Lee, Tsang-Wei Edward Lee, Tingnan Zhang, Brian Ichter, Jie Tan, Aleksandra Faust

**Contact**<EMAIL_ADDRESS>
**Links:** [Paper](https://arxiv.org/abs/2003.06906) \| [Video](https://youtu.be/HqeYcO1DBUU) \| [Website](https://sites.google.com/view/multiagent-hpp/home)

**Keywords**: multiagent systems; model-based reinforcement learning

#### [Reinforcement Learning with Videos:  Combining Offline Observations with Interaction](https://arxiv.org/abs/2011.06507)

**Authors**: Karl Schmeckpeper, Oleh Rybkin, Kostas Daniilidis, Sergey Levine, Chelsea Finn

**Contact**<EMAIL_ADDRESS>
**Links:** [Paper](https://arxiv.org/abs/2011.06507) \| [Website](https://sites.google.com/view/rl-with-videos)

**Keywords**: reinforcement learning, learning from observation

#### [Sampling-based Reachability Analysis: A Random Set Theory Approach with Adversarial Sampling](https://arxiv.org/abs/2008.10180)

**Authors**: Thomas Lew, Marco Pavone

**Contact**<EMAIL_ADDRESS>
**Links:** [Paper](https://arxiv.org/abs/2008.10180)

**Keywords**: reachability analysis, robust planning and control, neural networks

## Keynote

#### Walking the Boundary of Learning and Interaction (Dorsa Sadigh)

{% figure %}

{% endfigure %}

**Overview:** There have been significant advances in the field of robot learning in the past decade. However, many challenges still remain when considering how robot learning can advance interactive agents such as robots that collaborate with humans. This includes autonomous vehicles that interact with human-driven vehicles or pedestrians, service robots collaborating with their users at homes over short or long periods of time, or assistive robots helping patients with disabilities. This introduces an opportunity for developing new robot learning algorithms that can help advance interactive autonomy.

In this talk, I will discuss a formalism for human-robot interaction built upon ideas from representation learning. Specifically, I will first discuss the notion of latent strategies— low dimensional representations sufficient for capturing non-stationary interactions. I will then talk about the challenges of learning such representations when interacting with humans, and how we can develop data-efficient techniques that enable actively learning computational models of human behavior from demonstrations, preferences, or physical corrections. Finally, I will introduce an intuitive controlling paradigm that enables seamless collaboration based on learned representations, and further discuss how that can be used for further influencing humans.

**Live Event:** November 17th, 7:00AM - 7:45AM PST

We look forward to seeing you at CoRL!


text:
# Aeons End App
Aeons End is a two to four player deck building cooperative survival game. This is a collaborative project that makes it easier for a team of players to set up a game session, save game data, and review stats for cards and characters.

## Installation
#### Starting the server:
1. In the terminal, run ""./bin/webpack".
2. In another terminal, run "bundle exec rails server".

#### Frontend Dependencies:
- React: react-rails gem.
- [Lodash](https://www.npmjs.com/package/lodash): a JavaScript library.
- [axios](https://www.npmjs.com/package/axios): an HTTP client for the browser and node.js.

#### Backend Dependencies:
- Ruby on Rails
- Database: Postgres

## Usage
#### Randomizer
A 2-player randomizer that selects mages, a nemesis, and market cards for a game session. User can record outcome of the game.

![randomizer](./docs/website_pics/randomizer.png)

### Cards
Displays all the cards in the expansions, including gems, relics, spells, and each mage's unique cards. Each card has its information and its win rate from saved game data.

![cards](./docs/website_pics/cards.png)

### Mages
Displays all the mages in the expansions, including information about their unique abilities, their starting cards, and their win rate from saved game data.

![mages](./docs/website_pics/mages.png)

### Nemeses
Displays all the nemeses in the expansions, including information about their difficulty level (rated by the creators of the game) and their loss rate from saved game data.

![nemeses](./docs/website_pics/nemeses.png)

### Player Stats
Displays all the players on your team, including their win rate from saved game data.

![players](./docs/website_pics/players.png)

### Game History
Displays all the games played by your team, including the date and time, the difficulty rating of the game, if the game was a win or loss, players, mages played, nemesis, market cards, and notes. Also includes a delete button to delete a specific game.

![games](./docs/website_pics/games.png)

## Development
#### Design
- [Wireframes](./docs/wireframes.md)

#### Documentation guidelines:
- Ruby: [YARD](http://www.rubydoc.info/gems/yard/file/docs/GettingStarted.md) and [RDoc](https://ruby.github.io/rdoc/)
- Javascript: [JSDoc](http://usejsdoc.org/)

## Credits
- Collaborator: [James Lee](https://github.com/jamesleejl)
- Board Game Creator: Kevin Riley
- Board Game Publisher: Action Phase Games, Indie Boards & Cards

## License
Refer to "LICENSE" file for more information.


text:
# Falloff Customizer
## Interactively adjust light falloff values for Unity deferred rendering

[This is an old tool, consider using my Built-In ISF plugin instead](https://github.com/alexismorin/Built-In-ISF)

![header](images/reference.png)

By default, Unity lights use a linear falloff model. In nearly every single instance, this won't compare to lighting in other game engines (or the HDRP). Especially if you're using linear color space and the deferred render path, you'll probably want this issue fixed as soon as possible! This package not only converts your lighting model to the more standard Inverse Square falloff model, but also allows you from then on to customize the falloff for lighting in your project.

### Usage

![ui](images/ui.png)

Navigate to the *Falloff Customizer* folder in the packages section of the project view and drag the prefab into any scene - delete once you're done!

- Adjust the curve to edit the falloff for your lights - this is pretty straightforward, but keep in mind that best results are achieved by having the curve time remain in the 0-1 range.
- You can adjust the falloff for the progressive lightmapper. Just switch between settings, disable then re-enable the script - results will change on your next bake.
- You can adjust the resolution of the falloff lookup texture that the package generates (the default editor resolution is 16); adjust to your liking - I find 8 better but 16 has a little more edge to it.
- You can adjust the texture format of the lookup texture for better quality - ARGB32 is the default but R16 can smooth things out a little.
- You can adjust the filter mode of the lookup texture - bilinear is a good tradeoff between performance and quality.

![gif](images/gif.gif)

### Compatibility

The *UnityDeferredLibrary.cginc* and *Internal-DeferredShading.shader* included in this package are built for Unity 2019.1 - It *might* work with Unity Unity 2019.2, but in all likeliness you'll need to find the correct files for your version - they're widely available online, just Google *Unity Internal Shaders* with your version after that.

![guide](images/guide.png)

Once you have the two new shader files inside your project, you'll need to override the default deferred shader with the one you imported in the *Graphics* settings. This done, open the *UnityDeferredLibrary.cginc* file and edit as such:

- Right after the *UNITY_DECLARE_DEPTH_TEXTURE(_CameraDepthTexture);* line, add *sampler2D _customFalloffTexture;*
- aside from it's first instance in the file, replace all instances of *_LightTextureB0* with *_customFalloffTexture*

Save and reimport, then it should work - otherwise just add an issue on this repo and I'll see what I can do.

### Install process

Unlike most of my other packages, this repo does not only contain a package but also a sample project. While you can install the package onto any other Unity project, you can open the correctly configured sample project to check things out first - if you're then happy follow the instructions below.

![packman](images/packman.png)

This is a plugin that makes use of Unity's new *Package Manager* feature. Just drop the *com.alexismorin.falloffcustomizer* folder into your *packages* folder (found at the same level as the Assets folder) and it should work out-of-the-box. If you're using an older version of Unity (not really supported here, but can be made to work if you're courageous), take the *com.alexismorin.falloffcustomizer* folder and then drag it anywhere into your regular project hierarchy.

### Acknowledgements

Standard pipeline Unity light still use range instead of attenuation, and will thus never be 100% physically accurate. This package can get you pretty close, but if all else fails I guess you can switch to Unreal Engine 😏

[TwoTailsGames for their Unity 2019.1 internal shader repo.](https://github.com/TwoTailsGames/Unity-Built-in-Shaders)

[The SCP: Containment Breach - Unity development team for being so friendly and laying out the initial issue](https://www.scp-unity.com/)

[Arthur Daurio for writing this excellent article on the backend behind the problem.](http://arthurdaurio.com/2018/05/13/inverse-square-falloff-in-unity/)

Per usual, whipped up in around an hour on my couch - bugs beware.

repository: RuchirRaj/Falloff-Customizer

repo_name: RuchirRaj/Falloff-Customizer


text:
---
layout: post
rel_link:  "9_1_1_patch2"
title:  "CMSSW_9_1_1_patch2"
date:   2017-06-15 08:17:50
categories: cmssw
relmajor: 9
relminor: 1
relsubminor: 1
relpatch: _patch2
---

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

1. [19223](http://github.com/cms-sw/cmssw/pull/19223){:target="_blank"}  from **@davidlange6**: Xrootd revert back ported to 91x `comparison`  `core`  created: 2017-06-14 15:57:51 merged: 2017-06-14 15:58:27

2. [19212](http://github.com/cms-sw/cmssw/pull/19212){:target="_blank"}  from **@bsunanda**: Run2-hcx135 Bug fix to avoid crash in HcalGeometry (backport of PR#19172) `geometry`  created: 2017-06-14 02:20:15 merged: 2017-06-14 15:50:29

3. [19209](http://github.com/cms-sw/cmssw/pull/19209){:target="_blank"}  from **@bsunanda**: Phase2-hgx86 Fix the bug for overwriting (backport from 9_2_X #19198) `reconstruction`  `upgrade`  created: 2017-06-13 16:03:59 merged: 2017-06-15 08:13:15

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

repository: cms-sw/ReleaseNotes

repo_name: cms-sw/ReleaseNotes


text:
# The Bean Factory Pattern
Having started to look at Spring, lets take a little bit of time to understand better what is going on inside.  The Spring framework uses a pattern commonly referred to as a *Factory* (or specifically a Bean Factory).  The Factory is a *container* that references *blueprints* to build object (instances commonly referred to as *beans*) as required by a calling application.  These *beans* live inside the factory which manages them.  As they are based upon *blueprints* defined in a configuration file, their internals can be changed without altering the calling objects.  We say *internals* as changing their *interfaces* could however affect the callers.  The Factory manages the life of the bean, simply returns *references* to the caller to use and when the Beans are no longer references, the Factory destroys them.

A major benefit to this approach is that there can be just ONE copy of the instance which can be used repeatedly in the code.  However, this requires that instance be *stateless*.  Stateless means the Bean only retains _final_ data between calls; it must not have anything that varies (e.g. a counter).  This way, if 2 different threads call the same Bean, the values it holds will not be corrupted.

As explained earlier in the Module, Beans are defined in a variety of combinable ways:-
- xml configuration (mentioned earlier)
- during execution of the object (flexible but not always recommended)
- annotations in caller and definitional code - which is prescanned to generate the configuration that drives Spring.
Here, we focus on the annotation method.

The Bean Factory has several facets.  For today will focus on the core and practice, namely by:
- reviewing the concept Dependency Injection (DI) / Inversion of Control (IoC)
- explore the the bean factory model
- look at the core elements of beans, and using annotation how
  - configure the code so that beans are found and wired together
  - the different ways that bean can interact
  - specifying what to do when a bean is created and destroyed

## Materials & Resources

Consider the following situation:

```java
public class TextEditor {
   private SpellChecker spellChecker;

   public TextEditor() {
      spellChecker = new SpellChecker();
   }
}
```

Read this through closely.  It says that *When TextEditor is created, it will have a dependency on a creation of an instance of a SpellChecker*.  In this way we can say that the *TextEditor is dependent upon SpellChecker*.

Inversion of Control (IoC) says we can change that.  Instead we could pass an instance of the SpellChecker as we would a parameter:-

```java
public class TextEditor {
   private SpellChecker spellChecker;

   public TextEditor(SpellChecker spellChecker) {
      this.spellChecker spellChecker();
   }
}
```

This is the fundamental basis of IoC.  It's how we inject a dependency (DI).

The Bean Factory enables this sort of *passing* to occur in a simple, clean way.

| Material | Time |
|:---------|-----:|
|[Inversion of Control/Dependency Injection (JavaBrains.01)](https://www.youtube.com/watch?v=GB8k2-Egfv0&t=714s) - explains how the need for the Bean Factory arose.|14:51|
|[Understanding Beans & Factory Design Pattern (JavaBrains.03)](https://www.youtube.com/watch?v=xlWwMSu5I70)|6:52|
|[Creating beans - annotation (InterviewDot)](https://www.youtube.com/watch?v=P0m1dW0LJeE) - a simple illustration of annotation using `@bean()`.|1:58|
|[Overview of DI (tutorialspoint)](https://www.tutorialspoint.com/spring/constructor_based_dependency_injection.htm)|reading|
|[Using Annotation (tutorialspoint)](https://www.tutorialspoint.com/spring/spring_annotation_based_configuration.htm)|reading|
|[Autowire Annotation (tutorialspoint)](https://www.tutorialspoint.com/spring/spring_autowired_annotation.htm)|reading|
|[Useful reference on using Annotation(spring.io)](http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html) - peruse this, I think you'll find it handy later.|reading|

Once through the above, consider rewatching the first video (JavaBrains.01) to reinforce your understanding.

## Review
- Container (creates the objects needed; instantiates from *blueprint*)
  - Object Factory
    - gets a request
    - reads a configuration (blueprint / meta-data)
     - does the *new*
- Bean
  - Handle to an object that is made by the factory (repository)
  - Object lifecycle
    - instantiation
    - properties injected
    - .setBeanName() - method of BeanNameAware
    - preDestroy
- wiring
- `@Bean(name="*override the name of the bean here if you so wish*")`
- `@Configuration`
- `@Component`
- `@ComponentScan`
- `@Autowired`
  - on a setter method (that is `setX(int x) {this.x = x});`) -  will make required (unless told otherwise); byType wiring
  - on a property (that is `private AProperty aProperty;`) - will remove the need for a setter method; Spring automatically assigns the property with the values passed
  - on a constructor (that is `public class AClass { public AClass(){}; ...`) - will bean and connect in the subordinate class(es) !!AZE?
  - `@Autowired(required=false)` - will turn off the default behaviour so that the bean will be construct even if the value(s) to instantiate it are missing.
- Libraries
  - `org.springframework.context.annotation*` - to reach use annotation directives to instead read a Java class and pick up on `@configuration`, `@bean`, `@PostConstruct` & `@PreDestroy` and to have a Java class with embedded annotation
  - `org.springframework.beans.factory.*` (note also has annotation support)
- Different ways of instantiating the Factory, but as we are using annotation:-
  - `AnnotationConfigApplicationContext()`
- the naming convention for beans; start off lowercase (as opposed to a Class)

### Optional Items
- `@Resource` - similar to `@Autowired`
- `@Required` - similiar to `@Autowired`
- `@Service` - as opposed to `@Component`
- `@Scope` - prototype, singleton

## Workshops
- [Hello World](./workshop/Workshop01.md) - in this exercise, you will get acquainted with the IntelliJ support for Spring
- [Work through an example of DI](./workshop/Workshop02.md) - run the code and understand how it's working
- [Create a couple of beans that are autowired](./workshop/Workshop03.md) - try to do it yourself referring to earlier examples
- [More on Autowiring](./workshop/Workshop04.md) - play with where the @Autowire is set
- [Bean Dependency and adding initialization and destruction methods](./workshop/Workshop05.md)

#Links
- [Parent - Java Spring](../README.md)
- [Prior - Thymeleaf](../thymeleaf/README.md)
- [Next - Database Integration](../database-integration/README.md)

repository: gaborveres-planorama/teaching-materials

repo_name: gaborveres-planorama/teaching-materials


text:
# Trajectory Optimization Library

Contents:

1 Introduction

2 Setup
- 2.1 Third-Party Dependencies
- 2.2 Installation Instructions
  - 2.2.1 IPOPT Installation
  - 2.2.2 CMake Installation
  - 2.2.3 GNUPlot Installation
  - 2.2.4 MuJoCo Installation
  - 2.2.5 A `setup.sh` script for Mac-based system

3 Building and Running Samples
- 3.1 Building Library
- 3.2 Running Tests
- 3.3 Running Samples

4 Common Installation Issues
- 4.1 IPOPT-Related Issues
- 4.2 MuJoCo-Related Issues (when using cmake)
- 4.3 mujoco-py Issues (optional)

5 Profiling Instructions

## 1 Introduction

Trajectory optimization is a software library for robotic motion planning. The core libraries are implemented in C++. The library has been tested on Ubuntu 16.04.

## 2 Setup

### 2.1 Third-Party dependencies

1) [IPOPT](https://projects.coin-or.org/Ipopt)
2) [CMake](https://cmake.org/)
3) [GNUPlot](http://www.gnuplot.info/) (Optional, used for trajectory visualization)
4) [MuJoCo](http://www.mujoco.org)

### 2.2 Installation Instructions

#### 2.2.1 IPOPT Installation

1) Download the source code from https://www.coin-or.org/download/source/Ipopt/ , and then upack IPOPT in the home directory.
```
wget http://www.coin-or.org/download/source/Ipopt/Ipopt-3.12.4.tgz
tar xvzf Ipopt-3.12.4.tgz
```

2) Get IPOPT third-party packages:
```
cd ~/Ipopt-3.12.4/ThirdParty/Blas
./get.Blas
cd ../Lapack
./get.Lapack
cd ../Mumps
./get.Mumps
cd ../Metis
./get.Metis
cd ../../
```
3) Compile IPOPT:
```
cd ~/Ipopt-3.12.4/
mkdir build
cd build
../configure
make -j 4 #Compile using 4 cores (if you have them)
make install
```

#### 2.2.2 CMake Installation

1) Download the source code from https://cmake.org/download/ , choose "cmake-3.12.2.tar.gz".

2) Unpack the file in your preferred location, and then configure CMake.

```
tar -zxvf xx.tar.gz
./bootstrap
make
make install
```

#### 2.2.3 GNUPlot Installation
```
sudo apt-get install gnuplot
```

#### 2.2.4 MuJoCo Installation
1) If you do not have a license, get your license key following the website https://www.roboti.us/license.html .

2) Download MuJoCo Pro 150 from MuJoCo website https://www.roboti.us/index.html , choose "mjpro150 linux".

3) Unpack the file in your preferred location (home as an example), and **copy the license to the bin folder** (~/mjpro150/bin).

4) Add the environment variable to ~/.bashrc.

```
nano ~/.bashrc
```

```
export LD_LIBRARY_PATH=~/mjpro150/bin #your own location
export PATH="$LD_LIBRARY_PATH:$PATH"
```

```
source ~/.bashrc
```

5) Give it a try!

```
cd ~/mjpro150/bin
simualte ../model/humanoid.xml
```

You should be able to see a humanoid model falling down.

(it is noted that the executable "simulate" was coded to search the license key file to the relative simulate path, so the key should be put into the bin folder.)

#### 2.2.5 A `setup.sh` script for Mac-based system
(A script `setup.sh` has been provided to install the first three dependencies on a Mac-based system. It will install Homebrew and use it to install the first three dependencies. To execute it, run `chmod +x setup.sh && ./setup.sh`.)

Linux support has not been added to the script yet.

## 3 Building and Running Samples

### 3.1 Building Library

TrajectoryOptimization can be easily used as a git submodule in any other CMake-based project. Let's walk through integrating TrajectoryOptimization into an existing source project.

1) cd into your project directory, `git init` if it isn't already a git repository.
2) `mkdir -p lib && git submodule add [insert this project's clone URL (https/ssh)] lib/trajectoryOptimization`
3) If you don't already use CMake, run `touch CMakeLists.txt`. Insert `cmake_minimum_required(VERSION 3.8)` as the first line.
5) Insert these into your `CMakeLists.txt` to import and link the `TrajectoryOptimization::TrajectoryOptimizationLib` target:
```
add_subdirectory(lib/trajectoryOptimization)
add_executable([yourExecutableName] [yourSourceFiles])
target_link_libraries([yourExecutableName]
  PUBLIC
    TrajectoryOptimization::TrajectoryOptimizationLib
)
```
6) `mkdir build && cd build && cmake ..`
7) `make`
8) `./[yourExecutableName]`

Now you can build software using TrajectoryOptimization!

To ever recompile and rerun, just cd into `build/` and run `make && ./[yourExecutableName]`.

### 3.2 Running Tests

To build tests, run cmake like this: `cmake -Dtraj_opt_build_tests=ON ..`. Then cd into `lib/trajectoryOptimization` and run `ctest`.

### 3.3 Running Samples

To build samples, run cmake like this: `cmake -Dtraj_opt_build_samples=ON ..`. Then cd into `lib/trajectoryOptimization` and run `./trajectoryOptimizationSample`. The sample currently optimizes a 3D trajectory. Inspect [the source](src/trajectoryOptimizationMain.cpp) for more information and to learn about usage.

## 4 Common Installation Issues

When installing or builidng executables using CMake, you may encounter one of the following issues. Please try the suggestion below.

### 4.1 IPOPT-Related Issues

1) Could not find Blas: Solution:
```
sudo apt-get install gfortran
```
2) Could not find -lgfortran: You may need to update your gcc-5 to gcc-7 instructed by the following link https://gist.github.com/jlblancoc/99521194aba975286c80f93e47966dc5 . After that, When you make executable, you may run into “could not find -lgfortran”. You can solve this issue by copying all the files that named as "\*libgfortran"  in gcc 5 folder (4 files probably) into 7.3.0 folder (or your current gcc version).

### 4.2 MuJoCo-Related Issues (when using cmake)

1) Missing libgl: If you don't have libGL.so in usr/lib/x86_64-linux-gnu/ but have it in usr/lib/x86_64-linux-gnu/mesa , you may try the following solution.
```
ln -s /usr/lib/x86_64-linux-gnu/mesa/libGL.so /usr/lib/x86_64-linux-gnu/libGL.so
```

2) Missing libglfw: Create a simbolic link libglfw.so  to libglfw.so.3 (in ~/mjpro150/bin folder), so that the missing glfw problem can be solved.

```
ln -s libglfw.so.3 libglfw.so
```
### 4.3 mujoco-py Issues (optional)

If you want to test mujoco-py from OpenAI https://github.com/openai/mujoco-py , here are a few problems you might encounter.

1) If you accidentaly upgraded pip to pip 10 or above, you may run into this error “python3-pip installed but pip3 command not found” . Solution:
```
sudo apt-get remove python3-pip
sudo apt-get install python3-pip</pre
```
2) Fatal error: GL/osmesa.h: No such file or directory #96. Solution(https://github.com/openai/mujoco-py/issues/96):
```
sudo apt-get install libosmesa6-dev
```

3) ImportError: No module named 'OpenGL'. Solution:
```
sudo apt-get install python3-opengl
```

4) ERROR: GLEW initalization error: Missing GL version. Solution: add the environment variable to ~/.bashrc.
```
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/nvidia-390
```

## 5 Profiling Instructions
Tool: valgrind

repository: ZehaoXU/trajectory-optimization

repo_name: ZehaoXU/trajectory-optimization


text:
# Instructions append

You can use `collect(1:10)` as a quick way to create a collection but remember that
under the hood, collection returns an array so you can also just make an array
explicitly by doing `my_array = [1, 2, 3, 4, 5]`.

repository: exercism/julia

gha_language: Julia

repo_name: exercism/julia


text:
# T!ckr
A python reddit bot which supplies stock information when given a ticker command.

## Instructions:
```shell
$ pip install -r requirements.txt
$ python manage.py
```
When initially starting the program, it is important to edit the praw.ini file that is installed in your default Python pip directory.
Move it to the project directory. This is where authorization is done. On Reddit, under user preferences/apps, you can find two keys
after creating a personal script. These are the secret key and the user key.
```python
[bot1]
client_id=user_key (shorter-string of random characters)
client_secret=secret_key (long-string of random characters)
password=insert_password
username=insert_user
user_agent=PyEng Bot 0.1
```
Each can be found under the app information for your new script. Place them accordingly, as shown above.
If you don't include a Reddit username and password the bot will not be able to comment.
## How it Works:
RedditStock looks for ticker symbols preceded by an exclamation mark, and returns neatly formatted data to the requesting user
in the form of a comment.

![alt text](screenshots/Bot.png "Image from Reddit")

### Things to Note:
This bot runs off of a custom made csv file with NASDAQ and NYSE entries. If you wish to modify the CSV file, you must rebuild the
alphabetically sorted text file which tells the program where to start looking when given a ticker (when it searches for the company
name). You can do this using
```shell
python rebuild.py
```
in your command line. Just remember the CSV file must be alphabetically ordered.

repository: Xnetter/RedditStockBot

repo_name: Xnetter/RedditStockBot


text:
## FHIR Path

To use it, `npm install fhirpath.js`. Then:

```js
   var fp = require('fhirpath.js')
   var result = fp.evaluate({      // the target to evaluate against
     "a": 1,
     "b": [2, 3]
   },
   "a | b | a")                    // the path expression to evaluate

   assert.deepEqual(result, [1, 2, 3, 1])
```

## Try it

Live demo at https://niquola.github.io/fhirpath-demo/#/

## Develop it

Generate the lexer and parser from the included Antlr grammer via:

    sh ./setup.sh

Run tests:

    npm  test

Regenerate test case file:

    npm run-script generate-test-cases

repository: psbrandt/clinFHIR

repo_name: psbrandt/clinFHIR


text:
# SRFI nnn: Define higher-order lambda

by Lassi Kortela

## Status

Draft

## Abstract

This SRFI codifies the following shorthand syntax, which some Scheme
implementations have had for a long time.

    (define ((outer-name outer-args ...) inner-args ...)
      inner-body ...)

## Rationale

Procedures that make other procedures are commonly used in Scheme. A
shorthand syntax makes them easier to define, obviating the need to
write a lambda inside a lambda. The following code:

    (define (foo a b c)
      (lambda (d e)
        body ...))

can be shortened to:

    (define ((foo a b c) d e)
      body ...)

Apart from helping define higher-order functions, the shorthand syntax
also partially alleviates the lack of syntactic sugar for making
partially applied functions in Scheme.

### Survey of prior art

The following Scheme implementations have the shorthand syntax built
in:

* Chicken
* Gauche
* Larceny
* MIT Scheme
* Racket
* Sagittarius
* Scheme 9 from Empty Space

The following implementations don't have it: Bigloo, BiwaScheme, Chez
Scheme, Chibi-Scheme, Cyclone, Gambit, Gerbil, Guile, Ikarus,
IronScheme, Kawa, Loko, Mosh, s7, Scheme 48, SigScheme, STklos,
TinyScheme, Vicare, Ypsilon.

### Exporting the shorthand from a library

Since the shorthand is non-standard (i.e. not defined in _RnRS_), it
can be controversial or confusing to the uninitiated programmer.

This SRFI handles the conflict by storing the shorthand version of
`define` in a library that does not have to be imported by default.
Then programmers can choose whether to import it or not. In portable
code the `import` serves to document the dependency on this SRFI.

## Specification

The shorthand version of `define` behaves according to the following
`syntax-rules` macro:

    (define-syntax define
      (syntax-rules ()

        ((define ((name args ... . tail) xargs ... . xtail)
           xbody ...)
         (define/native (name args ... . tail)
           (lambda (xargs ... . xtail)
             xbody ...)))

        ((define ((name args ... . tail) xargs ...)
           xbody ...)
         (define/native (name args ... . tail)
           (lambda (xargs ...)
             xbody ...)))

        ((define ((name args ...) xargs ... . xtail)
           xbody ...)
         (define/native (name args ...)
           (lambda (xargs ... . xtail)
             xbody ...)))

        ((define ((name args ...) xargs ...)
           xbody ...)
         (define/native (name args ...)
           (lambda (xargs ...)
             xbody ...)))

        ((define things ...)
         (define/native things ...))))

where `define/native` is the implementation's native version of
`define`. The native `define` can be equivalent to the `define` from a
_RnRS_ report, or may have extensions to _RnRS_ `define`.

### Importing in R6RS and R7RS

In R6RS Scheme implementations, the shorthand version of `define` is
exported from the library `(srfi :NNN)`. In R7RS Scheme
implementations, it is exported from the library `(srfi NNN)`.

The shorthand version of `define` is exported under the name `define`,
which means that it shadows _RnRS_ `define`. To avoid the name clash,
a program using this SRFI should import the _RnRS_ base library as:

* R6RS: `(import (except (rnrs) define))`
* R7RS: `(import (except (scheme base) define))`

Alternatively, Scheme's import renaming can be used to import the
shorthand `define` under a different name, in which case the same
program can alternate between using the shorthand `define` and _RnRS_
`define`. For example:

* R6RS: `(import (rename (srfi :NNN) (define define/higher)))`
* R7RS: `(import (rename (srfi NNN)  (define define/higher)))`

### Importing from other libraries

The shorthand `define` may also be imported from libraries, possibly
under other names.

## Importing by default

This SRFI does not say whether or not the shorthand `define` is
imported into the default interaction environment.

## Examples

Simplest example:

```
(define ((greet-with-prefix prefix) suffix)
  (string-append prefix " " suffix))

(define greet (greet-with-prefix "Hello"))

(greet "there!") => "Hello there!"
```

With a dotted list to take a variable number of arguments:

```
(define ((append-to . b) . a)
  (apply append (append b a)))

((append-to)) => ()
((append-to '(1 2) '(3 4)) '(5 6) '(7 8)) => (1 2 3 4 5 6 7 8)
```

## Implementation

R6RS and R7RS libraries using `syntax-rules` are attached.

## Acknowledgements

Thanks to Arthur Gleckler for explaining the trick, and to Göran
Weinholt for collaborating on Docker containers that made it easy to
do the survey.

## Copyright

Copyright (C) Lassi Kortela (2021).

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

repository: pre-srfi/define-higher-order-lambda

repo_name: pre-srfi/define-higher-order-lambda


text:
## PHP Class for CVSS v3.0 / v3.1 Calculator

[![Build Status](https://travis-ci.org/security-database/cvssv3.svg?branch=master)](https://travis-ci.org/security-database/cvssv3)

[![Latest Stable Version](https://poser.pugx.org/security-database/cvss/version)](https://packagist.org/packages/security-database/cvss)
[![Total Downloads](https://poser.pugx.org/security-database/cvss/downloads)](https://packagist.org/packages/security-database/cvss)
[![Latest Unstable Version](https://poser.pugx.org/security-database/cvss/v/unstable)](//packagist.org/packages/security-database/cvss)
[![License](https://poser.pugx.org/security-database/cvss/license)](https://packagist.org/packages/security-database/cvss)

### Version

#### dev-master
Identical to 2.2 actually

#### 2.2
- Correction on MPR / PR calculation (could bewrong in some case)
- Added a test 8 to check
- Added optional and modification to X if not set (for better calculation)
- Correction of checkModified()

#### 2.1.1
- Travis and Composer update : php 5.6 -> 7.3 phpunit

#### 2.1.0
- CVSS 3.1 Upgrade
- Backward compatible with 3.0 -> accept 3.0 as input, output 3.1 vector
- Documentation upgrade to 3.1
- Our Cvss3::roundUp(), major upgrade in 3.1 from 3.0 seem to work fine (actually used in 3.0)
- Upgrade tests case to 3.1 and 3.0 vector in input give 3.1 vector in output
- Removed @version in Cvssv3.php

#### 2.0.3
- EnvScore calcultation fix with MPR and Scope when MS is not set (again)
- Cleaner code push by @faynwol
- Add some UnitTest on vectors vs CVSSv3 website

#### 2.0.2
- EnvScore calcultation fix with MPR and Scope when MS is not set
- EnvScore Formula, with now 2 RoundUp instead of One
- Add some UnitTest on vectors vs CVSSv3 website

#### 2.0.1
- EnvScore calcultation fix when envModifiedImpactSubScore <= 0
- EnvScore Formula set to 0 in that case
- Change some props to static
- Change Clean method to handle static properties

#### 2.0
- Change public vars to private vars
- Add getter to all private vars
- Add setter to locale vars
- Add locale validator in __constructor and setter
- Change phpUnit test case to reflect getter and setter
- Update documentation
- Update some DocBlock
- Update to 2.0 since getters and setters are not backward compatible

- Todo more and more phpUnit test case ...

#### 1.3.2
- Modify DocBlock with \Exception
- Add a Clean() function to be able to clean Object before register another one
- Add public vector_part (Base, Temp and Env vector part)
- Modify private to public base, env and tmp
- Change private to public some vars ($this->base, $this->env, $this->tmp)
- Fix \Exception()
- Add Code on some Exception (__construct && register && explodeVector)
- Change constructVector() to construct only mandatory vector (optional and modified are not put on vector if value is 'X' == No set)
- Fix check constant on language
- Fix modified metrics defaulting
- Add a constructor that load language files
- Add a reverse vector checker

#### 1.3.1
- Fix envImpactSubScoreMultiplier
- Add Scores priority

#### 1.3.0
- Fix - Errors on calculation, specific on Modified Scope
- Fix - Modified scores -> weight (float)
- Rework - Modified scores with normalized names - easy to read the code now
- Added - Multi language Label

### Common Vulnerability Scoring System Version 3.1

Common Vulnerability Scoring System (CVSS) is a free and open industry standard for assessing the severity of computer system security vulnerabilities. It is under the custodianship of NIST. It attempts to establish a measure of how much concern a vulnerability warrants, compared to other vulnerabilities, so efforts can be prioritized. The scores are based on a series of measurements (called metrics) based on expert assessment. The scores range from 0 to 10. Vulnerabilities with a base score in the range 7.0-10.0 are High, those in the range 4.0-6.9 as Medium, and 0-3.9 as Low. Class try to follow PSR2 standard except for some 120chars on formula.

### License
This piece of software is under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0)

### PHP Class

#### Initialization

Could be composer:

```php
composer require security-database/cvss
```

or traditional include class into your project, and include it.
```php
include_once('Cvss3.php');
```

After that, create a new vector.
```php
use SecurityDatabase\Cvss\Cvss3;

try {
    $cvss = new Cvss3();
    $cvss->register("CVSS:3.1/AV:N/AC:H/PR:H/UI:R/S:U/C:L/I:L/A:N/E:P/RL:W/CR:L/IR:L/MAV:A/MAC:H/MPR:L/MUI:N/MS:U/MC:L/MI:L/MA:L");

    print_r($cvss->getWeight());
    print_r($cvss->getScores());
    print_r($cvss->getScoresLabel());
    print_r($cvss->getSubScores());
    print_r($cvss->getSubScoresLabel());
    print_r($cvss->getRatings());
    print_r($cvss->getFormula());
    print_r($cvss->getVector());
    (...)

} catch (Exception $e) {
    print $e->getCode() . " : " . $e->getMessage();
}
```

#### Usage
You can now get some informations :

Get weight of every piece of the vector (array());
```php
print_r($cvss->getWeight());
/*
array (size=20)
  'AV' => float 0.85
  'AC' => float 0.44
  'PR' => float 0.27
  'UI' => float 0.62
  'C' => float 0.22
  'I' => float 0.22
  'A' => float 0
  'E' => float 0.94
  'RL' => float 0.97
  'CR' => float 0.5
  'IR' => float 0.5
  'MAV' => float 0.62
  'MAC' => float 0.44
  'MPR' => float 0.62
  'MUI' => float 0.85
  'MC' => float 0.22
  'MI' => float 0.22
  'MA' => float 0.22
  'RC' => float 1
  'AR' => float 1
*/
```

Get scores used in scores (array());
```php
print_r($cvss->getScores());
/*
array (size=7)
  'baseScore' => float 6.7
  'impactSubScore' => float 5.7576309677951
  'exploitabalitySubScore' => float 0.3924228
  'temporalScore' => string 'NA' (length=2)
  'envScore' => string 'NA' (length=2)
  'envModifiedImpactSubScore' => string 'NA' (length=2)
  'overallScore' => float 6.7
*/
```

Get scores with label (en_US) used in scoresLabel (array());
```php
print_r($cvss->getScoresLabel());
/*
array (size=7)
  'Base Score' => float 6.7
  'impact SubScore' => float 5.7576309677951
  'Exploitabality Sub Score' => float 0.3924228
  'Temporal Score' => string 'NA' (length=2)
  'Environmental Score' => string 'NA' (length=2)
  'Environmental Modified Impact SubScore' => string 'NA' (length=2)
  'Overall CVSS Score' => float 6.7
*/
```

Get sub scores used in sub_scores (array());
```php
print_r($cvss->getScores());
/*
array (size=9)
  'impactSubScoreMultiplier' => float 0.8064
  'impactSubScore' => float 5.7576309677951
  'exploitabalitySubScore' => float 0.3924228
  'baseScore' => float 6.7
  'temporalScore' => float 6.7
  'envModifiedExploitabalitySubScore' => float 0.3924228
  'envImpactSubScoreMultiplier' => float 0.8064
  'envModifiedImpactSubScore' => float 5.7576309677951
  'envScore' => float 6.7
*/
```

Get sub scores with label (en_US) used in sub_scoresLabel (array());
```php
print_r($cvss->getScoresLabel());
/*
array (size=9)
  'Impact SubScore Multiplier' => float 0.8064
  'impact SubScore' => float 5.7576309677951
  'Exploitabality Sub Score' => float 0.3924228
  'Base Score' => float 6.7
  'Temporal Score' => float 6.7
  'Environmental Modified Exploitabality SubScore' => float 0.3924228
  'Environmental Impact SubScore Multiplier' => float 0.8064
  'Environmental Modified Impact SubScore' => float 5.7576309677951
  'Environmental Score' => float 6.7
*/
```

Get Severity Ratings used in severityRatings (array());
```php
print_r($cvss->getRatings());
/*
array (size=3)
    'baseRating' => string 'Low' (length=3)
    'tempRating' => string 'Low' (length=3)
    'envRating' => string 'Low' (length=3)
*/
```

Get Formula with detail
```php
print_r($cvss->getFormula());

/*
    array (size=9)
      'impactSubScoreMultiplier' => string '1 - ( ( 1 - 0.22 ) * ( 1 - 0.22 ) * ( 1 - 0 ) )' (length=47)
      'impactSubScore' => string '6.42 * 0.3916' (length=13)
      'exploitabalitySubScore' => string '8.22 * 0.85 * 0.44 * 0.27 * 0.62' (length=32)
      'baseScore' => string 'roundUp( min( 10 , 2.514072 + 0.514634472 ) )' (length=45)
      'temporalScore' => string 'roundUp( 3.1 * 0.94 * 0.97 * 1)' (length=31)
      'envModifiedExploitabalitySubScore' => string '8.22 * 0.62 * 0.44 * 0.62 * 0.85' (length=32)
      'envImpactSubScoreMultiplier' => string 'min( 0.915, 1 - ( ( 1 - 0.22 * 0.5 ) * ( 1 - 0.22 * 0.5 ) * ( 1 - 0.22 * 1 ) ) )' (length=80)
      'envModifiedImpactSubScore' => string '6.42 * 0.382162' (length=15)
      'envScore' => string 'roundUp(min(10 , (2.45348004 + 1.181753232 ) * 0.94 * 0.97 * 1),1)' (length=66)
*/
```

Get the vector
```php
print $cvss->getVector();

/* return a string :
   CVSS:3.1/AV:N/AC:H/PR:H/UI:R/S:U/C:L/I:L/A:N/E:P/RL:W/CR:L/IR:L/MAV:A/MAC:H/MPR:L/MUI:N/MS:U/MC:L/MI:L/MA:L
*/
```

#### Contribute
If you found any error on the class, please, fork it, push a PR or contact us at "info at security-database.com"

gha_language: PHP


text:
[parm]:leanpubExtensions = 1
[parm]:title             = 'Tatin's Package Configuration'

# Tatin's package Configuration File

## Overview

Every package has a configuration file: that's one of the things that actually make it a package. It defines all there needs to be defined in order to consume the package, and to announce its existence to the world.

This is an example:

```
{
  alias: "",
  api: "DotNetZip",
  date: "2020-05-16",
  description: "Zipping and unzipping with.NET Core on all major platforms",
  files: "",
  group: "aplteam",
  name: "DotNetZip",
  project_url: "https://github.com/aplteam/DotNetZip",
  source: "DotNetZip.aplc",
  tags: "zip-tools;windows;mac-os;linux",
  version: "0.5.4",
}
```
## Details

### Introduction

In the workspace a simple namespace can be a used for package configuration. On file it is saved as JASON5.

Tatin's API offers a function `Tatin.InitialisePackage` that can be used to create a package config file.

It can be fed with an empty vector as right argument: then just defaults are established.

Instead you may create a namespace and populate that namespace with Tatin package configuration variables which are discussed underneath.

Example:

```
      parms←⎕NS''
      parms.group←'aplteam'
      parms.name←'Foo'
      parms.version←'1.0.0'
      Tatin.InitialisePackage parms
```

The user command aquivalent is `]tatin.packageconfig`

### User defined variables

You may define your own variables in a package configuration file.

However, since we might add Tatin-specific variables at a later stage there is a danger of name clashes. This is avoided by a simple rule:

The names of user defined variables _must_ start with an underscore.

If you specify any variable with a name that Tatin does not know about and that does not start with an underscore, then error will be thrown.

### Tatin's package configuration variables

#### alias

By default a package is established in the target space under its own name. However, for ease of use but also in order to avoid possible name clashes, an alias can be defined. If not empty the package must be addressed by the alias rather than its own name.

#### api

Things are different with namespaces, and with collections of namespaces and/or classes: In that case the names of some of the functions (for namespaces) or some of the classes might become the API.

Defines the API of the package. In the example the package consists of a single class named `DotNetZip`, therefore the class name is identical with the API. Similarly, if the package consists of a single function --- not that this is recommended! --- the name of the function is the API.

A> ### Defining an API with namespaces
A> Classes have a build-in mechanism for hiding details (all the private stuff) and offering a public interface (API): all the public stuff. Namespaces lack this.
A>
A> Thanks to references you can still easily simulate this. Given a namespace `Foo` one common technique is to put all the functions, variables, operators and sub-namespaces into a namespace `Foo.core`.
A>
A> You can then create the public interface by assigning references in `Foo`. If there is just one function (`Run`) and just one variable (`DATA`) that should be public then this would do:
A> ```
A> #.Foo.Run←#.Foo.core.Run
A> #.Foo.Data←#.Foo.core.DATA
A> ```
A>
A> That would not work with niladic functions, but purists would argue that you should not have niladic functions at all: by definition a function takes an argument, manipulates it and returns it. A niladic "function" might return something, but it  cannot take something, so calling it a function is questionable.

#### assets

This can be one of:

* A simple text vector representing a single filename
* A simple text vector representing a the name of a folder
* A vector of text vectors representing files or folders or a mixture of both

The path must be relative to the package since the file or the folder are part of the package. For that reason the path may not contain a "`:`" under Windows, and not start with "`/`" or with "`./`". If it does anyway an error is thrown.

There is one exception: when an absolute path is specified but it's partly identical with the source path of the package then Tatin removes the source part and makes the path(s) silently relative.

Note that when the package configuration file is written to disk the existence of the specified assets is checked. If any of them do not exist an error is thrown.

#### date

The date of the package. This is not necessarily the publishing date.

#### description

A short description of what the package is supposed to do, or what kind of problems it solves. This is supposed to be readable by and meaningful to humans.

This information is typically used when a human accesses a Tatin Server with a Browser.

#### group

The group part of the package ID[^id]

#### name

The name part of the package ID[^id]

#### project_url

The URL that points to something like GitHub. An example is `http://github.com/aplteam-MarkAPL-9.2.0`.

#### source

The name of a text file (that contains code) or a folder (that contains a collection of code files).

If it's a single file it might be anything with the extension `.aplf` (a function), `.aplo` (an operator), `.aplc` (a class script), `.apln` (a namespace script) or `.apli` (an interface script).

If it's a folder it might contain any number and mixture of the aforementioned files. Any files with other extension are misplaced and well be ignored entirely.

If `source` is left empty Tatin will attempt to identify the source itself.

* If there is any script file found with the aforementioned extension that file will become the source.

* If there is no file with such an extension all folders are investigated except those mentioned as "assets". If there is just one folder left that carries one or more files with the aforementioned extensions then that folder will become the source.

* If Tatin cannot establish the source an error will be thrown.

#### tags

A simple text vector, possibly empty (though that is not recommended), that should contain semicolon-separated lists of tag words. These can be helpful to filter packages when searching for a solution to a particular problem.

#### version

The version[^version] part of the package ID[^id]

[^id]: A package ID consists of `{group}-{name}-{major.{minor}.{patch}`
[^version]: A version is built from the major number, the minor number and the version number, and possibly a build number (which is not recorded in the package configuration file).

  Examples for valid version numbers are `1.2.3` and `<IP_ADDRESS>165`

### Access after loading a package

Whether you load a package with `LoadPackage` or `LoadDependencies`, the contents of the configuration file is available as readable JSON under the name `∆CONFIG` together with `∆URI` and `∆HOME`.

Note that `∆HOME` will be empty in case two conditions are met:

* The package was brought intot the workspace with `LoadPackage` (as opposed to `LoadDependencies`)
* The package does not have any assets

All of them are niladic functions because that's how we emulate constants in APL.

repository: mkromberg/Tatin

repo_name: mkromberg/Tatin


text:
## Core Functionality

### Authentication
- [x] Register and login with...
    - [x] with Email + Password (MVP)
    - [x] with Google (MVP)
    - [x] with Facebook (MVP)
    - [ ] with Twitter
    - [ ] with LinkedIn
    - [ ] with Pinterest
- [ ]  Link
    - [x]  A social account to my existing validated account (MVP)
    - [ ]  An email to my existing validated account
    - [ ]  Unlink a linked social account or email
- [x] Reset my password with an emailed reset link
- [x] Confirm ownership of an email address with an emailed link
    - [ ] Resend the confirmation email if the token expires

### Storefront

### Chat
- [ ] Register a Chat User that...
    - [ ] is attached to a User.
    - [ ] has a unique Username.
    - [ ] has a Watch List.
    - [ ] has an Ignore List.
- [ ] Send Messages to...
    - [ ] another Chat User [DM]
    - [ ] multiple Chat Users [MDM]
    - [ ] Channels
- [ ] Send Messages that...
    - [ ] display sent timestamps
    - [ ] support unicode
    - [ ] have markdown formatting
    - [ ] can tag one or more Chat Users
    - [ ] can share images
- [ ] Administer Chat Rooms by..
    - [ ] creating or deleting a Channel
    - [ ] setting it as Public / Private
    - [ ] setting it as Persistent / Volatile
    - [ ] invite other Chat Users to a Channel
    - [ ] kick / ban other Chat Users from a Channel
    - [ ] give Channel Admin Privileges to another Chat User
- [ ] Search for...
    - [ ] other Chat Users
    - [ ] public Channels
- [ ] Join and Leave...
    - [ ] Public Channels
    - [ ] Private Channels
    - [ ] Direct Messages
    - [ ] Multi-Direct Messages
- [ ] Add Users to...
    - [ ] a Watch List
    - [ ] an Ignore List

repository: abrisene/eidolon-server-ts

gha_language: TypeScript

gha_license_id: NOASSERTION

repo_name: abrisene/eidolon-server-ts


text:
UnitTesting
===================

[![Build Status](https://travis-ci.org/randy3k/UnitTesting.svg?branch=master)](https://travis-ci.org/randy3k/UnitTesting)
[![Build status](https://ci.appveyor.com/api/projects/status/9nnjlnj6tetbxuqd/branch/master?svg=true)](https://ci.appveyor.com/project/randy3k/unittesting/branch/master)
[![Coverage Status](https://coveralls.io/repos/github/randy3k/UnitTesting/badge.svg?branch=master)](https://coveralls.io/github/randy3k/UnitTesting?branch=master)

This is a unittest framework for Sublime Text 2 and 3. It runs unittest testcases on local machines and CI services such as [travis-ci](https://travis-ci.org) and [appveyor](http://www.appveyor.com). It also supports testing syntax_test files for the new [sublime-syntax](https://www.sublimetext.com/docs/3/syntax.html) format.

### Getting started example

It is hard to explain the usage without an example, please visit [UnitTesting-example](https://github.com/randy3k/UnitTesting-example) for a minimal example. The tests in this repo are written to test this plugin and they do not help in regular use case.

### Credits
Thanks [guillermooo](https://github.com/guillermooo) and [philippotto](https://github.com/philippotto) for their efforts in AppVeyor and Travis OSX support.

repository: alek-sys/UnitTesting

repo_name: alek-sys/UnitTesting


text:
---
title: loadModel
module: 9
jotted: false
---

  <button class="tablinks active" onclick="openTab(event, 'Overview')">Overview</button>
  <button class="tablinks" onclick="openTab(event, 'example')">Example</button>
  <button class="tablinks" onclick="openTab(event, 'resources')">Resources</button>
  <button class="tablinks" onclick="openTab(event, 'todo')">To Do</button>

### Overview

# loadModel

```js
//draw a spinning teapot
let teapot;

function preload() {
  // Load model with normalise parameter set to true
  teapot = loadModel('assets/teapot.obj', true);
}

function setup() {
  createCanvas(100, 100, WEBGL);
}

function draw() {
  background(200);
  scale(0.4); // Scaled to make model fit into canvas
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  normalMaterial(); // For effect
  model(teapot);
}
```

#### Description

Description
Load a 3d model from an OBJ or STL file.

loadModel() should be placed inside of preload(). This allows the model to load fully before the rest of your code is run.

One of the limitations of the OBJ and STL format is that it doesn't have a built-in sense of scale. This means that models exported from different programs might be very different sizes. If your model isn't displaying, try calling loadModel() with the normalized parameter set to true. This will resize the model to a scale appropriate for p5. You can also make additional changes to the final size of your model with the scale() function.

Also, the support for colored STL files is not present. STL files with color will be rendered without color properties.

#### Syntax

loadModel(path, normalize, [successCallback], [failureCallback], [fileType])
loadModel(path, [successCallback], [failureCallback], [fileType])

#### Parameters

* path String: Path of the model to be loaded
* normalize Boolean: If true, scale the model to a standardized size when loading
* successCallback function(p5.Geometry): Function to be called once the model is loaded. Will be passed the 3D model object. (Optional)
* failureCallback Function(Event): called with event error if the model fails to load. (Optional)
* fileType String: The file extension of the model (.stl, .obj). (Optional)

#### Returns
* p5.Geometry: the p5.Geometry object

### Example

Finding assets is not difficult. Here are a couple of sites:

* https://sketchfab.com/store
* https://www.turbosquid.com/Search/3D-Models/free/asset
* https://free3d.com/3d-models/assets

```js
//draw a well
let well;

function preload() {
  // Load model with normalise parameter set to true
  // remember you can load OBJ and STL models
  // the normalize parameter ensures that it will fit in p5
  well = loadModel('assets/well_OBJ.obj', true);
}

function setup() {
  createCanvas(500, 500, WEBGL);
}

function draw() {
  background(200);
  scale(3); // Scaled to make model fit into canvas
  rotateX(frameCount * 0.01);
  rotateY(frameCount * 0.01);
  normalMaterial(); // For effect
  // this displays the model using the "model" function
  model(well);
}
```

### Resources

Coding Train Video

Try the code in the earlier tab to see the final result. Feel free to change values.


text:
# _Track-a-Meal_

#### _Lets users input the meals they have eaten and  keep track of them._

#### By _**Thomas Rivas**_

## Description

#### _This web app uses angular2 and is meant for users to input meals and it's info such as name, details, calories and date. The user is also able to edit and add new meals. There is also an ability to filter meals based on calorie amount_

## Setup/Installation Requirements

* _Clone this repository_
* _Open in your text editor of choice_
* _In the command line write bower install and npm install after cloning_
* _In command line write gulp build to compile and gulp serve to run on browser_
* _Make sure you have bower install bootstrap --save so  bootstrap will work on the file_

## Known Bugs

_{No know bugs at the time}_

## Technologies Used

* _JavaScript_
* _HTML_
* _CSS_
* _Angular2_
* _Git_

### License

Copyright (c) 2016 **_Thomas Rivas_**

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
# Mobile Flashcards

Mobile Flashcards is a React Native app for iOS and Android that allows users to create decks, add cards and quiz themselves.

It uses React Native, Expo, Redux, & React Navigation.

This app is the third of three projects required for [Udacity's React Nanodegree program](https://www.udacity.com/course/react-nanodegree--nd019).

## Installation

```bash
$ git clone https://github.com/a-adly/mobile-flashcards.git
$ cd mobile-flashcards
$ yarn
```

## Usage

The project can be run with npm, yarn or expo

- `yarn start` or `npm start` or `expo start`

This will open Expo Developer Tools in the browser. You can then do one of the following.

- Use your real device to test:

  Scan the QR Code using the Expo Client app ([Expo Client for Android & iOS](https://expo.io/tools#client)) from an Android or iOS device.

- Use an Android Emulator or iOS Simulator to run the app:
  - [Android Emulator Setup](https://docs.expo.io/workflow/android-studio-emulator/)
  - [iOS Simulator Setup](https://docs.expo.io/workflow/ios-simulator/)

## Tests

| Platform | Device                | Tested             |
| :------- | :-------------------- | :----------------- |
| Android  | Xiaomi (android 10.0)   | :white_check_mark: |

## Credits

Credits to https://github.com/maanizfar/mobile-flashcards for inspiration.

## License

Licensed under MIT

repository: a-adly/mobile-flashcards

repo_name: a-adly/mobile-flashcards


text:
# 2D-MCTV-Denoising
This is the source code for "Minmax-concave Total Variation Denoising" (2D case).

## Paper
Du, H. & Liu, Y. **Minmax-concave Total Variation Denoising**.

*Signal, Image and Video Processing* (2018).

doi: 10.1007/s11760-018-1248-2

url: <https://link.springer.com/article/10.1007/s11760-018-1248-2>

## Prerequisite
- Python 3
- numpy
- scipy
- skimage
- matplotlib

## Usage
- For demonstration, you can simply clone the repository and run `main.py`. Denoising results as well as error images of three methods TV, NLTV and MCTV are plotted. Below is one demo figure.

- The demo 2D 256 × 256 synthetic block image and the corresponding noisy one are saved as `image.mat` and `noi_image.mat`, respectively. One thing I should point out is that the noisy image was generated by function `imnoise` in MATLAB. One reason I choose this function is that, after adding noise, it truncates outliers, and the pixel values stay within proper range (e.g., for gray image, the pixel range is [0, 1]).

- Feel free to explore and modify all parameter values in `main.py`. For detailed explanation of each parameter and its proper value range, please see the comment in code.

- For MATLAB version of the source code, you can email me<EMAIL_ADDRESS>
- I followed the instruction and used the source code of "Bregmanized Nonlocal Regularization for Deconvolution and Sparse Reconstruction" to get the NLTV denoising result (paper url: <https://doi.org/10.1137/090746379>), and saved it as `NLTV.jpg`. It greatly facilitates my coding process. You may download the source code from the author Xiaoqun Zhang's homepage, or here: <http://math.sjtu.edu.cn/faculty/xqzhang/html/code.html>.

- For more algorithm details, please see `tv2d.py` and `mctv2d.py` or the relevant research paper.