text:
# Animal Shelter API

#### Epicodus Ruby and Rails - Building an API - 2019.08.23

#### By Ben Bennett-Cauchon

## Description

An API for a fictional animal shelter created using Ruby on Rails. The API lists the available cats and dogs at the shelter. There are also routes for getting a random animal and for searching for animals by type (cat or dog), breed, sex, age, and weight.

## Specifications

The API should contain:
* Endpoints for GET (all and by id), POST, PUT and DELETE.
* A RANDOM endpoint that randomly returns a park/business/animal.
* A second custom endpoint that accepts parameters (example: a SEARCH route that allows users to search by specific park names).
* Model scopes to process parameters from API calls.
* At least one of the objectives from Monday's Further Exploration lesson (such as versioning, token authentication, or serialization).
* Thorough exception handling.
* Complete testing with request specs.
* Randomized data with Faker or your own custom seed code.
* A README that thoroughly documents all endpoints, including parameters that can be passed in.

## Setup

Created with Ruby version 2.5.1
* clone/download the repository
* navigate to the directory in a terminal
* run the commands:
```
bundle install
rake db:create
rake db:migrate
rake db:seed
rails server
```

## Sending Requests

* Send requests to the api through http://localhost:3000 using Curl, Postman, or a similar app
* All requests should return a JSON object with the requested records, a confirmation message (when deleting a record), or an error message (when invalid parameters are passed in)

## API Endpoints

#### GET /v1/animals

* Returns a list of all animals
* Http status: 200

#### GET /v1/animals/:id

* Returns the animal with the given :id, or an error message if no animal exists with the given :id
* Http status: 200 (valid :id) or 404 (invalid :id)

Sample Request:

`GET http://localhost:3000/v1/animals/1`

Sample Response:
```
{
    "id": 1,
    "animal_type": "Cat",
    "name": "Jasper",
    "breed": "Oriental Bicolor",
    "sex": "Male",
    "age": 15,
    "weight": 19,
    "created_at": "2019-08-23T22:35:47.068Z",
    "updated_at": "2019-08-23T22:35:47.068Z"
}
```
#### POST /v1/animals

* Adds an animal record to the database
* Parameters:
  * `animal_type`
  * `breed`
  * `name`
  * `sex`
  * `age` (in years)
  * `weight` (in pounds)
* Http status: 201 (valid params) or
422 (invalid params)

Sample Request:

`POST http://localhost:3000/v1/animals/?animal_type=Dog&name=Abigail&breed=Shepherd&sex=Female&age=1&weight=49.5`

Sample Response:
```
{
    "id": 13,
    "animal_type": "Dog",
    "name": "Abigail",
    "breed": "Shepherd",
    "sex": "Female",
    "age": 1,
    "weight": 49.5,
    "created_at": "2019-08-24T00:35:55.483Z",
    "updated_at": "2019-08-24T00:35:55.483Z"
}
```

#### PATCH/PUT /v1/animals/:id
* Edits the record with the given :id's attributes and returns the updated record
* Parameters are the same as for `POST /v1/animals`
* Http status: 201 (valid params) or
422 (invalid params)

Sample Request:

`PUT http://localhost:3000/v1/animals/13?name=Max&weight=42`

Sample Response:
```
{
    "id": 13,
    "animal_type": "Dog",
    "name": "Max",
    "breed": "Shepherd",
    "sex": "Female",
    "age": 1,
    "weight": 42,
    "created_at": "2019-08-24T00:35:55.483Z",
    "updated_at": "2019-08-24T00:35:55.483Z"
}
```

#### DELETE /v1/animals/:id
* Deletes the record with the given :id and returns a confirmation message
* Http status: 200 (valid :id) or 404 (invalid :id)

Sample Request:

`DELETE http://localhost:3000/v1/animals/13`

Sample Response:
```
{
    "message": "Animal deleted"
}
```

#### GET /v1/random
* Returns a random record from the database

Sample Request:

`GET http://localhost:3000/v1/random`

Sample Response:
```
{
    "id": 355,
    "animal_type": "Cat",
    "name": "Jasper",
    "breed": "Cornish Rex",
    "sex": "Female",
    "age": 2,
    "weight": 1,
    "created_at": "2019-08-23T22:35:47.256Z",
    "updated_at": "2019-08-23T22:35:47.256Z"
}
```

#### GET /v1/search
* Returns a list of all animals matching the given search parameters
* Parameters:
  * `animal_type`
  * `breed`
  * `sex`
  * `min_age` (in years)
  * `max_age` (in years)
  * `min_weight` (in pounds)
  * `weight` (in pounds)
* Http status: 201 (valid params) or
422 (invalid params)

Sample Request:

`GET http://localhost:3000/v1/search/?animal_type=dog&breed=shepherd&sex=female`

Sample Response:
```
[
    {
        "id": 402,
        "animal_type": "Dog",
        "name": "Abigail",
        "breed": "Shepherd - Hound",
        "sex": "Female",
        "age": 1,
        "weight": 49.5,
        "created_at": "2019-08-24T00:30:01.500Z",
        "updated_at": "2019-08-24T00:30:01.500Z"
    },
    {
        "id": 403,
        "animal_type": "Dog",
        "name": "Abigail",
        "breed": "Shepherd - Hound",
        "sex": "Female",
        "age": 1,
        "weight": 49.5,
        "created_at": "2019-08-24T00:32:23.667Z",
        "updated_at": "2019-08-24T00:32:23.667Z"
    },
    {
        "id": 303,
        "animal_type": "Dog",
        "name": "max",
        "breed": "Shepherd - Hound",
        "sex": "Female",
        "age": 1,
        "weight": 49.5,
        "created_at": "2019-08-23T22:35:47.068Z",
        "updated_at": "2019-08-24T00:52:53.880Z"
    },
    {
        "id": 398,
        "animal_type": "Dog",
        "name": "Chance",
        "breed": "Germanshepherd",
        "sex": "Female",
        "age": 12,
        "weight": 46,
        "created_at": "2019-08-23T22:35:47.438Z",
        "updated_at": "2019-08-23T22:35:47.438Z"
    }
]
```

## Support and contact details

If you find a bug, run into any issues, or have questions, ideas or concerns please feel free to submit an issue for the project here on GitHub.

## Technologies Used

* Ruby on Rails
* ActiveRecord
* RSpec
* Shoulda-Matchers
* Faker
* FactoryBot
* SimpleCov

### License

MIT License

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.

Copyright (c) 2019 Benjamin Bennett-Cauchon

repository: BenB-C/animal-shelter-api

gha_language: Ruby

repo_name: BenB-C/animal-shelter-api


text:
## SystemD Service Unit

template of service description to register redis-commander
as a systemd service unit.

### Installation

copy the `redis-commander.service` file to the `/etc/systemd/system/` directory
and modify it to fit the local installation of redis commander.

The following lines MUST be modified:

* "Environment" - add as many "Environment" lines as needed, one line per environment variable set
* "ExecStart" - update installation dir to match startup file inside local bin directory (`xxx/bin/redis-commander.js`)
* "User" - add name of unprivileged user to run redis commander under. Do not run this app as user "root"!

Now reload systemd as root to register this service unit:

`systemctl daemon-reload`

Service can now be started or stopped with:
* `systemctl start redis-commander`
* `systemctl stop redis-commander`

license: MIT

repository: malitov/rpi-redis-commander

branch_name: refs/heads/master

extension: md

gha_license_id: MIT

license_type: permissive

repo_name: malitov/rpi-redis-commander


text:
---
title: Changes
page_title: Changes
description: Check our "Changes" documentation article for the RadOutlookBar {{ site.framework_name }} control.
slug: radoutlookbar-changes
tags: changes
published: True
position: 0
---

# Changes

This article describes the release history of the __RadOutlookBar__ control.

