text:
## Hey there 👋,

I'm a full stack software developer/DevOps engineer from Canada.

I'm interested in JavaScript, TypeScript, ReactJS, .NET Core, and Software Engineering :heart:

![Alejandro's github stats](https://github-readme-stats.vercel.app/api?username=asanchezr&show_icons=true&count_private=true)

repository: asanchezr/asanchezr

repo_name: asanchezr/asanchezr


text:
---
title: "Start with Symfony on Mountain Lion"
created_at: 2013-10-01 22:43
kind: article
tags:
    - homebrew
    - macOS
    - symfony
---

Start developing [Symfony](http://symfony.com/) on a Mac is quite easy. Mountain Lion ships with some of the required libraries, but a few are hidden in the depth of the system.

This is a guide with shows you how to get [Symfony](http://symfony.com/) running on  Mac OS X Mountain Lion (10.8 that is).

## Xcode

First and foremost you need to install Xcode. Don't worry you can download it for free at [the App Store](https://itunes.apple.com/de/app/xcode/id497799835?mt=12).

After downloading and installation, start Xcode and go to downloads area in the preferences (⌘, > Downloads) and install the Command Line Tools.

![Xcode Preferences Panel](/images/blog/xcode-downloads.png)

## Homebrew

[Homebrew](http://brew.sh) is a package manager which helps us installing and configuring a few needed packages for our development platform.

Paste the following command into the terminal to install [Homebrew](http://brew.sh):

~~~ sh
$ ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"
~~~

After that you need to run `brew doctor` to finalize you installation.

## Database

You can decide which database you would like to use. Running [PostgreSQL](http://www.postgresql.org) is far easier than running [MySQL](http://www.mysql.com). Just use the [Postgres.app](http://postgresapp.com).

If you prefer running MySQL I'd like to refer to [MariaDB](https://mariadb.org) an enhanced, drop-in replacement for MySQL. You can install it with [Homebrew](http://brew.sh):

~~~ sh
$ brew install mariadb
~~~

If you get errors that no compilers are available install the `apple-gcc42` compiler and re-run `brew install mariadb`.

~~~ sh
$ brew install apple-gcc42
~~~

For now, just start your freshly installed MariaDB with `mysql.server start` and test your connection with `mysql -uroot`. If you get a warm welcome, everything works as expected. Terminate your connection with `\q`.

## Apache

Mountain Lion ships with Apache, but it is not running per default. You can start with `sudo apachectl start` and stop through `sudo apachectl stop`. But first we need to change some settings.

Open the file `/private/etc/apache2/httpd.conf` in your favorite editor and remove the `#` infront of theese two lines:

~~~ apache
#Include /private/etc/apache2/extra/httpd-vhosts.conf
…
#LoadModule php5_module libexec/apache2/libphp5.so
~~~

Now open the file `/private/etc/apache2/extra/httpd-vhosts.conf` and remove all `<VirtualHost>` instances and add the following:

~~~ apache
<VirtualHost *:80>
    DocumentRoot "/Users/[username]/symfony/web"
    ServerName dev.symfony

    <Directory "/Users/[username]/symfony">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog "/Users/[username]/symfony/app/logs/apache_error.log"
    CustomLog "/Users/[username]/symfony/app/logs/apache_access.log" common
</VirtualHost>
~~~

Replace `[username]` with your actual username. If you don't know it, start a new terminal and type `whoami`, which outputs your username.

Open your hosts file located at `/etc/hosts` and add a new entry for your `ServerName` specified in the Apache configuration above.

~~~
<IP_ADDRESS>   dev.symfony
~~~

We do not start Apache yet.

## PHP

You need to copy the default `php.ini` file to the correct place and add `detect_unicode = Off` to the end of the file.

~~~ sh
$ sudo cp /etc/php.ini.default /etc/php.ini
$ echo "echo 'detect_unicode = Off' >> /etc/php.ini" | sudo bash
~~~

Open the file `/etc/php.ini`, search for `date.timezone` and set your timezone accordingly.

~~~ ini
date.timezone = Europe/Berlin
~~~

Don't forget to remove the `;` at the beginning of the line. Save the file.

## Symfony

We use [Composer](http://getcomposer.org) to install [Symfony](http://symfony.com/). Start the install process:

~~~ sh
$ cd
$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer
~~~

Now you can get the current Symfony version with the command:

~~~ sh
$ composer create-project symfony/framework-standard-edition symfony/ 2.3.6
~~~

Answer the questions you get asked accordingly to your configuration. You also might need to replace `2.3.6` with the current version of symfony.

Now set the writing permissions for apache and the current user to the log and cache directory.

~~~ sh
$ cd symfony
$ chmod 0777 app/{logs,cache}
$ sudo chmod +a "_www allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
$ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
~~~

You now have a fresh installation of your Symfony in your home directory.

Now start Apache with `sudo apachectl start`.

## PECL and PEAR

Head over to your browser and type [http://dev.sympfony/config.php](http://dev.symfony/config.php) (or the ServerName you set above).

Correct all open major problems if there are some left.

Install PECL and PEAR:

~~~ sh
$ sudo php /usr/lib/php/install-pear-nozlib.phar
$ pear config-set php_ini /private/etc/php.ini
$ pecl config-set php_ini /private/etc/php.ini
$ sudo pear upgrade-all
$ sudo pear channel-update pear.php.net
$ sudo pecl channel-update pecl.php.net
~~~

Install the open recommendations `intl` and the PHP accelerator `apc`:

~~~ sh
$ brew install icu4c
$ sudo pecl install intl
~~~

Answer with the path `/usr/local/opt/icu4c` when asked for the ICU libraries and headers.

~~~ sh
$ brew install pcre
$ sudo ln -s /usr/local/include/pcre.h /usr/include/
$ sudo pecl install apc
~~~

Restart Apache `sudo apachectl restart`.

Reload your browser [http://dev.sympfony/config.php](http://dev.symfony/config.php) and watch for open recommendations.

<!--
## Add this

~~~
include_path = ".:/usr/lib/php/pear"
~~~
-->

license: MIT

repository: dabio/dabio

branch_name: refs/heads/main

extension: md

gha_language: SCSS

gha_license_id: MIT

license_type: permissive

repo_name: dabio/dabio


text:
# IS 117 Mini Project

By: Tejasree Seelam, Mehakpreet Kaur, Noura Hedhli

![git and github pic](https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRRVcHi7Vbr1vQhfCMvbNMsDCg_Z5batoKP0E9l0rVb-4q0h55u&s)

#### To-do List
- [x] Noura: Part 1 - What is it? Why do you do it? How do you do it?
- [x] Mehak: Part 2 - Explain gitFlow & define Git commands
- [x] Teja: Part 3 - Step by Step Tutorial
- [x] Teja: Add Section for Extra Links

### Click the links for more information!
* [What is it? Why do you do it? How do you do it?](part1.md)

* [GitFlow WorkFlow](part2.md)

* [Step by Step Tutorial](/part3.md)

* [Extra Links/Resources](/extralinks.md)

branch_name: refs/heads/master


text:
OpenResty Proxy
===============

A minimal-configuration OpenResty Docker image that makes it easy to have a FastCGI (and/or static file) proxy server
running as quickly as possible. This Docker image makes it trivial to start up a configurable OpenResty proxy server
that is able to serve requests to a FastCGI server.

## Configuration

| Name             | Default                                                                                | Description                                                                                |
|------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
| FALLBACK         | "@fastcgi"                                                                                | The fallback location to use if `try_files` fails.                                                            |
| FCGI_ROOT        | "${ROOT}"                                                                                | The document root for FastCGI servers (can be different to `$ROOT`).                                          |
| FCGI_SERVERS     | "<IP_ADDRESS>:9000"                                                                                | A comma separated list of `ip:port` pairs that will be used to create the upstream proxy for FastCGI servers. |
| GZIP_TYPES       | "application/ecmascript application/javascript application/json application/xhtml+xml application/xml text/css text/ecmascript text/javascript text/plain text/xml" | A list of mime types that will be gzipped when a response is sent.                                            |
| MAX_REQUEST_SIZE | "16M"                                                                                | The maximum request size that is allowed.                                                                     |
| ROOT             | "/app/public"                                                                                | The document root of the server.                                                                              |
| TIMEOUT          | 600                                                                                | The maximum length of time a request can be running for (sets the `fastcgi_read_timeout` property).           |

### Adding custom configuration.

    TODO

### Adding custom upstreams

    TODO

## Changelog

* **2019-11-07**
    * Add README.
    * Add `GZIP_TYPES` configuration option.

repository: garbetjie/docker-openresty

repo_name: garbetjie/docker-openresty


text:
# Back into it
Mtriage development has been stalled for some time, as I've had other
priorities. I'm hoping to pick up the pace in the last couple of months of
2020, however. These are a couple of things on the near horizon:

### Component-wise testing
This is pretty key to ensure that community component contributions are
meaningful. Currently there are only tests for the core part of mtriage, and it
is just an article of faith that each component (selector/analyser) works.

### Custom classifier documentation and compatibility
None of our code for bootstrapping custom classifiers with mtriage is public,
which means that it's pretty much useless to everyone in its current state,
except as a reference. We're looking to drive some more research around
training vision classifiers using synthetic data with mtriage, and we'll fold
out all of these fixes into upstream mtriage as ways to apply custom
classifiers in the abstract via mtriage as a deployment framework.

### Spec-ing a rewrite in Rust/Firecracker
This is somewhat irresponsible on my part, as this here Python/Docker version
of the framework barely works. But I'm looking for a way to get my fingers
properly sticky with Rust in practice, and mtriage seems a good candidate
(systems software, containers, etc).

repository: forensic-architecture/mtriage

gha_language: Python

gha_license_id: NOASSERTION

repo_name: forensic-architecture/mtriage


text:
# APIs example

"Who to follow" suggestions box with github api (https://api.github.com/users)

### Requirements:
We are going to focus on imitating its core features, which are:

On startup, load accounts data from the API and display 3 suggestions

On clicking "Refresh", load 3 other account suggestions into the 3 rows

On click 'x' button on an account row, clear only that current account and display another

Each row displays the account's avatar and links to their page

repository: jimulle/rxjs-workshop

repo_name: jimulle/rxjs-workshop


text:
---
published: false
layout: post
title: "How acta hides in the wake of SOPA and PIPA"
date: 2012-01-07 08:34
comments: true
categories:
  - Web
  - Government
  - Law
---

Today [Kader Arif](http://www.kader-arif.fr/) announced he has resigned from the
position as rapporteur for the `Anti-counterfeiting trade agreement'. He has
decided to do so as the agreement has been signed by the European Commission in
name of the European Union. Arif calls this series of events a
[charade](http://www.kader-arif.fr/actualites.php?actualite_id=147).

The signing of this agreement is remarkable as it closely resembles the SOPA and
PIPA accords that have so greatly [protested](TODO) and thus [postponed](a) or
even [cancelled](). According to Arif the signing of the agreement has been
rushed while negotiations have been conducted in secret. A


text:
# Signal.js
Real-time signal processing library. I'm developing this as part of another project that requires stuff like this. But still thought it would have been cool to externalize it for other javascript animation use cases.

Here is a quick guide: [Signal.js quick guide](http://mrgreenh.github.io/Signal.js/)


text:
# CSOB gateway

[![Build status](https://github.com/slevomat/csob-gateway/workflows/Build/badge.svg?branch=master)](https://github.com/slevomat/csob-gateway/actions?query=workflow%3ABuild+branch%3Amaster)
[![Code coverage](https://codecov.io/gh/slevomat/csob-gateway/branch/master/graph/badge.svg)](https://codecov.io/gh/slevomat/csob-gateway)
[![Latest Stable Version](https://img.shields.io/packagist/v/slevomat/csob-gateway.svg)](https://packagist.org/packages/slevomat/csob-gateway)
[![Composer Downloads](https://img.shields.io/packagist/dt/slevomat/csob-gateway.svg)](https://packagist.org/packages/slevomat/csob-gateway)

This repository provides a client library for ČSOB Payment Gateway.

- [CSOB payment gateway wiki](https://github.com/csob/paymentgateway/wiki)
- [CSOB eAPI 1.9](https://github.com/csob/platebnibrana/wiki/Vol%C3%A1n%C3%AD-rozhran%C3%AD-eAPI)

Library supports **all endpoints of eAPI 1.9** except NEJsplátku (loan@shop). Pull requests are welcome.

Older available versions (not actively maintained):
- Version 5.* supports PHP 7.2 and eAPI 1.8
- Version 4.* supports PHP 7.2 and eAPI 1.7
- Version 3.* supports PHP 7 and eAPI 1.6.
- Version 2.* supports PHP 7 and eAPI 1.5.
- Version 1.* supports PHP 5.6 and eAPI 1.5.

## Installation

The best way to install slevomat/csob-gateway is using [Composer](http://getcomposer.org/):

```
> composer require slevomat/csob-gateway
```

## Usage

First you have to initialize the payment in gateway and redirect customer to its interface.

**WARNING**: Please note, that all the prices are in hundredths of currency units. It means that when you wanna init a payment for 1.9 EUR, you should pass here the integer 190.
```php
$apiClient = new ApiClient(
	new CurlDriver(),
	new CryptoService(
		$privateKeyFile,
		$bankPublicKeyFile
	),
	'https://api.platebnibrana.csob.cz/api/v1.8'
);

$requestFactory = new RequestFactory('012345');

// cart has to have at least 1 but most of 2 items
$cart = new Cart(Currency::EUR);
$cart->addItem('Nákup', 1, 1.9 * 100);

$customer = new Customer(
    'Jan Novák',
<EMAIL_ADDRESS>    mobilePhone: '+420.800300300',
    customerAccount: new CustomerAccount(
        new DateTimeImmutable('2022-01-12T12:10:37+01:00'),
        new DateTimeImmutable('2022-01-15T15:10:12+01:00'),
    ),
    customerLogin: new CustomerLogin(
        CustomerLoginAuth::ACCOUNT,
        new DateTimeImmutable('2022-01-25T13:10:03+01:00'),
    ),
);

$order = new Order(
    OrderType::PURCHASE,
    OrderAvailability::NOW,
    null,
    OrderDelivery::SHIPPING,
    OrderDeliveryMode::SAME_DAY,
    addressMatch: true,
    billing: new OrderAddress(
        'Karlova 1',
        null,
        null,
        'Praha',
        '11000',
        null,
        Country::CZE,
    ),
);

$paymentResponse = $requestFactory->createInitPayment(
	123,
	PayOperation::PAYMENT,
	PayMethod::CARD,
	true,
	$returnUrl,
	HttpMethod::POST,
	$cart,
    $customer,
    $order,
    'some-base64-encoded-merchant-data',
    '123',
    Language::CZ,
    1800,
    1,
    2,
)->send($apiClient);
$payId = $paymentResponse->getPayId();

$processPaymentResponse = $requestFactory->createProcessPayment($payId)->send($apiClient);

// redirect to gateway
header('Location: ' . $processPaymentResponse->getGatewayLocationUrl());
```
After customer returns from gateway, he is redirected to `$returnUrl` where you have to process the payment.
```php
try {
    $receivePaymentResponse = $requestFactory->createReceivePaymentRequest()->send($apiClient, $_POST /* $_GET */);
    if ($receivePaymentResponse->getPaymentStatus() === PaymentStatus::S7_AWAITING_SETTLEMENT) {
        // payment was successful!
    }
} catch (VerificationFailedException | InvalidSignatureException $e) {
    // request was not send from csob api
}
```
Please refer to the CSOB documentation and learn what states you should to check, they are all available as PaymentStatus::S* constants.

## Custom `ApiClientDriver`

API calls are made through `ApiClientDriver` interface. Library contains two default implementations of driver - CurlDriver and GuzzleDriver. You can also
create your own driver by implementing the `ApiClientDriver` interface, and passing it to `ApiClient` constructor.

`CurlDriver` communicates via `curl` PHP extension, `GuzzleDriver` uses [guzzlehttp/guzzle](https://packagist.org/packages/guzzlehttp/guzzle) library. If you want to use
GuzzleDriver you need to require `guzzlehttp/guzzle` package in your composer.json.

repository: slevomat/csob-gateway

gha_language: PHP

repo_name: slevomat/csob-gateway


text:
# Data visualization style guidelines for Office Add-ins

Good data visualizations help users find insights in their data. They can use those insights to tell stories that inform and persuade. This article provides guidelines to help you design effective data visualizations in your add-ins for Excel and other Office apps.

We recommend that you use [Office UI Fabric](http://odux/fabric/?page=overview) to create the chrome for your data visualizations. Office UI Fabric includes styles and components that integrate seamlessly with the Office look and feel. The following figure shows a data visualization in an add-in that uses Fabric.

[![Title: images/msohtmlclipclip_image001.png - Description: C:\Users\lauragra\AppData\Local\Packages\Microsoft.Office.OneNote_8wekyb3d8bbwe\TempState\msohtmlclipclip_image001.png](https://raw.githubusercontent.com/mimisasouvanh/demonstration/master/images/msohtmlclipclip_image001.png - Description: C:\Users\lauragra\AppData\Local\Packages\Microsoft.Office.OneNote_8wekyb3d8bbwe\TempState\msohtmlclipclip_image001.png)](https://raw.githubusercontent.com/mimisasouvanh/demonstration/master/images/msohtmlclipclip_image001.png)

## Data visualization elements

Data visualizations share a general framework and common visual and interactive elements, including titles, labels, and data plots, as shown in the following figure.

### Chart titles

Follow these guidelines for chart titles:

*   Make your chart titles easily readable. Position them to create a clear visual hierarchy in relation to the rest of the chart.
*   In general, use sentence capitalization (capitalize the first word). To create contrast or to reinforce hierarchies, you can use all caps, but all caps should be used sparingly.
*   Incorporate the [Office UI Fabric type ramp](http://odux/fabric/?page=features) to make your charts consistent with the Office UI, which uses Segoe. You can also use a different typeface to differentiate chart content from the UI.
*   Use sans-serif typefaces with large counters.

The following examples show serif and sans-serif typefaces used in chart titles. Notice how the scale contrast and effective use of white space create a strong visual hierarchy.

### Axis labels

Make your axis labels dark enough to read clearly, with adequate contrast ratios between the text and background colors. Make sure that they are not so dark that they compete with data ink.

Light grays are most effective for axis labels. If you’re using Fabric, see the [Neutral Colors palette](http://odux/fabric/?page=features).

### Data ink

The pixels that represent the actual data in a chart are referred to as data ink. This should be the central focus of the visualization. Avoid the use of drop shadows, heavy outlines, or unnecessary design elements that distort or compete with the data. Use gradients only when data values are tied to color values. Avoid three-dimensional charts unless a measurable, objective value is bound to a third dimension.

### Color

Choose colors that follow operating system or application themes rather than hardcoded colors. At the same time, make sure that the colors you apply do not distort the data. Misuse of color in data visualizations can result in data distortion and incorrect reading of information.

For best practices for use of color in data visualizations, see the following:

[Why rainbow colors aren't the best option for data visualizations](http://www.poynter.org/2013/why-rainbow-colors-arent-always-the-best-options-for-data-visualizations/224413/)

[Color Brewer 2.0: Color Advice for Cartography](http://colorbrewer2.org/)

[I Want Hue](http://tools.medialab.sciences-po.fr/iwanthue/)

### Gridlines

Gridlines are often necessary for accurately reading a chart, but should be presented as a secondary visual element, enhancing the data ink, not competing with it. Make static gridlines thin and light, unless they are designed specifically for high contrast. You can also use interaction to create dynamic, just-in-time gridlines that appear in context when a user interacts with a chart.

Light grays are most effective for gridlines. If you’re using Fabric, see the [Neutral Colors palette](http://odux/fabric/?page=features).

The following image shows a data visualization with gridlines.

### Legends

Add legends if necessary to:

· Distinguish between series

· Present scale or value changes

Make sure that your legends enhance the data ink and do not compete with it. Place legends:

· Flush left above the plot area by default, if all legend items fit above the chart.

· On the upper right side of the plot area, if all legend items do not fit above the chart, and make it scrollable, if necessary.

To optimize for readability and accessibility, map legend markers to the relevant chart shape. For example, use circle legend markers for scatter plot and bubble chart legends. Use line segment legend markers for line charts.

### Data labels and tooltips

Ensure that data labels and tooltips have adequate white space and type variation. Use algorithms to minimize occlusion and collision. For example, a tooltip might surface to the right of a data point by default, but surface to the left if right edges are detected.

## Design Principles

The Office Design team created the following set of design principles, which we use when designing new data visualizations for the Office product suite.

## Visual design principles

· Visualizations should honor and enhance the data, making it easy to understand. Highlight the data, adding supporting elements only as needed to provide context. Avoid unnecessary embellishments (drop shadows, outlines, etc), chart junk, or data distortion.

· Visualizations should encourage exploration by providing rich visual feedback. Use well-established interaction patterns, interface controls, and clear system feedback.

· Embody time-honored design principles. Use established typographic and visual communication design principles to enhance form, readability, and meaning.

## Interaction design principles

· Design with affordances that allow for exploration.

· Allow for direct interactions with objects that reveal new insights (sorting via drag, for example).

· Use simple, direct, familiar interaction models.

For more information about how to design user-friendly interactive data visualizations, see [UI Tenets and Traps](http://uitraps.com/).

## Motion design principles

· Motion follows stimulus. Visual elements should move in the same direction at the same rate. This applies to:

· Chart creation

· Transition from one chart type to another chart type

· Filtering

· Sorting

· Adding or subtracting data

· Brushing or slicing data

 *   Resizing a chart

· Create a perception of causality. When staging animations:

Stage one thing at a time.

· Stage changes to axes before changes to data ink.

· Stage and animate objects as a group if they are moving at the same speed in the same direction.

 *   Stage data elements in groups of no more than 4-5 objects. Viewers have difficulty tracking more than 4-5 objects independently

· Motion adds meaning.

· Animations increase user comprehension of changes to the data, provide context, and act as a non-verbal annotation layer.

· Motion should occur in a meaningful coordinate space of the visualization.

· Tailor the animation to the visual.

 *   Avoid gratuitous animations.

· Motion follows data.

· Preserve data mappings. If an area is tied to a measure, maintain that area in transition.

· Maintain a consistent animation design language. Where possible, map data visualization animation to existing Office motion design language. Use similar animations for similar chart types.

## Accessibility in data visualizations

· Do not use color as the only way to communicate information. People who are color blind will not be able to interpret the results. Use shape, size and texture in addition to color when possible to communicate information.

· Make all interactive elements, such as push buttons or pick lists, accessible from a keyboard.

· Send accessibility events to screen readers to announce focus changes, tooltips, and so on.

## Additional resources (use dev.office.com links here, integrate external inline).

· [Data + Design: A Simple Introduction to Preparing and Visualizing Information](https://infoactive.co/data-design/titlepage01.html)

· [The Five Best Libraries for Building Data Visualizations](http://www.fastcompany.com/3029760/the-five-best-libraries-for-building-data-vizualizations)

· [The Visual Display of Quantitative Information](https://www.edwardtufte.com/tufte/books_vdqi)

repository: mimisasouvanh/demonstration

repo_name: mimisasouvanh/demonstration


text:
---
layout: post
title:  "Using Derived Tables and Nested SELECT"
date:   2017-06-19 11:48:30
categories: SQL
tags: [SQLzoo]
years: ['2017']
comments: true
---

# Using Subquery and Derived Tables

I had difficult time understanding the `world x` and `world y` concept from the yet completed post "SELECT Quiz". I found this one small hidden hyperlink "SELECT from SELECT" inside another hidden hyperlink "Using nested SELECT" from "SELECT within SELECT", expanding more about derived tables. I am going to cover on that first.

Derived table is when I could use result from one query in another query.

1) Subquery with `FROM`

- may use a `SELECT` statement in the `FROM` line
- in this case the derived table `X` has columns `name` and `gdp_per_capita`
- calculated values in the inner `SELECT` can be used in the outer `SELECT`

```sql
SELECT name, ROUND(gdp_per_capita) FROM
  (SELECT name, gdp/population AS gdp_per_capita FROM bbc) X
WHERE gdp_per_capita>20000
```

Happening here:

- outer query gather countries that has gdp_per_capita greater than 20000
- inner query gather ALL countries with their gdp_per_capita

Noting:

- inner table is given an alias `x`
- first column in inner query keeps its `name`
- second column in inner query has an alias `gdp/population AS gdp_per_capita`

| name | ROUND(gdp_per.. |
| Australia | 26900 |
| Austria | 32300 |
| Belgium | 31030 |
| ... |

2) Subquery with `IN`

- find the countries in the same region as Bhutan

- you may use a SELECT statement in the WHERE line - this returns a list of regions

```sql
SELECT name FROM bbc
WHERE region IN (SELECT region FROM bbc WHERE name = 'Bhutan')
```

- no derived table, has a inner query in `WHERE`
- inner query identifies the `region` that 'Bhutan' is in
- outer query gather all countries in the region yet identified until inner query

| name |
| Afghanistan |
| Bangladesh |
| Bhutan |
| ... |

3) Correlated Subquery

- if a value from the outer query appears in the inner query this is "correlated subquery"
- show the countries where the population is greater than 5 times the average for its region

```sql
SELECT name FROM bbc b1
WHERE population > 5 * (SELECT AVG(population) FROM bbc WHERE region=b1.region)
```

- outer query gathers countries `FROM` aliased `bbc b1` table with population greater than 5 times inner query result
- inner query calculates average population in each region

| name |
| Brazil |
| China |
| India |
| Nigeria |
| Russia |

# Using Nested SELECT

- result of a SELECT statement may be used as a value in another statement
- statement SELECT continent FROM world WHERE name = 'Brazil' evaluates to 'South America'
- can use this value to obtain a list of all countries in the same continent as 'Brazil'

1) Using SELECT in SELECT
List each country in the same continent as 'Brazil'

```sql
SELECT name FROM world
WHERE continent = (SELECT continent FROM world WHERE name = 'Brazil')
```

# Alias

- some versions of SQL insist that you give the subquery an alias
- using `AS somename` after the closing bracket

```sql
SELECT name FROM world
WHERE continent = (SELECT continent FROM world WHERE name='Brazil') AS brazil_continent
```

I decided to research a bit more about alias and found this juicy information in [wiki][wiki]. It is a feature of SQL that most of relational database management systems (RDBMSs) support.

What alias can do:

- reduce the amount of code required for a query
- make simpler to understand
- can be used as an obfuscation technique to protect the real names of database fields
- can alias tables and columns

Alias table is also called a correlation name.

# Multiple Results

- subquery may return more than one result
- if more than one result, will fail as testing one value against more than one value
- safer to use `IN` to cope with this possibility

FAIL: `(SELECT continent FROM world WHERE name = 'Brazil' OR name='Mexico')` will return two values ('North America' and 'South America')
{: .redfont}

- Saying "apple" and "orange" at the same time is impossible

BETTER:

```sql
SELECT name, continent FROM world
WHERE continent IN (SELECT continent FROM world WHERE name='Brazil' OR name='Mexico')
```

- outer query gather countries and continents
- inner query gather continents where 'Brazil' and 'Mexico' are in

3) Subquery on the SELECT line

- if certain that only one value will be returned then can use that query on the SELECT line
- show the population of China as a multiple of the population of the United Kingdom

```sql
SELECT population/(SELECT population FROM world WHERE name = 'United Kingdom')
FROM world WHERE name = 'China'
```

| population/(S.. |
| 21.2987 |

## ALL or ANY

- can use the words ALL or ANY where the right side of the operator might have multiple values

4) Show each country that has a population greater than the population of ALL countries in Europe

Note:

- that we mean greater than every single country in Europe
- not the combined population of Europe.

```sql
SELECT name FROM world
WHERE population > ALL (SELECT population FROM world WHERE continent='Europe')
```

| name |
| Bangladesh |
| Brazil |
| China |
| Egypt |
| Ethiopia |
| India |
| Indonesia |
| Japan |
| Mexico |
| Nigeria |
| Pakistan |
| Philippines |
| Russia |
| United States |
| Vietnam |

Now I am heading back to older post [SELECT Quiz][SELECT Quiz] to clarify, since now that I understand a bit more.

[wiki]: https://en.wikipedia.org/wiki/Alias_(SQL)
[SELECT Quiz]: https://ngarciaiii.github.io/sql/2017/06/13/SELECT-Quiz/

extension: markdown


text:
---
title: Telerik.Web.Data.AggregateFunction
page_title: Telerik.Web.Data.AggregateFunction
description: Telerik.Web.Data.AggregateFunction
---

# Telerik.Web.Data.AggregateFunction

Represents the basic class that supports creating functions that provide statistical information about a set of items.

## Inheritance Hierarchy

* System.Object
* Telerik.Web.Data.AggregateFunction

## Properties

###  Caption `String`

Gets or sets the informative message to display as an illustration of the aggregate function.

###  FunctionName `String`

Gets or sets the name of the aggregate function, which appears as a property of the group record on which records the function works.

###  ResultFormatString `String`

Gets or sets a string that is used to format the result value.

## Methods

###  CreateAggregateExpression

Creates the aggregate expression that is used for constructing expression
            tree that will calculate the aggregate result.

#### Parameters

#### enumerableExpression `System.Linq.Expressions.Expression`

The grouping expression.

#### Returns

`System.Linq.Expressions.Expression`

###  GenerateFunctionName

Generates default name for this function using this type's name.

#### Returns

`System.String` Function name generated with the following pattern:
            {.}_{}

repository: telerik/ajax-docs

gha_language: C#

repo_name: telerik/ajax-docs


text:
---
id: 662
title: 'Statistical Notes (2): Equivalence Testing and TOST (Two One-Sided Test)'
date: 2012-09-12T22:39:23+00:00
author: Jiangtang Hu
layout: post
guid: http://www.jiangtanghu.com/blog/?p=662
permalink: /2012/09/12/tost-equivalence-test/
categories:
  - SAS
  - statistics
tags:
  - equivalence test
  - Geometric Mean
  - SAS
  - statistics
  - T-test
  - TOST
---
> _Programmers Need to Learn Statistics Or I will Kill Them All –Zed A. Shaw_

In an equivalence testing [example](http://support.sas.com/documentation/cdl/en/statug/65328/HTML/default/viewer.htm#statug_ttest_examples05.htm) against lognormal data,  a TOST (Two One-Sided Test)  option used in SAS TTEST procedure:

> proc ttest data=auc dist=lognormal tost(0.8, 1.25);
   paired TestAUC*RefAUC;
run;

And the output:

[](http://www.jiangtanghu.com/blog/wp-content/uploads/2012/09/tost.png)

Since the 90% (who not 95%? see below) limit of the geometric mean ratio (0.9412) , [0.8634,1.0260], lies in the FDA endorsed equivalence bounds [0.8,1.25],  then we can make a conclusion of “Equivalent” among these Test and Reference drugs. Following are the notes on how this so called TOST (Two One-Sided Test) works.

In its original form, the hypothesis of equivalence testing is written as difference on means (equivalence by definition: not above the upper limit, and not below the lower limit):

[](http://www.jiangtanghu.com/blog/wp-content/uploads/2012/09/hypo.png)

Since our AUC example with lognormal data, the difference on means is transformed into a ratio,  geometric mean ratio: if no difference in means, then the ratio simply equals 1. The two one-sided tests are (with form of ratio, not difference anymore):

> I) upper one-sided T-test with a null ratio as the left bound of predefined limits, here is 0.8
>
> II) lower one-sided T-test with a null ratio as the right bound of predefined limits, here is 1.25.

T-test I can be done as (with option sides=U, where U means upper one-sided test. This option also only goes with SAS 9.2 and later)

> proc ttest data=auc dist=lognormal h0=0.8  sides=U;
   paired TestAUC*RefAUC;
run;

And the output:

[](http://www.jiangtanghu.com/blog/wp-content/uploads/2012/09/upper.png)

T-test II, lower one-sided (with option sides=L, where L means lower one-sided test):

> proc ttest data=auc dist=lognormal h0=1.25 sides=L;
   paired TestAUC*RefAUC;
run;

And the output:

[](http://www.jiangtanghu.com/blog/wp-content/uploads/2012/09/lower.png)

So, the two one-sided tests together get a limit of [0.8634,1.0260], which is exactly as same as we got before using TOST option, except the former noted as “95%” and the later, “90%”. That’s because, the 0.1 (1-90%) should be dividend by 2 for the two one-sided tests to ensure they can both get their 0.05 significance respectively. Namely, at significant level α=5%, the equivalence test gets a  100(1-2α)% = 90% interval.

At last, the overall P-value, will take the maximum one in these two one-sided tests (here we get max{0.0031,<0.0001} = 0.0031).

# SAS Notes

Just did a quick search, PROC MIXED seemed more popular for statisticians to perform equivalence test years before:

Cookbook SAS Codes for Bioequivalence Test in 2x2x2 Crossover Design, by Chunqin Deng (2012)

_The Paired T-Test: Does PROC MIXED Produce the Same Results as PROC TTEST?_ by Jack Nyberg (2004)

Section 8.2 Bioequivalence Testing, in __Pharmaceutical Statistics Using SAS: A Practical Guide, by Alex Dmitrienko, Christy Chuang-Stein, and Ralph D’Agostino (2007)

# Reference

_SAS TTEST Procedure User Guide_

_Beyond the t-Test_

repository: rbind/jiangtang

repo_name: rbind/jiangtang


text:
Onsen
=====

Boiler Controller Software

- Controller (python)
- Web interface (php)
- Sensor reader (Arduino sketch)

An __onsen__ is a term for hot springs in the Japanese language, though the term is often used to describe the bathing facilities and inns around the hot springs. Jigokudani Monkey Park is famous for its large population of __Snow Monkeys__, that go to the valley during the winter. Starting in 1963, the monkeys descend from the steep cliffs and forest to sit in the warm waters of the onsen, and return to the security of the forests in the evenings.

![Snow Monkeys](doc/images/onsen_monkeys.jpg)

repository: martinvdberg/onsen

repo_name: martinvdberg/onsen


text:
---
layout: post
title: AIR iPhone Application
link: http://www.psyked.co.uk/air-iphone-application/
author: psyked_james
description:
post_id: 628
created: 2009/01/22 10:48:51
created_gmt: 2009/01/22 09:48:51
comment_status: open
post_name: air-iphone-application
status: publish
post_type: post
---

# AIR iPhone Application

They've created the iPhone as an AIR app using the new Ribbit API. Pretty impressive [ http://merhl.com/?page_id=75]( http://merhl.com/?page_id=75)

## Comments

**[lee](#526 "2009-01-22 15:54:46"):** Haha, that's so cool. Completely bassackwards, but cool! AIR should run on the iPhone, not the pseudo iPhone in air, lol. Cooooool tho!


text:
# shelm
_subverting Elm packaging since 2019_

__status: works for me, might eat your files__

`shelm` is a bash wrapper around the `elm` tool that allows bypassing
the Elm packaging infrastructure.

It allows you to
- depend on Elm packages that have not been published to
  [package.elm-lang.org](https://package.elm-lang.org), such as
  versioned Github releases, local paths or arbitrary git urls.
- work with native Javascript code: Depend on modified versions of core
  Elm modules or write your own kernel modules by placing a package within
  the `elm/` or `elm-explorations/` package namespace.

__Note: Best not talk about this on the offical Elm channels unless you're
trolling.__

## How to use

`shelm` expects to be called from the top level directory of an Elm project,
which contains an `elm.json` file. The basic workflow is: First call
`shelm fetch` to download dependencies into the local package cache. Then
call `shelm make` as you would usually call `elm make`. (Other `elm` subcommands
are passed through, too, but might not work.)

With a regular `elm.json`, there should be no functional difference to normal
`elm` tool use. To make use of `shelm`'s extra features, you might:

- Add dependencies for a packages that have not been released to the Elm
  package repository. Suppose you have an Elm package in a GitHub repository
  `me/elm-experiment` that you haven't published using `elm publish`. Then if
  you tag a commit as "1.0.0", depending on
  ```
  "dependencies": {
      "direct": {
          ...
          "me/elm-experiment": "1.0.0",
          ...
  ```
  in `elm.json` as usual will make `shelm` download the 1.0.0 release.

- Specify alternative locations for dependencies. E.g., to use a patched
  version of the `elm/time` package that's published at `github.com/me/elm-time`,
  you would change the dependency section of `elm.json` to read
  ```
  "dependencies": {
      "direct": {
          ...
          "elm/time": "1.0.0"
      },
      "indirect": {
          ...
      },
      "locations": {
          "elm/time": {
              "method": "github",
              "name": "me/elm-time"
          }
      }
  }
  ```
  See below for full documentation of the `"locations"` field.

## Locations

`shelm` currently supports the following location types:

__github__

Parameters: `name` as "author/project".

Tagged GitHub releases, as used by regular `elm` packages. Downloads the
source archive for the release specified by the dependency version.

See above for an example.

__file__

Parameters: `path` as a local directory.

Copies over the given path as the source.

E.g., if you're developing `my-fancy-gui-toolkit` and want to test
it in `my-flashy-app` before publishing, you might tweak `my-flashy-app`'s
`elm.json` to include
```
"locations": {
    "me/my-fancy-gui-toolkit": {
        "method": "file",
        "path": "../my-fancy-gui-toolkit"
    }
}
```

__git__

Parameters: `url` as a git url, `ref` as a branch/tag/commit (defaults to version).

Checks out the given reference from the given git repository.

E.g., to build your application against the upstream development version
of `elm/time`,
```
"locations": {
    "elm/time": {
        "method": "git",
        "url": "https://github.com/elm/time.git",
        "ref": "master"
    }
}
```

## Troubleshooting

The `elm` tool error messages are explicitly unhelpful if something goes wrong
compiling dependencies. If you get some complaints about corruption or version
conflicts, chances are that `shelm` or your `elm.json` setup is at fault. Wiping
`elm-stuff` and calling `shelm fetch` again is a good first try.

It's important that both `elm make` and `elm make --docs=docs.json` works for
each dependency.

It's your responsibility to make sure that the source archive pointed at by
a location actually has the same version as listed in the dependencies. Things
are likely to go wrong if those don't align.

## Dependencies

__Elm compiler__

The `elm` tool should be in the path. Versions 0.19.0 and 0.19.1 are supported.

__jq__

The [jq](https://stedolan.github.io/jq/) JSON processor is used to read `elm.json`.

__curl, git, tar__

`git` is required for the "git" location method, `curl` and `tar` for the default
"github" archive method.

## How it works

shelm manages its own local copy of the Elm package database in
`elm-stuff/home/.elm`, by downloading source archives using a variety
of measures, and generating a matching package registry.
It calls `elm` with `$HOME` pointed at this directory and networking
disabled by setting an invalid `$HTTP_PROXY` variable.

The following two articles go into this with a bit more detail:

- https://vllmrt.net/spam/guix-elm-2.html describes a Guix build system
  for Elm applications that uses the same techniques.
- https://vllmrt.net/spam/subverting-elm.html shows how shelm came about
  when figuring out how to build an Elm app with native code.

repository: robx/shelm

gha_language: Shell

repo_name: robx/shelm


text:
---
title: Task definition defines sensitive environment variable(s).
---

# Task definition defines sensitive environment variable(s).

### Default Severity: critical

### Explanation

You should not make secrets available to a user in plaintext in any scenario. Secrets can instead be pulled from a secure secret storage system by the service requiring them.

### Possible Impact
Sensitive data could be exposed in the AWS Management Console

### Suggested Resolution
Use secrets for the task definition

### Insecure Example

The following example will fail the aws-ecs-no-plaintext-secrets check.
```terraform

 resource "aws_ecs_task_definition" "bad_example" {
   container_definitions = <<EOF
 [
   {
     "name": "my_service",
     "essential": true,
     "memory": 256,
     "environment": [
       { "name": "ENVIRONMENT", "value": "development" },
       { "name": "DATABASE_PASSWORD", "value": "oh no D:"}
     ]
   }
 ]
 EOF

 }

```

### Secure Example

The following example will pass the aws-ecs-no-plaintext-secrets check.
```terraform

 resource "aws_ecs_task_definition" "good_example" {
   container_definitions = <<EOF
 [
   {
     "name": "my_service",
     "essential": true,
     "memory": 256,
     "environment": [
       { "name": "ENVIRONMENT", "value": "development" }
     ]
   }
 ]
 EOF

 }

```

### Links

- [https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_task_definition](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_task_definition){:target="_blank" rel="nofollow noreferrer noopener"}

- [https://docs.aws.amazon.com/systems-manager/latest/userguide/integration-ps-secretsmanager.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/integration-ps-secretsmanager.html){:target="_blank" rel="nofollow noreferrer noopener"}

- [https://www.vaultproject.io/](https://www.vaultproject.io/){:target="_blank" rel="nofollow noreferrer noopener"}

repository: sachinpatkar/tfsec

repo_name: sachinpatkar/tfsec


text:
## File Menu

### Overview
The file menu offers a list of commands or choices to the user. The menu can be propogated with commands such as: quit, logout, restart, etc.

### What it looks like
![](./screenshot.png)

### Controls used
The controls used in this component are documented over in our Finsemble React Controls repo:
* [FinsembleMenu](https://github.com/ChartIQ/finsemble-react-controls/tree/master/FinsembleMenu)
* [FinsembleMenuSection](https://github.com/ChartIQ/finsemble-react-controls/tree/master/FinsembleMenuSection)
* [FinsembleMenuSectionLabel](https://github.com/ChartIQ/finsemble-react-controls/tree/master/FinsembleMenuSectionLabel)
* [FinsembleMenuItem](https://github.com/ChartIQ/finsemble-react-controls/tree/master/FinsembleMenuItem)

repository: sean-ciq/finsemble-seed

repo_name: sean-ciq/finsemble-seed


text:
# Word Cloud of @mentionedusers in tweets by YOU

## Introduction

First we're extracting out all **@mentionedusers** from tweets by this user & generate word cloud from it, where emphasized words denote frequent mentioning.

## Example

Below is a demonstration of word cloud, generated from my tweets.

![wordCloudOfMentionedUsersInTweetsByAnjan_Roy](../plots/wordCloudOfMentionedUsersInTweetsByAnjan_Roy.png)

repository: itzmeanjan/twiz

repo_name: itzmeanjan/twiz


text:
### Usage

Create a new Jekyll project

```sh
~ $ jekyll new Blog
```

Add this line to `Gemfile`

```ruby
gem "my-theme"
```

Add this line to `_config.yml`

```yaml
theme: my-theme
```

Add this line to `css/main.scss`

```scss
@import "my-theme";
```

and then execute

```sh
~ $ bundle install

~ $ bundle exec jekyll serve

# http://localhost:4000
```

repository: StartZeroGnu/gem-themes

repo_name: StartZeroGnu/gem-themes


text:
Contributing
=====================

rmodbus is work of [many contributors](https://github.com/rmodbus/rmodbus/graphs/contributors). You're encouraged to submit [pull requests](https://github.com/rmodbus/rmodbus/pulls), [propose features and discuss issues](https://github.com/rmodbus/rmodbus/issues).

We appreciate pull requests with test cases to prevent regressions.

#### Commit Changes

Writing good commit logs is important.  Click the 'Pull Request' button and fill out the form. Pull requests are usually reviewed within a few days.

#### Rebase

If you've been working on a change for a while, rebase with upstream/master.

```
git fetch upstream
git rebase upstream/master
git push origin my-feature-branch -f
```

#### Check on Your Pull Request

Go back to your pull request after a few minutes and see whether it passed muster with Travis-CI. Everything should look green, otherwise fix issues and amend your commit as described above.

#### Thank You

We really appreciate and value your time and work. Thank you for making rmodbus better!

repository: xinyifly/rmodbus

repo_name: xinyifly/rmodbus


text:
# KAREL

### Features
* Syntax Highlighting
* Easy code snippet insertion
* Built-in routines keywords

This repository stays under the [MIT License](LICENSE.md), so feel free to contribute for yourself or the community.

repository: teodormichalski/atom-karel

repo_name: teodormichalski/atom-karel


text:
---
id: getting-started
title: Getting Started with Neutron JS
sidebar_label: Getting Started
---

Neutron is a Command Line Interface developed to help developers create new react projects with Redux + Redux Saga, as well as providing a well-structured code organization.

This page will help you install and build your first react project using Neutron JS and it's very important to explain that to work with mobile, you must have installed the `expo-cli` in your development environment.

#### Why Expo for React Native?
We chose Expo due to maturity that it's reached and because it's not necessary to configure and install SDKs, emulators and other common requirements for iOS and Android development.

> To learn more about `expo-cli`, check: Get Started With Expo.

## Installation

This is simple and easy because Neutron JS is available as a package in Node Package Manager. You should write your terminal:

```shell
yarn global add @neutronjs/cli
```

After installation, you can confirm using `neutron` on your terminal or `neutron -h` to check all available commands:

```
Starts With:
  neutron create           Create new project with React

Commands:
  neutron add:component    Add new component files
  neutron add:duck         Add new duck file
  neutron add:page         Add new page files
  neutron add:saga         Add new saga and duck files

Utils:
  neutron -h               Show help information
  neutron -v               Output the version number
```

## Creating a new project

To create a new project, you must use command with this format:

```shell
neutron create <appName> <platform>
```

Available platforms:

- `--web`: create a new project with React JS
- `--mobile`: create a new project with React Native

#### Usage example:

```shell
neutron create my-app --web
```

After a while you will see the success message and be able to start the application with a development server using:

```shell
cd my-app && yarn start || npm run start
```

repository: neutronjs/neutron

gha_language: JavaScript

repo_name: neutronjs/neutron


text:
# Wdarking_Contactform

Magento 1.9 Custom Contact form module. This module is intended to be used as a base module to any custom changes to the default magento contact page form. This module already implements a captcha on the contact form. To enable the captcha on this form, go to `Store > Configuration > Customers > Customers Configuration > Captcha` and select `Wdarking Contacts Page`.

#### Features:
- Captcha


text:
---
layout: project
type: project
image: images/project2Image.png
title:    Bank Database Application in C and C++
permalink: projects/bankdatabase
# All dates must be YYYY-MM-DD format!
date: 2017-05-22
labels:
  - C
  - C++
  - linked list
  - Bank database
summary: The Bank Database Application was a semester long project where accounts were added, deleted, and modified using linked lists in C and C++.
---

For the ICS 212 Programming Structure course at UH Manoa, I developed a bank database application in C during the first half of the class and rewrote it in the C++ object oriented programming style. The bank account database had a UI that allowed its users to create a new, delete, modify, print all, or print specific bank account information. Linked lists data structures were used so that adding and deleting accounts could be done easily. The C and C++ bank account database programs were completed independently.

From this experience I learned how to write programs using linked lists, strengthened my ability to work with pointers, and improved upon my debugging and programming skills.

Source: bankDatabase


text:
Contributing to Flutter
=======================

_See also: [Minitel's code of conduct](CODE_OF_CONDUCT.md)_

Welcome
-------

We invite you to join our team! Everyone is welcome to contribute code
via pull requests, to file issues on GitHub, reproduce, or fix bugs
that people have filed, to add to our documentation, or to help out
in any other way.

We grant commit access (which includes full rights to the issue
database, such as being able to edit labels) to people who have gained
our trust and demonstrated a commitment to Minitel Toolbox.

This document focuses on what is needed to contribute by writing code
and submitting pull requests for the Minitel Toolbox.

Developing for Minitel
----------------------

To develop for Minitel, you will eventually need to become familiar
with our processes and conventions. This section lists the documents
that describe these methodologies. The following list is ordered: you
are strongly recommended to go through these documents in the order
presented.

1. [Our code of conduct](CODE_OF_CONDUCT.md), which stipulates explicitly
   that everyone must be gracious, respectful, and professional. This
   also documents our conflict resolution policy and encourages people
   to ask questions.

2. [Values](https://github.com/Darkness4/minitel-app/wiki/Values),
   which talks about what we care most about.

3. [Setting up your development environment](https://github.com/Darkness4/minitel-app/wiki/Setting-up-the-development-environment),
   which describes the steps you need to configure your computer to
   work on the Minitel Toolbox.

4. [Tree hygiene](https://github.com/Darkness4/minitel-app/wiki/Tree-hygiene),
   which covers how to land a PR, how to do code review, how to
   handle breaking changes, how to handle regressions, and how to
   handle post-commit test failures.

5. [Our style guide](https://github.com/Darkness4/minitel-app/wiki/Style-guide-for-Flutter-repo),
   which includes advice for designing APIs for Flutter, and how to
   format code in the framework.

In addition to the above, there are many pages on [our
Wiki](https://github.com/Darkness4/minitel-app/wiki/) that may be of
interest. For a curated list of pages see the sidebar on the wiki's
home page. They are more or less listed in order of importance.

gha_language: Dart


text:
# simplify-url
## Simplify-url is a application to shorten the URL using NodeJs, Express and MongoDB

### Prerequisites
Install the following software to run the project locally or on docker container
* [Node.js version 12.x/version 14.x](https://nodejs.org/en/download/)
* [MongoDB version 4.4.x](https://www.mongodb.com/download-center/community/releases)
* [Docker](https://www.docker.com/products)
* [docker-compose](https://docs.docker.com/compose/install/)

> **NOTE:** Use the links to setup each software

### Project setup
* Clone the project code from GitHub
* Goto project directory in CLI
    #### Local install
    * Run `# npm install`
    * Start the node server `# npm start`
    #### Docker install
    * Run `# docker-compose up -d`

    ![Docker Page](https://github.com/Sruthi-Ramachandran/simplify-url/blob/main/doc_img/docker.PNG)

* Goto [http://localhost:4100](http://localhost:4100)

### Project Testing
* Run `npm test` locally

![Test Run](https://github.com/Sruthi-Ramachandran/simplify-url/blob/main/doc_img/test.PNG)

> **Note:** Tests are not supported by Docker.

### Project GUI
* **Simplify URL/ Shorten**

    ![GUI Page](https://github.com/Sruthi-Ramachandran/simplify-url/blob/main/doc_img/gui_test_url.PNG)

    URL - Insert valid URL in textbox and submit.
    It returns the simplified URL as a link.

    **Example:**
    URL- https://github.com

    Simplified URL - http://localhost:4100/thwvXHS

* **Search the existing URL**

    ![Search URL](https://github.com/Sruthi-Ramachandran/simplify-url/blob/main/doc_img/gui_search_1.PNG)

    Enter Long/Short URL or keywords.
    It returns matching URL

    ![Search URL](https://github.com/Sruthi-Ramachandran/simplify-url/blob/main/doc_img/gui_search_2.PNG)

* **View the list of existing URL**

    Click on the View Button on left navigation bar.
    It returns the List of URLs from database

    ![Navigation](https://github.com/Sruthi-Ramachandran/simplify-url/blob/main/doc_img/gui_nav_bar.PNG)

    ![View Page](https://github.com/Sruthi-Ramachandran/simplify-url/blob/main/doc_img/gui_view_list.PNG)

* **Delete URL**

    Click on the delete button in the View page.

    ![View Page](https://github.com/Sruthi-Ramachandran/simplify-url/blob/main/doc_img/gui_view_list.PNG)

    ![Delete Page](https://github.com/Sruthi-Ramachandran/simplify-url/blob/main/doc_img/gui_delete.PNG)

### Useful docker commands to manage the project
|DOCKER COMMAND|DESCRIPTION|
|-|-|
|docker-composer up -d|Run the docker-compose to create the project containers in background mode.|
|docker-compose up --build -d|Build a new image and create the containers. Require if code changes are made.|
|docker-compose down -v|Delete the conatiners and the persistent volumes.|

repository: Sruthi-Ramachandran/simplify-url

repo_name: Sruthi-Ramachandran/simplify-url


text:
---
description: Follow along to build and connect your Losant Builder Kit.
---

# Losant Builder Kit Instructions

The Losant Builder Kit is an easy way to get up and running with the Losant Enterprise IoT Platform. This kit provides all the hardware and software needed to build a few simple projects that cover a wide variety of the features within the Losant Platform.

![Builder Kit](/images/getting-started/losant-iot-dev-kits/builder-kit-nodemcu/kit-complete.jpg "Builder Kit")

As you perform these workshops, if you run into any issues, please refer to the [Losant Documentation](/) and the [Losant Forums](https://forums.losant.com) for help.

Your kit should include the following items:

* 1 [NodeMCU v1.0](http://nodemcu.com/index_en.html) dev kit microcontroller (View board schematic)
* 1 solderless breadboard
* 8 jump wires
* 2 resistors
* 1 LED
* 1 TMP36 temperature sensor
* 1 button
* 1 micro-USB cable

## 1. Overview

These instructions are split into three workshops. Each workshop builds on the previous one and adds new functionality to your kit. It is recommended that you complete the workshops in order.

## 2. Environment Setup

The microcontroller included in this kit is programmed using the Arduino tools. Those must be installed by following the environment setup instructions.

## 3. Losant Setup

In this section, you’ll register for a Losant account, create your application, and add the device for your builder kit.

### Create Account

If you don't already have an account, navigate to [https://accounts.losant.com/create-account](https://accounts.losant.com/create-account) to register.

### Create Application

Create an application for the builder kit. You can name it whatever you want.

![Create Application](/images/getting-started/losant-iot-dev-kits/builder-kit/create-application.png "Create Application")

![Application Settings](/images/getting-started/losant-iot-dev-kits/builder-kit/application-settings.png "Application Settings")

### Add Device

The next step is to register the builder kit device with the platform. Click the `Add Device` button on the top right or select `Add Device` from the Devices dropdown.

![Add Device Menu](/images/getting-started/losant-iot-dev-kits/builder-kit/add-device-menu.png "Add Device Menu")

Next, choose the `Create Blank Device` option.

![Create From Scratch](/images/getting-started/losant-iot-dev-kits/builder-kit/add-from-scratch.png "Create From Scratch")

![Add Device Name](/images/getting-started/losant-iot-dev-kits/builder-kit/add-device-name.png "Add Device Name")

![Add Device Attributes](/images/getting-started/losant-iot-dev-kits/builder-kit/add-device-attributes.png "Add Device Attributes")

1. Name the device anything you want.
1. "Description" can be left blank, or fill it with whatever you want.
1. For "Device Type", leave "Standalone" selected.
1. Add a device attribute with the type `Boolean` and the name `button`.
1. Add a device attribute with the type `Number` and the name `tempF`.
1. Add a device attribute with the type `Number` and the name `tempC`.

The device attributes specify what state information the device reports. The firmware that you’ll flash in the following sections will report whenever a button is pressed, the temperature in Celsius (tempC), and the temperature in Fahrenheit (tempF). Device attributes are ***case-sensitive***, so make sure to enter these ***exactly as they appear***.

Click the `Create Device` button. The screen will change and show the device’s ID. This ID is required for the following sections. You might want to copy/paste it somewhere convenient.

![Device ID](/images/getting-started/losant-iot-dev-kits/builder-kit/device-id.png "Device ID")

### Generate An Access Key

Now we need to generate an [access key](/applications/access-keys/) so your device can authenticate against the Losant Platform. Select `Security` from the application menu bar, and then `Device Access Keys` from the left navigation. Then click `Add Access Key`.

![Access Keys](/images/getting-started/losant-iot-dev-kits/builder-kit/access-keys.png "Access Keys")

For these workshops, generate an access key that provides access to all devices in your application.

![Token Restrictions](/images/getting-started/losant-iot-dev-kits/builder-kit/token-restrictions.png "Token Restrictions")

This will cause a popup to appear with your access tokens. Losant ***DOES NOT*** store the secret, so you’ll have to copy it somewhere secure. Both of these values will be needed in the following sections, so make sure you copy/paste them somewhere convenient.

![Access Token Popup](/images/getting-started/losant-iot-dev-kits/builder-kit/access-token-popup.png "Access Token Popup")

## 4. Get Workshop Source Code

Now let's get the firmware you'll be flashing to the device. Download and extract the following zip file to your computer. We'll be editing and opening these files using the Arduino IDE, so put it somewhere convenient.

[https://github.com/Losant/losant-kit-builder-nodemcu/archive/master.zip](https://github.com/Losant/losant-kit-builder-nodemcu/archive/master.zip)

If you're familiar with Git, you can also clone the repository from here:

[https://github.com/Losant/losant-kit-builder-nodemcu](https://github.com/Losant/losant-kit-builder-nodemcu)

## 5. Workshop 1 – Internet Button

The first workshop creates an Internet button that triggers a Losant Workflow to send yourself an email.

### Workshop 1 Wiring

***Disconnect the NodeMCU dev kit from USB.***

For this workshop, you’ll need to attach the NodeMCU and button to the breadboard. Below is the wiring diagram. For more information on what breadboards are and how they work, check out our blog post on How to Use a Breadboard.

![Workshop 1 Wiring Diagram](/images/getting-started/losant-iot-dev-kits/builder-kit-nodemcu/workshop-1-wiring-diagram.png "Workshop 1 Wiring Diagram")

1. Push the NodeMCU into terminals 1-15 on either side of the center line, which are rows “b” and “i.” The USB port should be facing away from the breadboard.
1. Connect the 3V3 pin from the NodeMCU (a1) to the positive rail with a jump wire.
1. Connect the GND pin from the NodeMCU (a2) to the negative rail with a jump wire.
1. Connect the button to the other end of the breadboard so its leads straddle the center line and connect it to terminals e28, e30, f28, and f30.
1. Connect the positive rail to the button using terminal a28 using a jump wire.
1. Connect the negative rail to the button using terminal c30 using a resistor. It doesn’t matter which way resistors are oriented.
1. Connect the pin labeled "D1" on the NodeMCU (a14) to the button (j30) with a jump wire. In our code, "D1" is the equivalent of GPIO pin 5.

![Workshop 1 Wiring Image](/images/getting-started/losant-iot-dev-kits/builder-kit-nodemcu/workshop-1-wiring-image.jpg "Workshop 1 Wiring Image")

### Flash the Workshop 1 Firmware

Plug the NodeMCU back into USB. Make sure the device shows up under the Arduino IDE's `Tools -> Port` menu and it's selected. Refer to the [environment setup](/getting-started/losant-iot-dev-kits/environment-setup/#configure-device-usb-port) for instructions on properly configuring the device port.

With the Arduino IDE, use the `File -> Open` menu to navigate to where you downloaded and extracted the builder kit source code and open the file `workshop-1-internet-button/workshop-1-internet-button.ino`. Edit the following variables at the top of the file.

1. WIFI_SSID: The name of your WiFi network.
1. WIFI_PASS: Your WiFi password.
1. LOSANT_DEVICE_ID: After creating your device, the device ID is printed on the page in a gray box. You can also find it next to the name of your device on your application's "View All Devices" page.
1. LOSANT_ACCESS_KEY: Set this to the access key you generated after creating the Losant application.
1. LOSANT_ACCESS_SECRET: Set this to the access secret you generated after creating the Losant application.

![Update Variables](/images/getting-started/losant-iot-dev-kits/builder-kit/update-variables.png "Update Variables")

Your changes will automatically be saved as part of the upload process in the following steps. After editing the code, open the Arduino IDE's Serial Monitor and change the baud rate to 115200. The serial monitor can be opened using the button on the top right of the Arduino IDE or using the `Tools -> Serial Monitor` menu.

![Open Serial Monitor](/images/getting-started/losant-iot-dev-kits/builder-kit/open-serial-button.png "Open Serial Monitor")

![Serial Monitor Baud](/images/getting-started/losant-iot-dev-kits/builder-kit/serial-monitor-baud.png "Serial Monitor Baud")

The serial monitor won't print any information until we flash the device with the source code in the next step.

Upload the firmware to the device by clicking the `Upload` button or the `Sketch -> Upload` menu. This will take a few seconds and the NodeMCU will rapidly blink a blue light while it’s uploading.

![Upload Button](/images/getting-started/losant-iot-dev-kits/builder-kit/upload-button.png "Upload Button")

If you see an error in the Arduino IDE's output window, refer to the ones below for common solutions.

```c
#include <ESP8266WiFi.h>
                         ^
compilation terminated.
exit status 1
```

This means the board is not installed or properly setup. Refer to the [Arduino Setup](/getting-started/losant-iot-dev-kits/environment-setup/#configure-arduino-ide) step of the environment setup instructions to install the board and configure the Arduino IDE to use it.

```text
error: espcomm_open failed
error: espcomm_upload_mem failed
```

This means the port is not properly selected. Refer to the [Configure Device USB Port](/getting-started/losant-iot-dev-kits/environment-setup/#configure-device-usb-port) step of the environment setup instructions.

After the upload is complete, the Serial Monitor should start printing information about it connecting to WiFi and Losant. Push the button you wired up in the breadboard, and the Serial Monitor will print “Button Pressed!”

![Serial Output](/images/getting-started/losant-iot-dev-kits/builder-kit/serial-output.png "Serial Output")

If you don’t see the “Button Pressed!” message, check your wiring. The jump wires are not always the best connectors and sometimes just need wiggled around a little.

Every time the button is pressed, the firmware is publishing the state `{ "button": true }` to Losant. Currently, this firmware only reports when the button goes to true, it does not report the button going back to false. So if you hold the button down for a long time, it will only report when the button is initially pressed.

It’s now time to go into Losant and make use of this data.

### Create Workflow

[Workflows](/workflows/overview/) in Losant allow you to easily perform actions based on various triggers. In this workshop, our trigger will be a device state. Whenever the button is pressed, the device publishes a state message to Losant that we can use to trigger an action – for example, sending an email.

Create a new workflow and name it “Internet Button.”

![Create Workflow](/images/getting-started/losant-iot-dev-kits/builder-kit/create-workflow.png "Create Workflow")

![Save Workflow](/images/getting-started/losant-iot-dev-kits/builder-kit/save-workflow.png "Save Workflow")

Start by dragging a Device workflow Trigger Node to the canvas. Then, on the Device trigger's configuration panel, select your builder kit device. Since this is likely the application's only device, it will be selected by default. If, however, you have more than one device, simply start typing the name of the device and select it from the dropdown.

![Device Workflow Node](/images/getting-started/losant-iot-dev-kits/builder-kit/device-workflow-node.png "Device Workflow Node")

Next, add a [Debug Node](/workflows/outputs/debug/) so you can test that the workflow is triggered when the button is pressed. This is also an opportunity to see what a workflow payload looks like. Understanding the payload will help make the following steps make sense.

![Debug Workflow Node](/images/getting-started/losant-iot-dev-kits/builder-kit/debug-workflow-node.png "Debug Workflow Node")

Workflow nodes are connected by clicking on the small diamond-shaped connector on the source node and dragging it to anywhere on the destination node.

This workflow is now ready to test. Deploy it using the `Deploy Workflow` button on the top right.

![Deploy Workflow Button](/images/getting-started/losant-iot-dev-kits/builder-kit/deploy-workflow-button.png "Deploy Workflow Button")

After the workflow has been deployed, you can press the device button to see the debug output. The debug output can be reached by clicking the `Debug` tab on the right of the screen.

![ This is the data that flows through the workflow. Workflow nodes can change the payload, validate values, and perform many other operations. In this example, the payload includes the state that was published.

```text
{ "data" : { "button" : true }}
```

If you have an empty data field that does not include the button value, the typical cause is the button attribute defined on the device does not exactly match "button" (all lowercase). Go back to your device page and double-check that it matches exactly. If it does not, simply change the attribute's name and save the device. The button field should then automatically start showing up.

You may remember that when you originally set up the device, we added an attribute named “button” whose data type was boolean. This is the attribute that the firmware we flashed is sending to Losant. There’s nothing special about the name “button”; we could have named it anything.

Since the Device node can be triggered on any state request and we only want this workflow to run when the button attribute is sent, let’s add a [Conditional node](/workflows/logic/conditional/) to check that the value of button is true. This will be important for the later workshops when the device starts sending other state information. We don’t want an email every time the device sends something.

![Conditional Workflow Node](/images/getting-started/losant-iot-dev-kits/builder-kit/conditional-workflow-node.png "Conditional Workflow Node")

You can delete the existing Debug Node or click on the connecting line and delete it. Either way, insert a Conditional node between the Device node and the Debug Node.

Many workflow nodes, including the Conditional node, support what Losant calls [expressions](/workflows/accessing-payload-data/#expressions), which allow for testing the truthiness of a condition against a payload property. Set the conditional expression to the following:

```text
{{ data.button }} == true
```

This expression pulls the value of data.button from the payload, which you saw earlier using the Debug Node. If data.button doesn’t exist, this will evaluate to false.

The Conditional node branches the workflow depending on whether the expression is true or false. If the value is true, the workflow takes the right branch. If the expression is false, the workflow takes the left branch. Since we have nothing attached to the false branch, the workflow simply ends and nothing happens.

The last step is to add the Email node to send yourself an email every time the button is pressed.

![Email Workflow Node](/images/getting-started/losant-iot-dev-kits/builder-kit/email-workflow-node.png "Email Workflow Node")

Losant has two email output nodes. The [Email](/workflows/outputs/email/) node sends emails using Losant’s servers, but has a limit of one email per minute. If you need to send more than that, you can use the [SendGrid](/workflows/outputs/sendgrid/) email node.

Enter your email address as a recipient. You can then specify any subject and body you’d like. All of these fields support templates, which means they could pull their values from the payload, but this doesn’t apply for our example. For now, simply type any text you'd like.

Click the “Deploy Workflow” button and press the hardware button. You should now receive an email with the subject and body you specified.

This completes the first workshop. You’ve successfully created an Internet button that can be used for any number of useful actions. For an extra challenge, try browsing the other output nodes and come up with other actions you can control with your Internet button, such as sending yourself a text message.

## 6. Bonus Workshop - Virtual Light Wall

If you visit [http://lights.now.sh](http://lights.now.sh) you'll see a 3x3 grid of squares - that's the "Virtual Light Wall". In this workshop, we're going to make one of those squares light up with a random color and display a message of your choosing whenever you hit your internet button.

Start by adding an HTTP node to your workflow and connecting it to the Conditional node. You may also want to disconnect the Email node so you don't get emails every time you press the button during this workshop.

![HTTP Workflow Node](/images/getting-started/losant-iot-dev-kits/builder-kit-nodemcu/workflow-http-node.png "HTTP Workflow Node")

On the HTTP node configuration properties, change the `Request Method` to `POST` and set the `URL Template` to "http://lights.now.sh".

Set the body template to the following:

```json
{ "name" : "your name here", "message" : "your message here" }
```

The name and message can be anything you want. Try to keep it family friendly because it will be displayed in front of everyone.

Lastly, add a request header by setting the `Name` to "content-type" and the `Value Template` to "application/json".

Click the `Deploy Workflow` button to deploy this workflow.  The Light Wall then lights up a random square and displays the information. Everyone else who is also viewing the Virtual Light Wall will see your message in real-time.

This workshop shows a lot of the power behind workflows. We've completely changed the behavior of our internet button without having to write any code or update the firmware running on the device itself.

## 7. Workshop 2 – Remote Control LED

In the previous workshop, we showed you how to make a physical button do something in the virtual world. In this example, we’re going show how a virtual button can do something in the physical world.

Losant supports two major communication mechanisms – [states](/devices/state/) and [commands](/devices/commands/). You already saw how state works in the previous example. Commands allow you to send actions to the device. In this workshop, we’re going to send a “toggle” command that will turn on and off an LED.

### Workshop 2 Wiring

***Disconnect the NodeMCU from USB.***

Each workshop builds on the previous one, so if you completed the first workshop, it is not necessary to disconnect any components from your breadboard. We will simply add an LED and connect it to the NodeMCU.

![Workshop 2 Wiring Diagram](/images/getting-started/losant-iot-dev-kits/builder-kit-nodemcu/workshop-2-wiring-diagram.png "Workshop 2 Wiring Diagram")

1. Add the LED so the positive lead (the longer one) is in terminal e19 and the negative lead is in e20.
1. Connect the positive lead of the LED from terminal c19 to D2 on the NodeMCU (terminal a13) with a jump wire.
1. Connect the negative lead of the LED from terminal c20 to the negative rail with a resistor.

![Workshop 2 Wiring Image](/images/getting-started/losant-iot-dev-kits/builder-kit-nodemcu/workshop-2-wiring-image.jpg "Workshop 2 Wiring Image")

### Flash the Workshop 2 Firmware

Plug the NodeMCU back into USB.

Open the file `workshop-2-led.ino` with the Arduino IDE. Just like in the first workshop, you’ll have to edit the WiFi and credentials fields. You can use the same values from the previous workshop.

Just like before, make sure the Serial Monitor is open and upload the sketch to the NodeMCU. On some Windows machines, we've noticed you have to re-select the board and port whenever you open a new file. Make sure these are properly set under the `Tools -> Board menu and Tools -> Port` menu.

![Upload Workshop 2](/images/getting-started/losant-iot-dev-kits/builder-kit/upload-workshop-2.png "Upload Workshop 2")

The firmware we just flashed is listening for a specific “toggle” command. Let’s use Losant to easily send it this command.

### Create the Virtual Button

Create a new workflow and name it “Virtual Button.”

![Create Workflow Virtual Button](/images/getting-started/losant-iot-dev-kits/builder-kit/create-workflow-virtual-button.png "Create Workflow Virtual Button")

![Workflow Virtual Button Settings](/images/getting-started/losant-iot-dev-kits/builder-kit/workflow-virtual-button-settings.png "Create Workflow Virtual Button")

Once created, drag the Virtual Button workflow node to the canvas.

![Virtual Button Workflow Node](/images/getting-started/losant-iot-dev-kits/builder-kit/virtual-button-workflow-node.png "Virtual Button Workflow Node")

The Virtual Button Node allows you to completely define the payload that will flow through the workflow. Since we won’t be using the payload, it can be kept as an empty object or left blank. The Virtual Button is often useful to debug complex workflows because you can trigger the workflow with any test data you’d like, but in our case, we're going to use it to send the toggle command to our device.

Next, drag a Device Command Node onto the canvas and connect it to the Virtual Button.

![Device Command Workflow Node](/images/getting-started/losant-iot-dev-kits/builder-kit/device-command-workflow-node.png "Device Command Workflow Node")

The Device Command Node requires the device and the command details. Since you likely only have one device, it should be automatically selected. If not, choose it from the dropdown. The command name that the kit supports is “toggle.” Command names can be anything, and what commands a device supports are entirely up to the firmware. In our example, the firmware we flashed is looking for a command named “toggle” and knows to flip the LED when it’s received. Commands also support optional payloads that could be arguments to the command. For example, if the command is “start recording,” the payload could be `{ "resolution" : 1080 }`. Our toggle command, however, doesn't need a payload, so leave it blank.

Click the “Deploy Workflow” button at the top-right of the screen.

![Deploy Virtual Button](/images/getting-started/losant-iot-dev-kits/builder-kit/deploy-virtual-button.png "Deploy Virtual Button")

Once deployed, you can now click the virtual button and see the LED on the board turn on and off.

![Virtual Button Click](/images/getting-started/losant-iot-dev-kits/builder-kit/virtual-button-click.png "Virtual Button Click")

The Serial Monitor will also print a message whenever a command is received.

![Command Serial Output](/images/getting-started/losant-iot-dev-kits/builder-kit/command-serial-output.png "Command Serial Output")

We’ve now seen the two primary ways devices can communicate with Losant – state and commands. If you link these together, a whole world of possibilities opens up. Imagine having two builder kits where the button on one invokes the toggle command on another via a workflow. This allows us to easily perform machine-to-machine (m2m) communication without the devices even knowing about each other.

## 8. Workshop 3 – Temperature Sensor

In this workshop, we’re going to add a temperature sensor to your builder kit. We’ll then use Losant’s dashboarding tools to visualize the real-time and historical temperature data.

### Workshop 3 Wiring

***Disconnect the NodeMCU from USB.***

Just like the previous workshop, keep everything you've already wired and add these new components.

![Workshop 3 Wiring Diagram](/images/getting-started/losant-iot-dev-kits/builder-kit-nodemcu/workshop-3-wiring-diagram.png "Workshop 3 Wiring Diagram")

1. Add the tmp36 temperature sensor to terminals e22, e23, and e24. It’s ***VERY IMPORTANT*** that the sensor is oriented the right way with the flat side facing the bottom of the board – towards column a.
1. Connect the rightmost lead (a24) of the temperature sensor to the negative rail using a jump wire.
1. Connect the leftmost lead (a22) of the temperature sensor to the positive rail using a jump wire.
1. Connect the center lead (a23) to the A0 pin on the NodeMCU (terminal j15) with a jump wire.

![Workshop 3 Wiring Image](/images/getting-started/losant-iot-dev-kits/builder-kit-nodemcu/workshop-3-wiring-image.jpg "Workshop 3 Wiring Image")

### Flash the Workshop 3 Firmware

Plug the NodeMCU back into USB. Open the file workshop-3-temp.ino. Just as in the previous two workshops, edit the top of the file to set the WiFi and Losant credentials. You can use the same values as the previous two workshops.

![Deploy Workshop 3](/images/getting-started/losant-iot-dev-kits/builder-kit/deploy-workshop-3.png "Deploy Workshop 3")

After the upload completes, the Serial Monitor will print the temperature every 15 seconds.

![Temp Serial Output](/images/getting-started/losant-iot-dev-kits/builder-kit/temp-serial-output.png "Temp Serial Output")

This firmware is publishing state every 15 seconds to the Losant Platform. The state includes the tempF and tempC attributes that we defined back when the device was added. This is also why we had to add the Conditional Workflow node to the Internet button (Workshop 1). Without the Conditional, you’d get an email every time the device published temperature, which is likely not what you want.

### Build a Dashboard

Now, let’s visualize some of this temperature data that we’re sending. Create a new dashboard in Losant and add a gauge block.

![Create Dashboard](/images/getting-started/losant-iot-dev-kits/builder-kit/create-dashboard.png "Create Dashboard")

![Create Dashboard Form](/images/getting-started/losant-iot-dev-kits/builder-kit/create-dashboard-form.png "Create Dashboard Form")

![Add Gauge](/images/getting-started/losant-iot-dev-kits/builder-kit/add-gauge.png "Add Gauge")

The gauge block allows you to display a single real-time value or a value that is an aggregate over time (like sum, mean, etc).

![Gauge Details](/images/getting-started/losant-iot-dev-kits/builder-kit/gauge-details.png "Gauge Details")

Set the gauge block header to any value you’d like. Select your builder kit application from the Application dropdown. Change the Block Type to `Dial Gauge` and set the minimum to 0 and the maximum to 100. We want to show the real-time temperature, so select `Last received data point` from the Duration dropdown. Lastly, enter units (Deg F) in the label field, select your device, and set the attribute to either "tempF" or "tempC," whichever you’re more familiar with.

As soon as you enter all values, you should see the preview on the right immediately update.

Once you click `Add Block`, the gauge will appear on your dashboard.

![Dashboard with Gauge](/images/getting-started/losant-iot-dev-kits/builder-kit/dashboard-with-gauge.png "Dashboard with Gauge")

Next, let’s add a graph to the dashboard that shows the temperature value over time. Click the `Add Block` link on the top-right and select the `Time Series Graph` block.

![Select Linear Graph](/images/getting-started/losant-iot-dev-kits/builder-kit/select-linear-graph.png "Select Linear Graph")

![Time Series Settings](/images/getting-started/losant-iot-dev-kits/builder-kit/time-series-settings.png "Time Series Settings")

Set the name of the block to any value you’d like. Select your builder kit application from the Application drop down. Next, select to view the last 15 minutes of data at a 10 second resolution. This will cause the graph to show 15 minutes of data with a data point every 10 seconds.

In the block data section, name the graph series Deg F or Deg C, select your device, select the tempF or tempC attribute, and set the aggregation to `Mean`.

The aggregation is the operator applied to the data in order to provide a data point for every 10 seconds. Since we chose Mean, all data points in a 10 second window will be averaged together for each data point on the graph.

Click the `Add Block` button and the graph will appear on your dashboard.

![Dashboard with Graph](/images/getting-started/losant-iot-dev-kits/builder-kit/dashboard-with-graph.png "Dashboard with Graph")

As an extra challenge, see if you can use a new workflow to send yourself an email whenever the temperature exceeds 80 degrees Fahrenheit. To test, you can lightly pinch the temperature sensor between your fingers to raise its value.

These workshops are just the beginning. You now have a kit that can be used for any number of interesting solutions.

Tweet

repository: Losant/losant-docs

gha_language: CSS

repo_name: Losant/losant-docs


text:
---
layout: post
title: "Are Girls Neko or Sh=ojo? Cross-Lingual Alignment of Non-Isomorphic Embeddings with Iterative Normalization"
date: 2019-06-04 17:56:22
categories: arXiv_AI
tags: arXiv_AI Embedding
author: Mozhi Zhang, Keyulu Xu, Ken-ichi Kawarabayashi, Stefanie Jegelka, Jordan Boyd-Graber
mathjax: true
---

* content
{:toc}

##### Abstract
Cross-lingual word embeddings (CLWE) underlie many multilingual natural language processing systems, often through orthogonal transformations of pre-trained monolingual embeddings. However, orthogonal mapping only works on language pairs whose embeddings are naturally isomorphic. For non-isomorphic pairs, our method (Iterative Normalization) transforms monolingual embeddings to make orthogonal alignment easier by simultaneously enforcing that (1) individual word vectors are unit length, and (2) each language's average vector is zero. Iterative Normalization consistently improves word translation accuracy of three CLWE methods, with the largest improvement observed on English-Japanese (from 2% to 44% test accuracy).

##### Abstract (translated by Google)

##### URL
[http://arxiv.org/abs/1906.01622](http://arxiv.org/abs/1906.01622)

##### PDF
[http://arxiv.org/pdf/1906.01622](http://arxiv.org/pdf/1906.01622)


text:
# fish-gruvbox
[gruvbox] theme for [fish shell]

# Install
With [fisherman]
```
fisher install jomik/fish-gruvbox
```

This will expose the function called `theme_gruvbox`.
It is a simple function that takes two arguments.
The first is the mode, either `light` or `dark`.
The second is the contrast, `soft`, `medium` or `hard`.
The defaults are `light` and `medium`.

To automatically apply this theme, call `theme_gruvbox` from your `config.fish`.

[gruvbox]: https://github.com/morhetz/gruvbox
[fish shell]: http://fishshell.com/
[fisherman]: https://github.com/fisherman/fisherman

repository: trescenzi/fish-gruvbox

repo_name: trescenzi/fish-gruvbox


text:
OpenBMP Development Image
----------------------------
This image is the base development image used to build all the OpenBMP
components. It has all the needed dependencies included.

### Build Image

```
docker build -t openbmp/dev-image:build-NNN .
```

### Publish Image to dockerhub

```
# Login to docker
docker login

# Tag the image
docker tag openbmp/dev-image:build-NNN openbmp/dev-image:latest

# Upload the image
docker push openbmp/dev-image:build-NNN
docker push openbmp/dev-image:latest
```

### Running

```
docker run --rm -v $(PWD):/ws -it openbmp/dev-image /bin/bash
```


text:
Replace-Quotes
==============

Replaces smart quotes and dashes, and other annoying characters often generated by Microsoft Word

http://gusruss89.github.io/Replace-Quotes/


text:
---
layout: post
title: Showing Binomial is an Exponential Family with a Natural Parameter
category: Data-Science-1
lang: EN
description: This is an exercise from BDA on page 37
sticky: false
---

This post shows that the binomial is indeed an **exponential family** with **natural parameter** $\text{logit}(\theta)$. Specifically, this exercise comes from Chapter 2 of [_**Bayesian Data Analysis (BDA) 3rd Edition**_](http://www.stat.columbia.edu/~gelman/book/BDA3.pdf) on page 37.

Recall that a binomial distribution whose **likelihood** $\Pr(y \mid \theta, n ) = \text{Bin}(y \mid n, \theta)$ with $n$ known, the **conjugate prior distribution** on $\theta$ is a **beta distribution**. Particularly, the **likelihood** (a _binomial distribution_) is

$$ \begin{equation}
  \Pr( y \mid \theta ) \propto \theta^y (1 - \theta)^{n-y} \tag{1}\label{eq:likelihood}
\end{equation}$$
with $\theta$ denotes a probability of a head occurrence, $n$ is a number of trials, and $y$ expresses a number of head occurences. Additionally, the prior (a _beta distribution_) is

$$ \begin{equation}
  \Pr( \theta ) \propto \theta^{\alpha - 1} (1 - \theta)^{\beta - 1} \tag{2}\label{eq:prior}
\end{equation}$$
with $\alpha$ and $\beta$ denote a number of head and tail occurrences respectively.

We will show that

$$ \begin{equation}
  \Pr(\theta \mid y ) \propto g(\theta)^{\eta + n} \exp{\left( \phi(\theta)^T (\nu + t(y)) \right)} \tag{3}\label{eq:posterior-density}
\end{equation}$$

Actually, Equation \eqref{eq:posterior-density} is a general form which holds for vector $\phi(\theta)$ and both $\eta$ and $\nu$ are constants. Let's start computing the posterior density as follows:

$$ \begin{align}
  \Pr(\theta \mid y ) &\propto \Pr(y \mid \theta) \Pr( \theta )  \tag{4}\label{eq:posterior-start}  && \text{by Bayes Rule} \\
                      &\propto \theta^y (1- \theta)^{n-y} \, \theta^{\alpha - 1} (1 - \theta)^{\beta - 1} \\
                      &= \theta^{y+\alpha-1} (1 - \theta)^{n - y + \beta - 1} \\
                      &= \theta^{y+\alpha-1} \,  \frac{1}{(1 - \theta)^{-n+y-\beta +1}} \\
                      &= \frac{\theta^{\alpha-1}}{(1 - \theta)^{-n-\beta+1}} \, \frac{\theta^y}{(1-\theta)^y} && \text{by rearranging terms} \\
                      &= \frac{\theta^{\alpha-1}}{(1 - \theta)^{-n-\beta+1}} \, \exp{\left( \log{ \left( \frac{\theta}{1-\theta} \right)^y } \right)} \\
                      &= \theta^{\alpha-1} (1 - \theta)^{\beta-1} (1 - \theta)^n \, \exp{( y \; \text{logit}{ (\theta) } )} \\
                      &= \left( \theta^{\frac{\alpha - 1}{n}} (1 - \theta)^{\frac{\beta-1}{n}} (1-\theta)  \right)^n \, \exp{( \text{logit}{ (\theta) } \; y )} \\
                      &= g(\theta)^n \exp{( \phi(\theta) \; t(y) )} && \text{by referring to Equation }\eqref{eq:posterior-density}
\end{align}$$

with $g(\theta) = \left( \theta^{\frac{\alpha - 1}{n}} (1 - \theta)^{\frac{\beta-1}{n}+1} \right)$, $t(y) = y$, and $\phi(\theta) = \text{logit}(\theta)$.
Finally, we have shown that the binomial is indeed an **exponential family** with **natural parameter** $\text{logit}(\theta)$.


text:
[![CircleCI Badge](https://circleci.com/gh/wiyarmir/kotlin-multiplatform-mobile-template.svg?style=svg)](https://circleci.com/gh/wiyarmir/kotlin-multiplatform-mobile-template)
![Kotlin Version](https://img.shields.io/badge/kotlin-v1.4.0-F88909?style=flat&logo=kotlin)

# Kotlin Multiplatform Mobile Template

Template that will give you a ready-to-go project including:

- Android App project with KotlinJVM at [android/](/android)
- iOS App project with KotlinNative at [ios/](/ios)
- Shared network, domain and presentation at [common/](/common)

*Looking for a project with Backend and Web as well? It's here: https://github.com/wiyarmir/kotlin-multiplatform-template*

*Looking for a project with just Backend and Web? It's here: https://github.com/wiyarmir/kotlin-multiplatform-frontend-template*

## Building and running the project

### Android

Open the root project in Android Studio or IntelliJ, and it will recognise the Android App configuration after a
successful Gradle sync. You can use that configuration to run, debug and profile the app.

### iOS

Open the workspace located at [ios/KotlinMultiplatformTemplate.xcworkspace](/ios/KotlinMultiplatformTemplate.xcworkspace)
in XCode. The Podfile includes an entry to the common code with an extra user script for it to be recompiled as a build
step.

## Contributing

If you would like to contribute code to this repository you can do so through GitHub by creating a new branch in the repository and sending a pull request or opening an issue. Please, remember that there are some requirements you have to pass before accepting your contribution:

* Write clean code and test it.
* The code written will have to match the product owner requirements.
* Follow the repository code style.
* Write good commit messages.
* Do not send pull requests without checking if the project build is OK in the CI environment.
* Review if your changes affects the repository documentation and update it.
* Describe the PR content and don't hesitate to add comments to explain us why you've added or changed something.

## License

    Copyright 2019 Kotlin Multiplatform Template

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

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

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