To see the fixes and features included in our latest official release please refer to our {% if site.site_name == 'Silverlight' %} [Release History](http://www.telerik.com/support/whats-new/silverlight/release-history) {% endif %} {% if site.site_name == 'WPF' %} [Release History](http://www.telerik.com/support/whats-new/wpf/release-history) {% endif %}.

## Q1 2014

### What's Fixed

* Fixed: Icons in minimized items are not visualized

## Q1 2013

### What's Fixed

* Fixed: Crashes VS design time when placed in Docking and SelectedIndex is set in XAML

* Fixed: Editing the template in Blend do not extract the default style but the control template

* Fixed: The Arrow doesn't change its direction when the OutlookBar is minimized in Metro theme

## Q2 2012

### What's Fixed

* Fixed: OutlookBarItems are not initially shown until the control is resized when the MinimizedAreaVisibility is set to Collapsed

* Fixed: Setting the ActiveItemsCount to 0 in XAML does not work

## Q1 2012

### What's Fixed

* Fixed: Add a possibility to programmatically move the items in the minimized area

* Fixed: Ability to template the items in the Drop Down Area of the OverflowButton is needed

>You can examine the Q1 2012 release history in {% if site.site_name == 'Silverlight' %}[our site](http://www.telerik.com/products/silverlight/whats-new/release_notes/q1-2012-version-2012-1-215-271395503.aspx){% endif %}{% if site.site_name == 'WPF' %}[our site](http://www.telerik.com/products/wpf/whats-new/release-history/q1-2012-version-2012-1-215-1506305735.aspx){% endif %}.

repository: telerik/xaml-docs

gha_language: JavaScript

gha_license_id: NOASSERTION

repo_name: telerik/xaml-docs


text:
# Viral-Track

Viral-Track is a R-based computational software based on **STAR** and **samtools** developped to detect and identify viruses from single-cell RNA-sequencing (scRNA-seq) raw data. This tool was tested on various scRNA-seq datasets derived from mouse and human infected samples as described in our paper *'Detecting and studying viral infection at the single-cell resolution using Viral-Track'*.  Viral-Track was tested on a CentOS 7 cluster and on an Ubuntu 18.0.4 workstation.

Installation
-------------

Before running Viral-Track, several dependencies must be installed :

1 . The first step is to install [**R software**](https://www.r-project.org/). Once this is done, several Bioconductor packages  have to be installed too. To do so start a R session and type :

```r
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install(version = "3.10")
BiocManager::install(c("Biostrings", "ShortRead","doParallel","GenomicAlignments","Gviz","GenomicFeatures","Rsubread"))
```

2 . **S**pliced **T**ranscript **A**lignment to **A** **R**eference (**STAR**) has to be installed. The full installation process is described on the STAR [Github](https://github.com/alexdobin/STAR). On Ubuntu this can be done directly by typing :

```batch
sudo apt-get install rna-star
```
3 . **Samtools** suite is also required. The installation is described extensively [here](http://www.htslib.org/download/). On Ubuntu this is done by simply typing :

```batch
sudo apt-get install samtools
```

4 . The transcript assembler **StringTie** is needed. This installation process is described [here](https://ccb.jhu.edu/software/stringtie/). Don't forget to add StringTie to your shell's PATH directory.

5 . For the single cell demultiplexing we will use **UMI-tools** and the R package **RSubread**. Installation of **UMI-tools** is described [here](https://github.com/CGATOxford/UMI-tools).

Creation of the  Index and of the annotation file
----------

The first step consists in creating a **STAR** index that include both host and virus reference genomes.
To do so first download the **ViruSite**  [genome reference database](http://www.virusite.org/index.php?nav=download). Host genome has also to be downloaded from the [ensembl website](https://www.ensembl.org/info/data/ftp/index.html).
This can take some time and requires large amount of memory and storage space : please check that you have at least 32 GB of RAM and more than 100GB of avaible memory.

The  **STAR** index can now be built by typing :

```batch
mkdir /path/to/index
STAR --runThreadN N --runMode genomeGenerate --genomeDir /path/to/index --genomeFastaFiles /path/to/Virusite_file.fa  path/to/Host_genome_chromosome*.fa
```

Lastly you need to create a small file that list all the viruses included in the index and their genome length. We provide an example in the Github that corresponds to the VirusSite dataset.

Pre-processing of the single data
----

Before running any analysis we advise the user to perform the first steps of the demultiplexing on the  raw fastq data. This can be done using **UMI-tools** and is easy for droplet based techniques such as DROP-seq and 10X. An extensive tutorial can be found [here](https://github.com/CGATOxford/UMI-tools/blob/master/doc/Single_cell_tutorial.md). The user should stop at step 3 (included) in order to get filtered and annotated fastq files with the cellular and UMI barcode in the sequence header.

Detection of viruses in scRNA-seq data
---------------

We can now start the real analysis. Viral-Track relies on two different text files to run : a file containing the values of all parameters (parameter file) and one containing the path to the sequencing files to analyze (target file). An exemple of each file is provided in the Github.

The parameter file consists in a list of rows where the name of each variable is followed by an equal symbol and then the value of the parameter.

The target file contains the list of the files paths. The files can be either .fastq or .fastq.gz files.

Before running any scanning analysis check the parameter file and make sure that you have set the correct values for :

1. The output directory (Output_directory variable) : If the directory does not exist it will be created.
2. The path to the STAR index (Index_genome).
3. The path to the virus annotation file (Viral_annotation_file).
4. The number of cores to use (N_thread) : please be carefull as STAR and samtools can comsumme large amount of memory ! Runnning Viral-Track with a too high number of thread can trigger massive memory swapping....

Once this is done you can launch the analysis using :

```batch
Rscript Viral_Track_scanning.R Path/to/Parameter_file.txt Path/to/Target_file.txt
```
If you want to launch it in the background use instead :

```batch
R CMD BATCH Viral_Track_scanning.R Path/to/Parameter_file.txt Path/to/Target_file.txt &
```

Once the analysis is over, the results can be checked by looking at the output directory. A pdf called QC_report.pdf is automatically generated and described the most important results :
The three first panels describe the general quality of the mapping (percentage of mapped reads, mean length of the mapped reads....). The next panels describe the quality of the mapping of each individual virus : three different scatter plots show the number of uniquely mapped reads, the complexity of the sequences, the percentage of genome mapped and the length of the longest mapped contig. By default only viruses with at least 50 uniquely mapped reads, a mean sequence complexity of 1.3 and 10% of the genome mapped is considered as being present in the sample.
An example of a QC pdf file can be found in the Github.

Transcriptome assembly
---------------

 If wanted, the viral transcriptome of the detected viruses can be assembled : while efficient in some case (see the example of the Influenza virus segment 7), the biased coverage of conventionnal scRNA-seq techniques makes the transcript assembly challenging.

```batch
Rscript Viral_Track_transcript_assembly.R  Path/to/Parameter_file.txt Path/to/Target_file.txt
```
The annotated transcriptome is saved as a GTF file (called Merged_GTF.txt) inside a new directory which is named accordingly to the variable 'Name_run' stored in the Parameter file.

Single-cell demultiplexing
---------------

Single cell demultiplexing is performed using a wrapper of **UMI-tools** and **Rsubreads** : _make sure you have processed the fastq data as described above !_

The creation of the count table is straightforward : by typing

```batch
Rscript Viral_Track_cell_demultiplexing.R  Path/to/Parameter_file.txt Path/to/Target_file.txt
```
For each sample a TSV table called Expression_table.tsv is generated  : it is a conventionnal UMI tab that describes viral gene expression in each cell and can therefore be used for analysis and data integration.

repository: rumarova/Viral-Track

repo_name: rumarova/Viral-Track


text:
# Welcome to our Playbook

At Obvious, we’re working to build an inclusive company with a value-driven culture. That’s an easy thing to want and say, but it’s difficult to practice because exclusion is often the default in our industries \(both software and consulting\). It takes active effort to find the hidden biases in our companies and remove them.

One of our core values is to be "**public by default**": this repository therefore contains nearly all of the policies and practices that we use at Obvious. It represents many hours of research, lots of thoughtful debates, and some serious introspection. It’s certainly not perfect, but we think it’s a great place to start.

| Table of Contents |
| :--- |
| [Employee Handbook](employee-handbook/introduction/) |
| [Design Playbook](https://design.obvious.in/) |
| [Engineering Playbook](https://engineering.obvious.in/) |
| [Hiring Playbook](https://hiring.obvious.in/) |
| [Career Growth and Progression](https://progression.obvious.in/) |
| [Community and Events](https://community.obvious.in/) |
| [Job Listings](https://jobs.obvious.in/) |

Feel free to fork this repository and use any or all of these policies, and to modify them in whatever way makes sense for your company. We hope that by publishing them, other companies can benefit from our research and make their own policies more inclusive.

All feedback and suggestions _\(especially in the form of pull requests\)_ are appreciated. We’ve gotten several different perspectives to help arrive at these policies, but we are certainly missing many more and making mistakes as a result. This is a work in progress that we hope will get better with more time and more contributors.

If these policies sound like a place where you want to work, please do look through our [open career listings](https://jobs.obvious.in/).

### Acknowledgements

The Obvious Employee Handbook is a derivative of the [Tidepool Employee Handbook](https://github.com/tidepool-org/handbook/), which is itself derived from the [Clef Employee Handbook](https://github.com/clef/handbook/). These are/were available to all via a Creative Commons license, and for that we are very thankful.

We hope that many more people will suggest ways for us to improve these policies.

repository: vinaysshenoy/handbook

repo_name: vinaysshenoy/handbook


text:
---
title: CompletionStage
permalink: /Java/CompletionStage/
date: 2021-01-11
key: Java.C.CompletionStage
category: Java
tags: ['java se', 'java.util.concurrent', 'java.base', 'interface java', 'Java 1.8']
sidebar:
  nav: java
---

## Descripción
{{site.data.Java.C.CompletionStage.description }}

## Sintaxis
~~~java
public interface CompletionStage<T>
~~~

## Métodos
* [acceptEither()](/Java/CompletionStage/acceptEither)
* [acceptEitherAsync()](/Java/CompletionStage/acceptEitherAsync)
* [applyToEither()](/Java/CompletionStage/applyToEither)
* [applyToEitherAsync()](/Java/CompletionStage/applyToEitherAsync)
* [exceptionally()](/Java/CompletionStage/exceptionally)
* [handle()](/Java/CompletionStage/handle)
* [handleAsync()](/Java/CompletionStage/handleAsync)
* [runAfterBoth()](/Java/CompletionStage/runAfterBoth)
* [runAfterBothAsync()](/Java/CompletionStage/runAfterBothAsync)
* [runAfterEither()](/Java/CompletionStage/runAfterEither)
* [runAfterEitherAsync()](/Java/CompletionStage/runAfterEitherAsync)
* [thenAccept()](/Java/CompletionStage/thenAccept)
* [thenAcceptAsync()](/Java/CompletionStage/thenAcceptAsync)
* [thenAcceptBoth()](/Java/CompletionStage/thenAcceptBoth)
* [thenAcceptBothAsync()](/Java/CompletionStage/thenAcceptBothAsync)
* [thenApply()](/Java/CompletionStage/thenApply)
* [thenApplyAsync()](/Java/CompletionStage/thenApplyAsync)
* [thenCombine()](/Java/CompletionStage/thenCombine)
* [thenCombineAsync()](/Java/CompletionStage/thenCombineAsync)
* [thenCompose()](/Java/CompletionStage/thenCompose)
* [thenComposeAsync()](/Java/CompletionStage/thenComposeAsync)
* [thenRun()](/Java/CompletionStage/thenRun)
* [thenRunAsync()](/Java/CompletionStage/thenRunAsync)
* [toCompletableFuture()](/Java/CompletionStage/toCompletableFuture)
* [whenComplete()](/Java/CompletionStage/whenComplete)
* [whenCompleteAsync()](/Java/CompletionStage/whenCompleteAsync)

## Ejemplo
~~~java
{{ site.data.Java.C.CompletionStage.code}}
~~~

## Artículos

{%- for _ldc in site.data.Java.C.CompletionStage.ldc -%}

       {{ _ldc['nombre'] }}

{%- endfor -%}

branch_name: refs/heads/main


text:
# php_genderize
PHP5 lib for handling genderize.io gender recognition

Basicaly, it's for guessing the gender by a given first name and using [genderize.io](http://genderize.io).

Author: Bart Tyrant<EMAIL_ADDRESS>Contributors: Luke Shaheen @tlshaheen http://github.com/tlshaheen
License: The MIT License http://www.opensource.org/licenses/mit-license.php

==Usage:==

The simplest case:

```php
$recognizer = new \Genderize\Base\Recognizer('Peter');

$peter = $recognizer->recognize();
print_r($peter);
```

will give:

Genderize\Base\Name Object
(
    [_name:protected] => Peter
    [_count:protected] => 4284
    [_gender:protected] => male
    [_probability:protected] => 1.00
)

You can pass multiple names - at time of writing, genderizer.io accepts up to 10 at once

```php
$recognizer = new \Genderize\Base\Recognizer(array('Peter', 'John'));

$namesinfo = $recognizer->recognize();
print_r($namesinfo);
```

will give:

array([0] => Genderize\Base\Name Object
            (
                [_name:protected] => Peter
                [_count:protected] => 4284
                [_gender:protected] => male
                [_probability:protected] => 1.00
            ),
        [1] => Genderize\Base\Name Object
            (
                [_name:protected] => Peter
                [_count:protected] => 4284
                [_gender:protected] => male
                [_probability:protected] => 1.00
            )
)

--

Also, country and language filters are supported:

```php
$Recognizer = Genderize::factory();

$asia = $Recognizer->set_name('Asia')->recognize();
print_r($asia);

$asiaPL = $Recognizer->set_country_id('pl')->set_name('Asia')->recognize();
print_r($asiaPL);
```

... will print out:

Genderize\Base\Name Object
(
    [_name:protected] => Asia
    [_count:protected] => 97
    [_gender:protected] => female
    [_probability:protected] => 0.99
)
Genderize\Base\Name Object
(
    [_name:protected] => Asia
    [_count:protected] => 26
    [_gender:protected] => female
    [_probability:protected] => 1.00
    [_country_id] => PL
)

Have an API key from http://store.genderize.io? Use `$Recognizer->set_api_key($api_key)` to pass it with the request.

gha_language: PHP


text:
# xtabs

A cross tabulation library simulating R's API.

## Installation

```bash
$ npm install xtabs
```

## Examples

### Cross tabulation

```js
var xtabs = require("xtabs");

var data = {
  // null represents absence of data, like NA in R.
  department: ["RD", "RD", "HR", "GA", null, "GA", "RD"],
  gender: ["M", "F", null, "M", "F", "M", "M"]
};

// Make a cross tabulation by department and gender.
var t = xtabs.table(data, "department", "gender");
console.log(t.get("HR", "M")); // 0
console.log(t.get("RD", "F")); // 1
console.log(t.dim); // [3, 2]
console.log(t.dimnames);

// Use undefined to indicate that you want the whole data.
// t.get(undefined, "M") is equivalent to t[, "M"] in R.
console.log(t.get(undefined, "M").get("GA")); // 2

// You can also use number indices to retrieve data.
// t.get(0) is equivalent to t.get(0, undefined).
console.log(t.get(0).dim); // [2]

// You can use list indices as well.
console.log(t.get(["RD", "GA"], "F").dim); // [2]

// List indices can also be in number form.
console.log(t.get([0, 2], 1).dim); // [2]
```

### Adding margins

```js
var sum = function(a) {
  return a.reduce(function(x, y) { return x + y });
};

var prod = function(a) {
  return a.reduce(function(x, y) { return x * y });
};

var t = xtabs.table(data, "department", "gender");

// This adds a row 'Sum'.
var t_ = xtabs.addMargins(t, 0, { n: "Sum", f: sum });
console.log(t_.get("Sum", "M")); // 4
console.log(t_.get("Sum").array); // [4, 1]

// This adds a column 'Sum'.
var t_ = xtabs.addMargins(t, 1, { n: "Sum", f: sum });
console.log(t_.get("RD", "Sum")); // 3
console.log(t_.get(undefined, "Sum").array); // [3, 0, 2]

// This adds both a row 'Sum' and a column 'Sum'.
var t_ = xtabs.addMargins(t, [0, 1], { n: "Sum", f: sum });
console.log(t_.get("Sum", "Sum")); // 5

// This adds 'Sum' and 'Prod' rows and a 'Sum' column.
var t_ = xtabs.addMargins(t, [0, 1],
  [[{ n: "Sum", f: sum }, { n: "Prod", f: prod }], [{ n: "Sum", f: sum }]]);
```

### Proportions of a table

```js
var t = xtabs.table(data, "department", "gender");

// Proportions calculated in relation to all data.
var t_ = xtabs.prop(t);
console.log(t_.get("RD").array); // [0.4, 0.2]

// Proportions calculated in relation to rows.
var t_ = xtabs.prop(t, 0);
console.log(t_.get("RD").array); // [2/3, 1/3]

// Proportions calculated in relation to columns.
var t_ = xtabs.prop(t, 1);
console.log(t_.get(undefined, "M").array); // [0.5, 0, 0.5]
```

## API

### xtabs.factor(x, [useNull])

Returns a factor represented as a JavaScript array with a `levels` property. You may refer to R's factor to better understand it. If `useNull` is true, then `null` is counted as level too, this simulates R's _factor not excluding NA's_ behavior.

### xtabs.isFactor(o)

Checks if `o` is a factor.

### xtabs.asString(factor)

Converts back a factor to its string representation.

### xtabs.table(x, [[variable, ...], useNull])

Creates a cross tabulation.

If `x` is an array or factor, it is being used as the data source for the tabulation.

If `x` is an object with array/factor properties, then subsequent `variables` are provided as tabulation variables. For example:

```js
xtabs.table(employees, "department", "gender")
```

The above means that __employees__ is the data source (a table in fact) containing __department__ and __gender__ data, and you want to make a cross tabulation by _department_ and then by _gender_. The result in this particular case is a two-dimensional table, sort of like this:

```
                gender
department    M        F
   RD         2        1
   HR         0        0
   GA         2        0
```

For more about behaviors about cross tabulation, you can refer to R's `xtabs` function (Hence the name of this project).

If `useNull` is true, then `null` is counted too.

### xtabs.addMargins(table, margins, fun)

Add margins to a table. For a two-dimensional table, that means adding rows and columns, margin 0 represents rows, margin 1 represents columns. `fun` is the function to apply. E.g:

```
Given the following table:

                gender
department    M        F
   RD         2        1
   HR         0        0
   GA         2        0

After adding a margin 0 using a sum function, you will get:

                gender
department    M        F
   RD         2        1
   HR         0        0
   GA         2        0
   Sum        4        1

If you add a margin 1 instead, you will get:

                gender
department    M        F      Sum
   RD         2        1       3
   HR         0        0       0
   GA         2        0       2
```

You can add multiple margins at once, or apply multiple functions at once, or both. If you want to add multiple margins at once, you pass in an array of margins to be added in order, instead of a single margin. If you want to apply multiple functions, you can provide a list of function objects (See [Adding margins](#adding-margins)) per margin. Functions are applied in the same order the margins are provided.

### xtabs.prop(table, margin)

Return a new table with proportions according to `margin`. If `margin` is undefined or null, then proportions are calculated in relation of the whole table. See [Proportions of a table](#proportions-of-a-table) for examples of how to use it. Also refer to the following diagrams:

```
Original table:
                gender
department    M        F
   RD         2        1
   HR         0        0
   GA         2        0

Proportions in relation to rows:
                gender
department    M        F
   RD        2/3      1/3
   HR        NaN      NaN
   GA        2/2      0/2

Proportions in relation to columns:
                gender
department    M        F
   RD        2/4      1/1
   HR        0/4      0/1
   GA        2/4      0/1

Proportions in relation to whole:
                gender
department    M        F
   RD        2/5      1/5
   HR        0/5      0/5
   GA        2/5      0/5
```

## Class: xtabs.Table

This is what you get when you call [xtabs.table](#xtabstablex-variable--usenull), however, this class is not directly exposed to you.

### table.dim

The dimensions of the table. It's an array with each dimension's length.

### table.dimnames

An array containing each dimension's names, each one has a `dim` property indicating the dimension's name and a `names` property indicating each level's name in the dimension.

### table.array

The array representing the table. This is underline data structure of the table.

### table.get([level | list of levels, ...])

Gets data out of the table. Basically, you pass in each variable's index or indices to get the data out. You can also pass in `undefined` as a special way to indicate that you want all the data of this variable. You can refer to the [Examples](#examples) section for the various ways to use this method.

## License

(The MIT License)

Copyright (c) 2013 Seth Yuan

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: sethyuan/xtabs

repo_name: sethyuan/xtabs


text:
---
layout: ziplab
description: Learn how to launch a Virual Machine using Oracle Cloud Infrastructure Computer Service
tags: Oracle Cloud, Oracle Cloud Infrastructure, OCI, Virtual Machine, VM, Virtual Cloud Network, VCN
permalink: /data-management-library/autonomous-database/ziplabs/2019/oci-vm/index.html
---
# Create a Virtual Machine Instance Using Oracle Cloud Infrastructure Compute #

## Before You Begin ##
This 20-minute tutorial shows you how to create a Virtual Machine (VM) instance using Oracle Cloud Infrastructure (OCI) Compute Service. Before you can create a VM, you'll create a Virual Cloud Network (VCN).

### Background ###
Oracle Cloud Infrastructure Compute Service lets you create Virtual Machine instances on which you can run your mission-critical applications with high availability.

Before you can launch an instance, you need to have a VCN to launch it into. In the VCN, you launch the instance into a subnet. A subnet is a subdivision of your VCN that you define in a single Availability Domain. The subnet directs traffic according to a route table. Access the instance can be done over the internet using its public IP address, so your route table will direct traffic to an Internet Gateway. The subnet also uses a security list to control traffic in and out of the instance.

### What Do You Need? ###
* Access to an instance of Oracle Cloud Infrastructure Compute Service
* A VCN in the compartment in which the instance will run
* An SSH key (provided)

## Create a Virtual Cloud Network ##
1. Sign in to the Oracle Cloud.
2. Click the menu icon to expand the menu on the left edge of the screen.
3. Select **Networking**.
4. Click **Virtual Cloud Networks**.

    ![](img/OCIMenu1.png)

    [Description of the illustration OCIMenu1.png](files/OCIMenu1.txt)

5. Select the **root** compartment from the Compartment dropdown menu.

    ![](img/Compartment.png)

    [Description of the illustration Compartment.png](files/Compartment.txt)

6. Click the button **Create Virtual Cloud Network**.
7. In the Create Virtual Cloud Network dialog box, enter the following information:
     * **Name**: `user01_Network`
     * **Create in Compartment**: Select the root compartment.
     * Select **Create Virtual Cloud Network Plus Related Resources**.
     * Ensure the box to **Use DNS Host Names in this VCN** is checked.
     * Scroll down. The box to **View detail page after this resource is created** should also be checked.
8. Click the button **Create Virtual Cloud Network**. The dialog box then confirms the details of the VCN.
9. Click **Close**.
     * You should be taken to a page detailing your new VCN.
     * Notice its state is `Available`.

## Create a Virtual Machine Instance ##
1. Click the OCI menu icon to expand the menu on the left edge of the screen.
2. Select **Compute**.
3. Click **Instances**.

    ![](img/OCIMenu2.png)

    [Description of the illustration OCIMenu2.png](files/OCIMenu2.txt)

4. Ensure the **root** compartment is still selected in the Compartment dropdown menu.

    ![](img/Compartment.png)

    [Description of the illustration Compartment.png](files/Compartment.txt)

5. Click the button **Create Instance**.
6. On the Create Compute Instance page, enter the following information:
     * **Name**: Keep the default value.
     * **Operating System**: `Oracle Linux 7.7` (Or the latest Oracle Linux).
     * **Availability Domain**: Keep the default value.
     * **Instance Type**: `Virtual Machine`
     * **Instance Shape**: `VM.Standard2.1 (1 Core OCPU, 15 GB Memory)`
     * **Configure Networking**: Ensure your VCN compartment is set to **root** and VCN set to what you created earlier, `user01_Network`. Keep the default values for the remaining fields.
     * **Boot Volume**: Keep the default values. The boxes should remain unchecked.
     * **Add SSH Key**: Select `Paste SSH Keys`. An example SSH key you can paste is:

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDVNPh09u35ejTZun3FNEGhrjL/CovPsHAh79pN0QVprxEJaW2zjmaBZF1Q6lkuyTRvraomIlduCYxrlnwCe8oyER5dY1zuJATWm7ZiqgsvIkhj8L+ea9dBZRvFvcnFsNFnt4ALZYkW2nB2EeTdvqVMHERjFKfbRMCcO0dusmBUEsvaaqLtrvVuHBjwoXIDKkT/PFkix4DWRZRkZIjmZ/y9kwrHO4W1FYsFi4LP1xIB1c9y2H4w0SBXAMv4NCSFEIgWPQly2NywMsgEbddjW+zPz+7YjYqjWfz5Fgchu7+N1gejsIdzg1/aLvDpze6TN9xLcZx5gt04jA3TR+xfs2Ab Tim@Corsair

    ![](img/pastesshkey.png)

    [Description of the illustration pastesshkey.png](files/pastesshkey.txt)

7. Click **Create** at the bottom of the page.
     * While the instance is being created, its status displays as `PROVISIONING`.
     * The status changes to `RUNNING` when the instance is fully operational.

## Want to Learn More? ##
* [Oracle Cloud Infrastructure Training](https://education.oracle.com/learn/iaas/pPillar_640) from Oracle University
* [Oracle Cloud Infrastructure 2018 Architect Associate Certification](https://education.oracle.com/es/oracle-cloud-infrastructure-2018-architect-associate/pexam_1Z0-932) from Oracle University

repository: jdavies/learning-library

repo_name: jdavies/learning-library


text:
The Topic Modeling Neural Toolkit (TMNT) is a software library that enables training
topic models as neural network-based variational auto-encoders.

Current stable version is: 0.6.3

Documentation can be found here: https://tmnt.readthedocs.io/en/stable/

The latest development version documentation is here: https://tmnt.readthedocs.io/en/latest

repository: mitre/tmnt

gha_language: Python

repo_name: mitre/tmnt


text:
# RenderSystem

Renders Entities. Buckets and sorts Entities in render passes, manages render
states, performs draw calls.

[TOC]

The render system has many knobs and switches that allow it to be configured,
but still tries to provide a simple interface that remains largely hands-off for
common use cases.

## Backends

The render system has an abstract-like interface, which allows you to choose
from various backends:

* FPL
* Ion
* Mock

The backend is decided in the BUILD file by pointing at one of the corresponding
build targets.  The 'render_system' target is header-only.

## Definition

Like all components, renderables are configured by adding a [RenderDef]
component to an entity's json file.

## Render passes

Render passes determine the overall render state and high level render order.

* Pano: a special use pass for stereoscopic pano images.
* Opaque: intended for opaque 3D models that draw into the depth buffer.
    * Blending disabled, zwrite and ztest enabled.
* Main:
    * Lerp blend based on src alpha, zwrite disabled, ztest enabled.
* OverDraw: a special use pass to draw over everything in the scene.
    * Lerp blend based on src alpha, zwrite and ztest disabled.
* Debug: a special use pass for rendering debug information.
* Invisible: a special use pass whose contents are not drawn.

### Custom render passes

If you need to set a specific render state that is not included in the
predefined render passes or draw things in a very specific order, you can add
entities into custom render passes.

## Meshes

There are two ways to define a mesh: by defining a quad, or by loading an FBX
file.

### Quads

By using a QuadDef, you can create a simple quad mesh, optionally with rounded
corners and auto-generated texture coordinates.  Quads are also affected by a
[deform component]

### FBX files

Through FPL's mesh_pipeline, Lullaby can also load meshes from
[FBX](http://www.autodesk.com/products/fbx/overview) files.  This import path
allows complex meshes to be loaded into the render system.

Meshes loaded from FBX files are not affected by deform components.

## Shaders

Shaders can be loaded into the render system from .fplshader files, which simply
contain the source for both the vertex and fragment shaders.

### Attributes

Vertex attributes follow the FPL naming convention:

* aPosition: vec3
* aNormal: vec3
* aTangent: vec4 (xyz: tangent vector, w: handedness)
* aTexCoord: vec2
* aTexCoordAlt: vec2
* aColor: vec4 (source: normalized ubyte[4])
* aBoneIndices: [i]vec4 (source: ubyte[4])
* aBoneWeights: vec4 (source: normalized ubyte[4])

### Uniforms

Since Lullaby was based on the FPL renderer, by default it uses FPL's uniform
naming convention (hence "model_view_projection" and not
"clip_from_entity_matrix").

The following uniforms are set automatically by the render system:

* color: vec4
  * Normalized rgba.
* uv_bounds: vec4
  * xy: offset, zw: bounds.
* model_view_projection: mat4
  * AKA clip_from_entity_matrix
* model: mat4
  * AKA world_from_entity_matrix
* uIsRightEye: int
  * 1 when drawing right eye, otherwise 0.
* texture_unit_%d: texture
* bone_transforms: array of 3 vec4s (representing mat3x4[])
* camera_pos: vec3
  * Camera position in world space.

## Textures

Textures can be loaded from various file formats, though only a few are
supported by both backends:

* TGA (FPL, Ion)
* WEBP (FPL, Ion)
* PNG (FPL, Ion)
* JPEG (Ion)
* BMP (Ion)
* PSD (Ion)
* GIF (Ion)
* HDR (Ion)
* PIC (Ion)
* ASTC (FPL)
* PKM (FPL)
* KTX (FPL)

### Atlases

Multiple images can be combined into a single texture atlas using the
fpl_texture_atlas build command.  You can reference individual images by using
an all-caps version of the filename without its extension: eg toggleoff.png
would be referred to as TOGGLEOFF.

## Draw order

Within a render pass, entities can be drawn in a sorted order.  This is most
useful for blend-enabled render passes, but can be configured separately for
each render pass using
[SetSortMode]

By default, the Main render pass is sorted using kSortOrderIncreasing.

### Default sort order

The two kSortOrder sort modes are simply a compare of entities' sort_order key.
By default, this is calculated based on the scene graph so that parents draw
before children, and siblings are drawn in linear order.  This can be tweaked
slightly in the RenderDef by setting the sort_order_offset, which will replace
the sibling order when calculating the sort_order.

The calculation used was chosen to group trees tightly, so that root-level trees
will always draw together, but within a tree the order remains top-down.

```c++
using SortOrder = uint32_t;
const int kNumBitsPerDepth = 4;
const int kRootShift = 8 * sizeof(SortOrder) - kNumBitsPerDepth;
if (parent) {
  default_sort_order = parent_sort_order |
                       (offset << kRootShift - depth * kNumBitsPerDepth);
} else {
  default_sort_order = (offset << kRootShift);
}
```

repository: xinfushe/lullaby

repo_name: xinfushe/lullaby


text:
---
date: 22 August 2011
categories: advanced, guides
author: Mason Wendell
summary: Sass gladly lets you add calculations and logic in a way that CSS would never abide. But does that mean you should go around adding and dividing just anywhere? Find out how you can use pure Sass functions to make reusable logic more useful and your working Sass file more readable.
---

# Using pure Sass functions to make reusable logic more useful

Sass gladly lets you add calculations and logic in a way that CSS would never abide. But does that mean you should go around adding and dividing just anywhere? Find out how you can use pure Sass functions to make reusable logic more useful and your working Sass file more readable.

## Sass adds Functions

Sass has [mixins](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixins), we all know that. And because they accept arguments I always thought of them as Sass's version of functions. Pretty sweet. But when [Sass 3.1.0](http://sass-lang.com/docs/yardoc/file.SASS_CHANGELOG.html#310) came out it added a feature that blew that notion apart. Yeah, you guessed it ... actual [functions](http://sass-lang.com/docs/yardoc/file.SASS_CHANGELOG.html#sassbased_functions). Instead of outputting lines of Sass the way mixins do, functions return a value. This makes them a super powerful behind-the-scenes player in a lot of my favorite Sass recipes.

## Mixins and Functions: Kissing Cousins

Functions and mixins are very similar in nature. Because they can both accept variables, you might end up creating a mixin when what you really need is a function. In the following examples, we review the creation, usage and output of both a mixin and a function.

### Exhibit A: Mixin

The following mixin can accept arguments and do calculations. The output of this mixin (in this case) is a CSS rule and will be unfurled where ever you `@include` it.

    :::scss
    @mixin my-padding-mixin($some-number) {
      padding: $some-number;
    }

Now we use the `@include` directive to insert our mixin's code.

    :::scss
    .my-module {
      @include my-padding-mixin(10px);
    }

And here is the output CSS code.

    :::css
    .my-module {
      padding: 10px;
    }

### Exhibit B: Function

A function is very similar to a mixin, however the output from a function is a single value. This can be any Sass [data type](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#data_types), including: numbers, strings, colors, booleans, or lists.

The following function can accept 2 arguements, `$some-number` and `$another-number`. The value returned are those two variables added together.

    :::scss
    @function my-calculation-function($some-number, $another-number){
      @return $some-number + $another-number
    }

This time around we replace the common value of the `padding` property with what a snippet of [SassScript](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#sassscript) to call our function, pass it the arguments and include in our output CSS code.

    :::scss
    .my-module {
      padding: my-calculation-function(10px, 5px);
    }

And here is the output CSS code.

    :::css
    .my-module {
      padding: 15px;
    }

### Readable, DRY Sass

As you can see, functions help you write more readable and DRY Sass by letting you move your reusable logic out of specific declarations and even out of your mixins. This can make all the difference in the world when you're working on something that's even a little bit complex.

## Using Functions

I love how writing Sass lets me think like a programmer when I'm writing CSS. It's very satisfying to refactor and abstract the methods behind successful techniques to make them reusable and portable for the next project.

**Pro tip**: Use functions when you need to calculate a value that may be reused somewhere else.

In Ethan Marcotte's lovely new book [*Responsive Web Design*](http://www.abookapart.com/products/responsive-web-design), he stresses the formula for calculating the percent value for a width so you can achieve a fluid layout based on a reference design made using pixels.

    target / context = result

So if you have a container that's 1000px wide, and a module that's designed to be 650px wide, that calculation becomes:

    650px / 1000px = 65%

That's as clear a case for a function as I can imagine. It would be overkill to work that logic into each mixin for a site, and even worse to do those calculations in line. So in a recent project I just created a little function, like so:

    :::scss
    @function calc-percent($target, $container) {
      @return ($target / $container) * 100%;
    }

**Pro tip**: Create short-names for functions and mixins that you will be using often.

For example, for the above function, I created the short-name below. It simply collects the needed arguments, and passes it along to its sister with the longer name, and then returns the value.

    :::scss
    @function cp($target, $container) {
      @return calc-percent($target, $container);
    }

With that in place, I can easily remove the mechanics of that process out of my view, and focus on writing my Sass using the values I already know.

    :::scss
    .my-module {
      width: calc-percent(650px, 1000px);
    }

or

    :::scss
    .my-module {
      width: cp(650px, 1000px);
    }

Either of which simply output this CSS.

    :::css
    .my-module {
      width: 65%;
    }

This is a simple example, but I think it's a pretty useful one, especially if you'd rather have Sass do the math for you. Once you start pulling a few calculations into Sass functions, you'll start to see how they open up new ways to write lighter, cleaner Sass that's more readable.

## Homework: Dig Deeper by reading the source code

Sass functions have become an indispensable tool for me in all my latest projects. I've heard from many others that is the case for them as well. If you dig into [the](http://compass-style.org/reference/blueprint/grid/) [source](http://compass-style.org/reference/compass/layout/grid_background/) [code](http://compass-style.org/reference/compass/typography/vertical_rhythm/) of [Compass](http://www.abookapart.com/products/responsive-web-design) you will see that a lot of real heavy lifting is done by some well-placed functions.

extension: markdown

gha_language: SCSS


text:
# behavortreely.py

A behavior tree implementation in Python. It runs behavior trees defined in JSON format and will trigger actions in your code.

**Note:** this is the first full working draft of behavortreely.py, the example, especially the JSON is very place holder. I intend to update this in the coming days and weeks to be better documented. Probably just cursed myself by by saying that. Ah well.

## Overview

1) Prepare your tree JSON.
2) Instantiate a behavortreely BehaviorTree by loading your tree JSON.
3) Register your action handlers, condition handlers, and selector handlers if needed.
4) Run the tree: once, many times, ongoing, etc.
    - Run via start() activates the tree's ongoing tick
    - Or run via tick() run it once

## Example

    test_json = """
    {
        "nodeName":"root of behavior XYZ",
        "goal":"to test treely",
        "description":"this is the root",
        "slug":"root",
        "type":"LimitTime",
        "limit":7,
        "weight":0,
        "time_started":null,
        "tries":null,
        "selectorHandler":null,
        "conditionHandler":null,
        "actionHandler":null,
        "children":[
            {
                "nodeName":"try to win",
                "slug":"try-your-best0",
                "description":"keep trying your best",
                "type":"Selector",
                "weight":0.5,
                "parameters":[],
                "children":[
                    {
                        "nodeName":"try to win1",
                        "slug":"try-your-best1",
                        "description":"keep trying your best1",
                        "type":"Action",
                        "weight":0.6,
                        "parameters":[],
                        "children":[],
                        "successHandler":null,
                        "failHandler":null,
                        "selectorHandler":null,
                        "conditionHandler":null,
                        "actionHandler":"do a test action",
                        "parentNodeSlug":"root"

                    },
                    {
                        "nodeName":"try to win2",
                        "slug":"try-your-best2",
                        "description":"keep trying your best2",
                        "type":"Action",
                        "weight":0.5,
                        "parameters":[],
                        "children":[],
                        "successHandler":null,
                        "failHandler":null,
                        "selectorHandler":null,
                        "conditionHandler":null,
                        "actionHandler":"do a test action",
                        "parentNodeSlug":"root"

                    },
                    {
                        "nodeName":"try to win3",
                        "slug":"try-your-best3",
                        "description":"keep trying your best3",
                        "type":"Action",
                        "weight":0.9,
                        "parameters":[],
                        "children":[],
                        "successHandler":null,
                        "failHandler":null,
                        "selectorHandler":null,
                        "conditionHandler":null,
                        "actionHandler":"do a test action",
                        "parentNodeSlug":"root"

                    }
                ],
                "successHandler":null,
                "failHandler":null,
                "selectorHandler":"do a test selector",
                "conditionHandler":null,
                "actionHandler":null,
                "parentNodeSlug":"root"

            }
        ]
    }
        """

        def condition_test():
            print("running a condition")
            return True

        def action_test():
            print("running an action")
            return True

        def selector_test(choices, blackboard, tree):
            # could do a lot more than this to provide proper slug from choices
            return choices[0]

        print("starting as script...")

        # create the behavior tree instance
        bt = BehaviorTree(test_json)

        # register any needed actions, conditions, or selectors referred to in the JSON
        bt.actions["do a test action"] = action_test
        bt.conditions["do a test condition"] = condition_test
        bt.selectors["do a test selector"] = selector_test

        # use start() instead of tick() to keep the behavior tree running
        # bt.start()

        # use tick() to run the tree once
        bt.tick()

repository: zxsted/behaviortreely

repo_name: zxsted/behaviortreely


text:
# How to use CDSW

## Accessing to CDSW

Simply, you may access to CDSW via the link on Cloudera Manager.

```
$ ./get_cluster_ip.sh ${CLUSTER_CONF}
[Cloudera Manager]
Public IP: <IP_ADDRESS>    Private IP: <IP_ADDRESS>
CM URL: http://<IP_ADDRESS>:7180

[Nodes]
    master    Public IP:   <IP_ADDRESS>    Private IP:       <IP_ADDRESS>
    worker    Public IP:     <IP_ADDRESS>    Private IP:       <IP_ADDRESS>
    worker    Public IP:    <IP_ADDRESS>    Private IP:       <IP_ADDRESS>
    worker    Public IP:    <IP_ADDRESS>    Private IP:       <IP_ADDRESS>
      cdsw    Public IP:    <IP_ADDRESS>    Private IP:        <IP_ADDRESS>

[CDSW]
CDSW URL: http://cdsw.<IP_ADDRESS>.xip.io

[SSH Tunnel for Dynamic Port Forwarding]
ssh -i your-aws-sshkey.pem -D 8157 -q<EMAIL_ADDRESS>
$ ssh -i your-aws-sshkey.pem -D 8157 -q<EMAIL_ADDRESS>```

After above, you can access to http://cdsw.<IP_ADDRESS>.xip.io from your web browser via SSH SOCKS Proxy (See https://www.cloudera.com/documentation/director/latest/topics/director_security_socks.html).

## Logging into CDSW

### Secure Cluster
1. Access to CDSW from browser.
2. Click "**Sign Up for a New Account**" and create a new account. This username doesn't relate to existing OS users or Kerberos principals. Therefore you can create any users.
    - Full Name: (anything)
    - Username: (anything)
    - Email:  (anything)
    - Password: (anything)

3. After logging in, authenticate against your cluster’s Kerberos KDC by going to the top-right dropdown menu and clicking **Settings** -> **Hadoop Authentication**. You can use the prepared principals `user<N>@HADOOP`. Please read the "User and Authentication" section of [README](../README.md). In case you use `user1`:

    - Principal: user1@HADOOP
    - Password: user1

### Unsecure Cluster
1. Access to CDSW from browser.
2. Click "**Sign Up for a New Account**" and create a new account. This username *DOES* relate to existing OS users. In case you use `user1`:

    - Full Name: (anything)
    - Username: user1
    - Email: (anything)
    - Password: (anything)
3. It's okay to remain blank in **Settings** -> **Hadoop Authentication**.

## Setting up for GPU

### Custom Engine Image

You need to have a custom CUDA-capable Engine Image. You can refer to my [Notes on building the image](./cdsw-engine.md) as well as Cloudera Documentation below.

**Cloudera Documentaion:**
 [Using NVIDIA GPUs for Cloudera Data Science Workbench Projects](https://docs.cloudera.com/documentation/data-science-workbench/1-6-x/topics/cdsw_gpu.html#custom_cuda_engine)

You may want to access the latest information:
[Using NVIDIA GPUs for Cloudera Data Science Workbench Projects](https://docs.cloudera.com/documentation/data-science-workbench/latest/topics/cdsw_gpu.html#custom_cuda_engine)

### CDSW Settings

#### Engine Images

**Admin** -> **Engines** -> **Engine Images**

I built a sample CUDA-capable engine image. You may use [my image](https://hub.docker.com/r/yoshiyukikono/cdsw-cuda/) (`yoshiyukikono/cdsw-cuda:8`).

**Note:** When you start a new session for the first time, it will take pretty longer time than usual beause the above engine image is downloaded at that time.

##### Jupyter notebook
If you want to use Jupyter notebook with custome engine images, you need to add an Editor entry.

1. Under Engine Images, click the Edit button for the customized engine image that you want to configure for Jupyter Notebook.
1. Click New Editor.
1. Complete the fields:

- Name: Enter `Jupyter Notebook`.
- Command: Enter the command to start Jupyter Notebook. This command is:
```
/usr/local/bin/jupyter-notebook --no-browser --ip=<IP_ADDRESS> --port=${CDSW_APP_PORT} --NotebookApp.token= --NotebookApp.allow_remote_access=True --log-level=ERROR
```

#### Maximum GPUs
**Admin** -> **Engines** -> **Engine Profiles** -> **Maximum GPUs per Session/Job**

You must increase the number from 0 to 1 or higher.

#### Memory (GiB)
**Admin** -> **Engines** -> **Engine Profiles**

The default memory size (2GiB) is not enough even for installing deep learning packages. You need to have at least 4 GiB.

For more details, please read the Cloudera documentation mentioned above.

## Testing GPU setup

To confirm if GPU is used properly on your environment, please refer to [Notes on building the image](./cdsw-engine.md).

## Checking CDSW Status

On the CDSW node, you can check the status of CDSW using `cdsw status`.
The following example is the output of `cdsw status` after installation finished (details are different depending on the version).

```
$ sudo cdsw status
cdsw status
Sending detailed logs to [/tmp/cdsw_status_HAmpRL.log] ...
CDSW Version: [1.3.0:9bb84f6]
OK: Application running as root check
OK: Sysctl params check
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|        NAME       |   STATUS   |           CREATED-AT          |   VERSION   |   EXTERNAL-IP   |          OS-IMAGE         |         KERNEL-VERSION         |   GPU   |   STATEFUL   |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|   ip-10-0-0-167   |    True    |   2018-01-28 14:40:09+00:00   |   v1.6.11   |       None      |   CentOS Linux 7 (Core)   |   3.10.0-514.16.1.el7.x86_64   |    0    |     True     |
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1/1 nodes are ready.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                    NAME                   |   READY   |    STATUS   |   RESTARTS   |           CREATED-AT          |     POD-IP     |    HOST-IP     |   ROLE   |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
|             etcd-ip-10-0-0-167            |    1/1    |   Running   |      0       |   2018-01-28 14:41:34+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |   None   |
|        kube-apiserver-ip-10-0-0-167       |    1/1    |   Running   |      0       |   2018-01-28 14:40:08+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |   None   |
|   kube-controller-manager-ip-10-0-0-167   |    1/1    |   Running   |      0       |   2018-01-28 14:40:07+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |   None   |
|         kube-dns-3911048160-krs31         |    3/3    |   Running   |      0       |   2018-01-28 14:40:24+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |   None   |
|              kube-proxy-lzq95             |    1/1    |   Running   |      0       |   2018-01-28 14:40:24+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |   None   |
|        kube-scheduler-ip-10-0-0-167       |    1/1    |   Running   |      0       |   2018-01-28 14:40:07+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |   None   |
|      node-problem-detector-v0.1-h8mbg     |    1/1    |   Running   |      0       |   2018-01-28 14:41:48+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |   None   |
|              weave-net-91xmq              |    2/2    |   Running   |      0       |   2018-01-28 14:40:24+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |   None   |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
All required pods are ready in cluster kube-system.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|                  NAME                  |   READY   |     STATUS    |   RESTARTS   |           CREATED-AT          |      POD-IP     |    HOST-IP     |           ROLE           |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|         cron-1906902965-qxnjd          |    1/1    |    Running    |      0       |   2018-01-28 14:41:47+00:00   |    <IP_ADDRESS>   |   <IP_ADDRESS>   |           cron           |
|          db-1165222207-99m93           |    1/1    |    Running    |      0       |   2018-01-28 14:41:47+00:00   |    <IP_ADDRESS>   |   <IP_ADDRESS>   |            db            |
|        db-migrate-9bb84f6-6lhbr        |    0/1    |   Succeeded   |      0       |   2018-01-28 14:41:47+00:00   |    <IP_ADDRESS>   |   <IP_ADDRESS>   |        db-migrate        |
|           engine-deps-ctmvq            |    1/1    |    Running    |      0       |   2018-01-28 14:41:47+00:00   |    <IP_ADDRESS>   |   <IP_ADDRESS>   |       engine-deps        |
|   ingress-controller-684706958-zl9l3   |    1/1    |    Running    |      0       |   2018-01-28 14:41:47+00:00   |    <IP_ADDRESS>   |   <IP_ADDRESS>   |    ingress-controller    |
|        livelog-2502658797-ltqg5        |    1/1    |    Running    |      0       |   2018-01-28 14:41:47+00:00   |    <IP_ADDRESS>   |   <IP_ADDRESS>   |         livelog          |
|      reconciler-2738760185-lqlmz       |    1/1    |    Running    |      0       |   2018-01-28 14:41:47+00:00   |    <IP_ADDRESS>   |   <IP_ADDRESS>   |        reconciler        |
|       spark-port-forwarder-mx286       |    1/1    |    Running    |      0       |   2018-01-28 14:41:48+00:00   |    <IP_ADDRESS>   |   <IP_ADDRESS>   |   spark-port-forwarder   |
|          web-3320989329-698m4          |    1/1    |    Running    |      0       |   2018-01-28 14:41:48+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |           web            |
|          web-3320989329-cqtpz          |    1/1    |    Running    |      0       |   2018-01-28 14:41:48+00:00   |    <IP_ADDRESS>   |   <IP_ADDRESS>   |           web            |
|          web-3320989329-gwmfm          |    1/1    |    Running    |      0       |   2018-01-28 14:41:48+00:00   |   <IP_ADDRESS>   |   <IP_ADDRESS>   |           web            |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
All required pods are ready in cluster default.
All required Application services are configured.
All required config maps are ready.
All required secrets are available.
Persistent volumes are ready.
Persistent volume claims are ready.
Ingresses are ready.
Checking web at url: http://cdsw.<IP_ADDRESS>.xip.io
OK: HTTP port check
Cloudera Data Science Workbench is ready!
```

repository: YoshiyukiKono/cloudera-demo-env

gha_language: Shell

repo_name: YoshiyukiKono/cloudera-demo-env


text:
## Creating Provisoning Requests Programmatically

The most common way to provision a VM is via the CloudForms WebUI, i.e.

![screenshot](images/screenshot6.png)

We can also. however, initiate the provisioning process programmatically by calling `$evm.execute` to run the method `create_provision_request`. This method takes a number of arguments, which correspond to the argument list for the EVMProvisionRequestEx SOAP API call. A typical call to provision a VM into RHEV might be:

```
# arg1 = version
args = ['1.1']

# arg2 = templateFields
args << {'name'         => 'rhel7-generic',
		 'request_type' => 'template'}

# arg3 = vmFields
args << {'vm_name'   => 'rhel7srv010',
		 'vlan'      => 'public',
		 'vm_memory' => '1024'}

# arg4 = requester
args << {'owner_email'      =><EMAIL_ADDRESS>
		 'owner_first_name' => 'Peter',
		 'owner_last_name'  => 'McGowan'}

# arg5 = tags
args << nil

# arg6 = additionalValues (ws_values)
args << {'disk_size_gb' => '50',
			'mountpoint' => '/opt'}

# arg7 = emsCustomAttributes
args << nil

# arg8 = miqCustomAttributes
args << nil

request_id = $evm.execute('create_provision_request', *args)
```
### Argument List
The arguments to the `create_provision_request` call are described below. The arguments match the fields in the Provisioning Dialog (and the values from the corresponding YAML template), and any arguments that are set to **required: true** in the Dialog YAML, but don't have a **:default:** value, should be specified. The exception for this is for sub-dependencies of other options, for example if **:provision\_type:** is _pxe_ then the sub-option **:pxe\_image\_id:** is mandatory. If the **:provision\_type:** value is anything else then **:pxe\_image\_id:** is not relevant.

In ManageIQ versions prior to _Capablanca_ the arguments were specified as a string, with each value separated by a pipe ('|') symbol, i.e.

```
"vm_name=rhel7srv010|vlan=public|vm_memory=1024"
```

With _Capablanca_ (CloudForms Management Engine 5.5) however this syntax has been deprecated, and the options within each argument type should be defined as a hash as shown in the example above. This is more compatible with the equivalent RESTful API call to create a provisioning request.

The _value_ for each hashed argument pair should always be a string, for example `{'number_of_vms' => '4'}` rather than `{'number_of_vms' => 4}`.

#### version

Interface version. Should be set to 1.1

#### templateFields

Fields used to specify the VM or Template to use as the source for the provisioning operation. Supply a _guid_ or _ems\_guid_ to protect against matching same-named templates on different Providers within CloudForms Management Engine. The **request\_type** field should be set to one of: **template**, **clone\_to\_template**, or **clone\_to\_vm** as appropriate. A normal VM provision from template is specified as:

```
'request_type' => 'template'
```

#### vmFields

Allows for the setting of properties from the **Catalog**, **Hardware**, **Network**, **Customize**, and **Schedule** tabs in the Provisioning Dialog. Some of these are Provider-specific, so when provisoning an OpenStack Instance for example, we need to specify the **instance\_type**

```
# arg2 = vmFields
arg2 = {'number_of_vms'    => '3',
		 'instance_type'   => '1000000000007', # m1.small
		 'vm_name' 		 => "#{$instance_name}",
		 'retirement_warn' => "#{2.weeks}"}
args << arg2
```

#### requester

Allows for the setting of properties from the **Request** tab in the Provisioning Dialog. **owner_email**, **owner\_first\_name** and **owner\_last\_name** fields are required fields.

#### tags

Tags to apply to newly created VM, e.g.

```
{'server_role' => 'web_server',
 'cost_centre' => '0011'}
```

#### additionalValues (aka ws_values)

Additional values, also known as ws\_values, are name-value pairs stored with a provision request, but not used by the core provisioning code. These values are usually referenced from automate methods for custom processing. They are added into the Request Options Hash, and can be retrieved as a hash from:

```
$evm.root['miq_provision'].options[:ws_values]
```

#### emsCustomAttributes

Custom Attributes applied to the virtual machine through the Provider as part of provisioning. Not all Providers support this, although VMware does support native vCenter Custom Attributes, which if set are visible both in CloudForms and in the vSphere/vCenter UI.

#### miqCustomAttributes

Custom Attributes applied to the virtual machine and stored in the CloudForms Management Engine database as part of provisioning. These VMDB-specific Custom Attributes are displayed on the VM details page (see also [A More Advanced Example](../chapter5/a_more_advanced_example.md)).

### Setting Placement Options

The Rails code that implements the `create_provision_request` call makes the assumption that any non-interactive provision request will be using Automatic placement, and it sets `options[:placement_auto] = [true, 1]` as a request option. This also means however that it disregards any **vmFields** options that we may set that are normally found under the **Environment** tab of an interactive provision request, such as `cloud_tenant` or `cloud_network` (these are hidden in the WebUI if we tick **Choose Automatically**).

![screenshot](images/screenshot44.png)

If we try adding one of these (such as `cloud_network`), we see in evm.log:

```
Unprocessed key <cloud_network> with value <"1000000000007">
```
The only way that we can set any of these placement options is to add them to the **additionalValues/ws\_values (arg6)** argument list, and then handle them ourselves in the **CustomizeRequest** stage of the State Machine.

For example, in our call to `create_provision_request` we can set:

```
# arg6 = additionalValues (ws_values)
args << {'cloud_network' => '10000000000031'
		 'cloud_tenant   => '10000000000012'}
```

We can then copy `ManageIQ/Cloud/VM/Provisioning/StateMachines/Methods/openstack_CustomizeRequest` into our own domain, and edit as follows:

```ruby
#
# Description: This method is used to Customize the Openstack Provisioning Request
#
def find_object_for(rsc_class, id_or_name)
  if /\d{13}/.match(id_or_name.to_s)
    # Looks like an ID
    obj = $evm.vmdb(rsc_class, id_or_name.to_s)
  else
    obj = $evm.vmdb(rsc_class).find_by_name(id_or_name.to_s)
  end
  $evm.log(:warn, "Couldn\'t find an object of class #{rsc_class} \
  			with an ID or name matching \'#{id_or_name}\'") if obj.nil?
  obj
end

# Get provisioning object
prov = $evm.root["miq_provision"]
ws_values = prov.options.fetch(:ws_values, {})

if ws_values.has_key?(:cloud_network)
  cloud_network = find_object_for('CloudNetwork', ws_values[:cloud_network])
  prov.set_cloud_network(cloud_network)
end
if ws_values.has_key?(:cloud_tenant)
  cloud_tenant = find_object_for('CloudTenant', ws_values[:cloud_tenant])
  prov.set_cloud_tenant(cloud_tenant)
end

$evm.log("info", "Provisioning ID:<#{prov.id}> Provision Request \
         ID:<#{prov.miq_provision_request.id}> Provision Type: <#{prov.provision_type}>")
```

### Calling create\_provision\_request From a Service Item Definition

One of the most common uses for calling `$evm.execute('create_provision_request')` is from a Service Catalog Item definition.

When we create a new a Service Catalog Item, we select from a drop-down list of available Catalog Item Types. This lists the defined Provider Types, but also an additional type of **Generic**. If we define a Catalog Item using a Provider Type, we pre-configure the Provisioning Dialog options, just as we would if we were provisioning the request interactively. This also includes the **Number of VMs** (`:number_of_vms`) option, and this cannot be changed once the Service Catalog Item is ordered.

If we wish to be able to dynamically select the number of VMs when we order a service, we must use the **Generic** Catalog Item Type, and call our own Automate Method that creates the provision request on-the-fly using `$evm.execute('create_provision_request')`. This can include an updated `:number_of_vms` as an **arg3** value.


text:
# get-changed-files

[![CI status](https://github.com/Ana06/get-changed-files/workflows/Test/badge.svg)](https://github.com/Ana06/get-changed-files/actions?query=event%3Apush+branch%3Amain)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE.txt)

This project is a fork of <https://github.com/jitterbit/get-changed-files>, which supports `pull_request_target`, allow to filter files using regular expressions and removes the ahead check.

## Get All Changed Files

Get all of the files changed/modified in a pull request (`pull_request` or `pull_request_target`) or push's commits.
You can choose to get all changed files, only added files, only modified files, only removed files, only renamed files, or all added and modified files.
These outputs are available via the `steps` output context.
The `steps` output context exposes the output names `all`, `added`, `modified`, `removed`, `renamed`, and `added_modified`.

## Usage

See [action.yml](action.yml)

```yaml
- uses<EMAIL_ADDRESS>  with:
    # Format of the steps output context.
    # Can be 'space-delimited', 'csv', or 'json'.
    # Default: 'space-delimited'
    format: ''
    # Filter files using a glob filter
    filter: '*'
```

## Scenarios

- [get-changed-files](#get-changed-files)
  - [Get All Changed Files](#get-all-changed-files)
  - [Usage](#usage)
  - [Scenarios](#scenarios)
    - [Get all changed files as space-delimited](#get-all-changed-files-as-space-delimited)
    - [Get all changed *.php files as space-delimited](#get-all-changed-php-files-as-space-delimited)
    - [Get all changed *.yml files but exclude .github/*/*.yml files](#get-all-changed-yml-files-but-exclude-githubyml-files)
    - [Get all added and modified files as CSV](#get-all-added-and-modified-files-as-csv)
    - [Get all removed files as JSON](#get-all-removed-files-as-json)
  - [Install, Build, Lint, Test, and Package](#install-build-lint-test-and-package)
  - [License](#license)

### Get all changed files as space-delimited

If there are any files with spaces in them, then this method won't work and the step will fail.
Consider using one of the other formats if that's the case.

```yaml
- id: files
  uses<EMAIL_ADDRESS>- run: |
    for changed_file in ${{ steps.files.outputs.all }}; do
      echo "Do something with this ${changed_file}."
    done
```

### Get all changed *.php files as space-delimited

If there are any files with spaces in them, then this method won't work and the step will fail.
Consider using one of the other formats if that's the case.

```yaml
- id: files
  uses<EMAIL_ADDRESS>  with:
    filter: '*.php'
- run: |
    for changed_file in ${{ steps.files.outputs.all }}; do
      echo "Do something with this ${changed_file}."
    done
```

### Get all changed *.yml files but exclude .github/*/*.yml files

Be careful that the order of the glob has an importance.
Therefore, including all YML files first and excluding the YML files of your `.github/*/` directories is the way to go to exclude them.
If those two globs were inverted, you **would** include all the YML files, with the ones in your `.github/*/` directories.

```yaml
- uses<EMAIL_ADDRESS>  with:
    filter: |
      *.yml
      !.github/*/*.yml
```

### Get all added and modified files as CSV

```yaml
- id: files
  uses<EMAIL_ADDRESS>  with:
    format: 'csv'
    filter: '*'
- run: |
    mapfile -d ',' -t added_modified_files < <(printf '%s,' '${{ steps.files.outputs.added_modified }}')
    for added_modified_file in "${added_modified_files[@]}"; do
      echo "Do something with this ${added_modified_file}."
    done
```

### Get all removed files as JSON

```yaml
- id: files
  uses<EMAIL_ADDRESS>  with:
    format: 'json'
    filter: '*'
- run: |
    readarray -t removed_files <<<"$(jq -r '.[]' <<<'${{ steps.files.outputs.removed }}')"
    for removed_file in ${removed_files[@]}; do
      echo "Do something with this ${removed_file}."
    done
```

## Install, Build, Lint, Test, and Package

Make sure to do the following before checking in any code changes.

```bash
yarn
yarn all
```

## License

The scripts and documentation in this project are released under the [MIT License](LICENSE)

repository: rnsc/get-changed-files

gha_language: TypeScript

repo_name: rnsc/get-changed-files


text:
# MQTT

This module is a native module for the `MQTT` protocol, which is compatible with
the [MQTT.js](https://github.com/mqttjs/MQTT.js).

**Example**

```js
var mqtt = require('mqtt');
var client  = mqtt.connect('mqtt://test.mosquitto.org');

client.on('connect', function () {
  client.subscribe('presence');
  client.publish('presence', 'Hello mqtt');
});

client.on('message', function (topic, message) {
  // message is Buffer
  console.log(message.toString());
  client.end();
});
```

## Class: MqttClient

### new MqttClient(endpoint, options)

* `endpoint` {String} The uri of what your MQTT service at.
* `options` {Object} The options:
  * `keepalive` {Number} 60 seconds, set to 0 to disable
  * `clientId` {String} `'mqttjs_' + Math.random().toString(16).substr(2, 8)`
  * `protocolId` {String} `MQTT`
  * `protocolVersion` {String} `4`
  * `clean` {Boolean} `true`, set to false to receive QoS 1 and 2 messages while offline
  * `reconnectPeriod` {Number} `1000` milliseconds, interval between two reconnections
  * `connectTimeout` {Number} `30 * 1000` milliseconds, time to wait before a CONNACK is received
  * `username` {String} the username required by your broker, if any
  * `password` {String} the password required by your broker, if any

Creates a new client of `endpoint`.

### client.connect()

Connects the specified before url by MQTT.

### Event `'connect'`

Emitted on successful (re)connection (i.e. connack rc=0).

### Event `'reconnect'`

Emitted when a reconnect starts.

### Event `'offline'`

Emitted when the client goes offline.

### Event `'error'`

* `err` {Error} the error returned.

Emitted when the client cannot connect (i.e. connack rc != 0) or when a parsing error occurs.

### Event `'message'`

* `topic` {String} topic of the received packet.
* `message` {String} payload of the received packet.

Emitted when the client receives a publish packet.

### Event `'packetsend'`

Emitted when the client sends any packet. This includes .published() packets as well as packets used by MQTT for managing subscriptions and connections.

### Event `'packetreceive'`

Emitted when the client receives any packet. This includes packets from subscribed topics as well as packets used by MQTT for managing subscriptions and connections.

### client.publish(topic, message[, options[, callback]])

* `topic` {String} topic to publish
* `message` {String|Buffer} message to publish
* `options` {Object} options to publish with, including:
  * `qos` {Number} QoS level, default `0`
  * `dup` {Boolean} mark as duplicate flag, default `false`
  * `retain` {Boolean} retain flag, default `false`
* `callback` fired when the QoS handling completes, or at the next tick if QoS 0. An error occurs if client is disconnecting.

Publish a message to a topic.

### client.subscribe(topic[, options[, callback]])

* `topic` {String} topic to publish
* `options` {Object} options to publish with, including:
  * `qos` {Number} QoS level, default `0`
* `callback` callback fired on suback.

Subscribe to a topic.

> Not support on topics array or object.

### client.unsubscribe(topic[, callback])

* `topic` {String} topic to publish
* `callback` callback fired on suback.

Unsubscribe from a topic.

### client.end([force[, callback]])

* `force` {Boolean} passing it to true will close the client right away.
* `callback` {Function} will be called when the client is closed. This parameter is optional.

Close the client.

### client.reconnect()

Connect again using the same options as connect().

For more detailed, please see [MQTT.js Readme](https://github.com/mqttjs/MQTT.js#client).

repository: ErosZy/ShadowNode

repo_name: ErosZy/ShadowNode


text:
# Post-Workshop Q&A
 We received some great questions from attendees of the 2020 vASB GitHub Workshop. We've consolidated them along
 with their answers. At the bottom is a list of resources that can help further your Git/GitHub understanding.

**Have you used the same process (Git/GitHub) for manuscripts? If so, any tips or suggestions?**

Git and GitHub work best with raw text files. Code is an example of this, and allows for the line-by-line
tracked changes we saw in the tutorial. If you use LaTeX to write manuscripts, Git/GitHub would be a great option
for manuscript version control. But if you use Word Documents, there are probably better options because
they are not raw text files. Here are two options to consider:
1. Google Drive has some [version control functionality](https://support.google.com/drive/answer/2409045?co=GENIE.Platform%3DDesktop&hl=en)
 with any type of file. It is limited, but can be very useful still.
2. A service like [Simul Docs](https://www.simuldocs.com/how-it-works) provides version control for Word
Documents specifically. At this time, it is free to collaborate on a single document, but they offer paid
services for more functionality. I'm using Simul Docs for one of my manuscripts and it's based on the same version
control concepts we introduced at the start of this tutorial.

**When do I create a new repository?**

Repositories contain files for a given project, so I would have a repository for each project or study you might have.
You can then organize your repo with subfolders for scripts used to process, analyze, or visualize your data, for example.

**If I have multiple files in a repository and I think I may need to edit only some of them, should I
just branch/checkout those files or all of them?**

A clear distinction we need to make is that when you checkout a branch, your entire repository is copied. This will
contain all of your files, so you don't need to worry about knowing ahead of time which files you'll need
to change. You can just make changes in a branch, committing them along the way.
When you are satisfied with the changes you've made in your branch, you can merge them into the master
branch via a Pull Request like you did during [`Breakout 1`](Workshop_Instructions/breakout_1.md).

**How does Git handle reverting back to an earlier version (from version n to n-2, for example)?
What happens to versions n and n-1?**

We didn't have time to cover this in the 2020 ASB Tutorial, but it's been included in the associated video on youtube.
Undoing changes is handled by [`Breakout 2`](Workshop_Instructions/breakout_2.md) in a way
that *maintains the integrity of your repository history*. This means that when we say
your repository is "reverted", a new commit is being made that undoes the prior changes. The changes you
made in version n and n-1 are still present in your repository's commit history in case you ever want to view them.
However, version n+1 now contains changes that are the exact opposite of versions n and n-1. This is illustrated in the
[Further Considerations](https://github.com/alcantarar/ASB_Tutorial/blob/master/Tutorial_Instructions/breakout_2.md#further-considerations-reverting-multiple-changes-at-once)
 portion of Breakout 2.

 ## Additional Git/GitHub Resources
 * [Git Cheatsheet](Workshop_Instructions/git_cheatsheet.md) has the most-common commands and their definitions.
 * [How to undo (almost) anything with Git](https://github.blog/2015-06-08-how-to-undo-almost-anything-with-git/) is a blog
 by GitHub on undoing commits, messages, etc.
 * [GitHub's Guides](https://guides.github.com/) contains many instructional blog posts covering everything you need to know
 about using Git and GitHub.
 * [Good enough practices in scientific computing by Wilson et al. (2017)](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1005510)
 is a publication highlighting the need for academic researchers to start learning about scienfiic computing best practices.
 Version control is included, along with general recommendations for computing workflows.
 * [Pro Git](https://git-scm.com/book/en/v2) is the actual textbook on Git. It's free and chapters 1-5 should cover 90% of what you need to know.
 * [LearnGitBranching.org](https://learngitbranching.js.org/) is an interactive web app that illustrates branching.

gha_language: R


text:
##Introduction

This SLOGO project will provide an interactive programming environment that allows users to create code expressions that commands a sample object in a window pane. The primary design goals of the project are to develop a substantial code hierarchy that promotes effective interaction between the front end and back end models, as well as to have enough extensibility to account for potential new features or additional programming language properties. The primary architecture of the project is to have the view/simulation side take in input, pass it to the back end controller, which interprets and makes changes based on that input, and then pass refreshed values that reflect those changes back to the simulation, which will then adjust the current state to the new state. The commands and interpreter will be closed since those features are concrete in behavior, while the display and visualization will be open due to the changing nature of the user edits.

##Design Overview

![Slogo] (SLOGOpic.png "Slogo Architecture Design")

Our design is back end heavy with a command design pattern, with the model and controller handling most of the changes in this project. The view will encompass the display packages which are responsible for initializing and updating the various panes on the screen, including the history, command, and scene features. User input will be sent to the internal back end parser, which will then process those commands and make the appropriate changes in the respective model (turtle, line, commandList, canvas, etc.). The commands package will be responsible for changing values and the binding nature of those variables will be updated throughout the project. This way, the front end and the back end are consistently working with the same states and information.

Looking more in depth at each of our API, we obtain a better view of the design model. In the front end (internal), methods exist to draw() the turtle, lines, and scene per input; showHistory(); and showCommands(). From these, when a command is input, the back end will parse() the input information and convert it to the language of the program. Once the input string is parsed, the commands will be passed to the external back end for execution towards the UI. By some method, this parsed line will execute() changes to the respective values of the scene so long as the exceptionCheck() does not catch any errors on the deciphered syntax. With each execute(), the appropriate target (observable turtle, line, scene (and such)) will be signalled to update and the external front end will update() to obtain those values to draw() once more. This will all be repeated for each input line until each instruction is complete, and then the program will wait for the next input from the user.

Our design is back end heavy, with the model and controller handling most of the changes in this project. The view will encompass the display packages which are responsible for initializing and updating the various panes on the screen, including the history, command, and scene features. User input will be sent to the parser, which will then process those commands and make the appropriate changes. The commands package will be responsible for changing values and the binding nature of those variables will be updated throughout the project. This way, the front end and the back end are consistently working with the same states and information.

##User Interface

The User Interface will contain many components that will all interact with each other. There will be a splash screen that prompts the user to begin programming. From there, a new window will open with three panes. The first will be an initially blank history screen that will continually refresh with previous user input. Next, there will be a graphic display to show the turtle and the results of the user's commands. Lastly, there will be a command pane that allows the user to type in new input code to be interpreted and executed. In addition, there will be small features like buttons to exit or navigate back to the main menu. In the event that the user inputs improperly formatted expressions, a error message will appear with details about how to make the appropriate changes. The user will be required to dismiss the message before being allowed to try again.

##API Details

Front-end Internal

draw()

Back-end Internal

Front-end External

Back-end External

##API Example Code
draw() - abstract method from Drawable interface
Each view implements the Drawable interface
Each view has a set of properties and a draw method that draws the object using those properties

Front-end External

update() - abstract method from Updateable interface
Each view implements the Updateable interface
After a command updates backend values, each view is updated by calling the update
method (which draws all the updated elements)

Back-end Internal

execute() - abstract method from Command interface
Each command implements the Command interface
Updates model by calling model method with specific arguments

Back-end External
beginCommands(String s)
Takes the command input and parses it into a queue of commands
Execute each command, which updates the view

##API Example Code

### Use Case: Move forward 1 unit 100 times
input: ‘dotimes 100 fd 1’
description: move forward by 1 unit 100 times
precondition: turtle beings at (x,y)
postcondition: turtle ends at (x + 100*cos(heading), y+100*sin(heading))

course of action:
backExternal:  begincommands(“textField.getString()”);
exceptionChecker(for (n=0; n<100; n++){fd(1)});     (some parsedInput)
backInternal:   parser(“dotimes 100 fd 1”);
		execute(fd(1)) - updates turtle model
		execute(fd(1))	- updates turtle model
		…
		execute(fd(1)) - updates turtle model
		execute(fd(1)) - updates turtle model
Loops through all views and calls update and draw
frontExternal:  update();
frontInternal:   draw();

### Use Case: Move forward 50 units with pen down
input: ‘pd fd 50’
description: move forward by 50 units
precondition: turtle beings at (x,y)
postcondition: turtle ends at (x + 50*cos(heading), y+50*sin(heading)) with a line behind it

course of action:
backExternal:  begincommands(textField.getString());
exceptionChecker(for (n=0; n<100; n++){fd(1)});     (some parsedInput)
backInternal:   parser(‘pd fd 50’);
	execute(‘pd’); - updates line model
	execute(‘fd 50’) - updates turtle model
Loops through all views and calls update and draw
frontExternal:  update();
frontInternal:   draw();

### Use Case: Change the background color of the display
input: ‘bg blue’
description: changes the background of the display to blue
precondition: background has a color other than blue
postconiditon: background is blue

course of action:
backExternal: begincommands(textField.getString());
		exceptionChecker(isColor()): (some parsedInput)
backInternal: parser(‘bg blue’);
	          execute(bg.setColor(Colors.BLUE));
Loops through all views and calls update and draw
frontExternal:  update();
frontInternal:   draw();

### Use Case: Erroneous input
input: ‘   fksdflds’
description: input read, found to be unrecognizable and error returned in command pane to user
precondition: some state
postcondition: same state but with user friendly error printed

course of action:
backExternal: beginCommands(textField.getString());
	           exceptionChecker(“not a real input”);
(will print straight to command pane from exceptionChecker() to give the appropriate error)

### Use Case: Add Two Numbers
input: ‘sum 1 2’
description: adds the numbers 1 and 2 and displays the result in the command window
precondition: some state
postcondition: same state with the result in the command window

course of action:
backExternal: 	beginCommands(textField.getString());
		exceptionChecker();
backInternal:	parser(‘sum 1 2’);
		execute(sum(1,2)); - adds the two numbers and returns result
frontExternal:	update()
frontInternal:	draw()

## Design Considerations

In our planning process, we discussed updating the display when there are multiple commands in the expression. For example, ‘pu fd 50 pd fd 50’ can be split into two operations and evaluated successively. The issue we debated was to either handle a command, update the display, and handle the next command or to handle all commands at once and then pass the display the states of the turtle after every command and allow the front end to update this. We choose to go with the first option so that the movement of the turtle would be more dynamic and evaluating programming expressions would be more visible to a new programmer.

Another issue we discussed was having an animation timer versus an update method. The display with the turtle only needs to be refreshed after the user inputs more commands that alter its features. So rather than have an animation timer with a step method responsible for refreshing values, we opted to have the back end update the display so that way the changes take place sequentially and the problem of having all of the changes take place within one frame is avoided.

## Team Responsibilities

The team is split into two parts, front end (Michael and Michael) and back end (Andy and Anirudh). The front end side will work on User Interface and managing display changes and handling user input. The back end will handle the programming interpretation and command changes. In addition, cross collaboration will be essential to making the most effective and best designed project. Testing edge cases and debugging larger bug issues will take place at group meetings.


text:
---
title: 'Automated tools management system'
permalink: /productivity-solutions-grant/solutionrepo/solution2040
---

## Automated tools management system

## Overview

**Description**

Centralized tool storage, dispensing & inventory management (IM) system with 2 key components:

1) Smart IM software:
Monitors tool inventory, stock level & consumption rate; and
With customizable option to link to ERP or supplier online automated ordering process; and;
Controls the issuing of tools per user's security access level

2) Tool dispensing hardware
Hardware can be in the form of a drawer or coil vending system.

Cost of equipment capped at $28,000 per unit

## Solution Packages Option(s)

Equipment Name
Cost Cap
Mandatory Specifications

Automated tools management system
28000
Unit is expandable, customizable to hold different types of tools, and fully secured.

Support only hardware and software.

## Mode and Schedule of Payment

 - Direct Purchase

Interested companies can get a quotation from your selected vendor, before applying for the PSG through the Business Grant Portal (BGP).

repository: isomerpages/govtech-gobusiness

branch_name: refs/heads/staging

gha_language: HTML

repo_name: isomerpages/govtech-gobusiness