text:
# Docker under macOS

c.f.

 * [General](./docker.md) information
 * Use Docker for [Android CI](./docker.andorid.md)

We use [Docker for Mac](https://docs.docker.com/docker-for-mac/), older Mac's may need [Docker Toolbox](https://www.docker.com/products/docker-toolbox), but that's not discussed further here.

Unfortunatly there are some issues with the Docker VM ineracting with the `adb` Android emulator VM.

docker
> ps
> information
> version
> images

# `boot2docker`

Located here - `/usr/local/share/boot2docker`

# `docker-machine`

is the OS-X VM used to run Docker. A nice command would be `docker-machine inspect default` or `docker-machine start`. The default machine is called `default`.

If the network has broken things (as mine often does) then a quick `docker-machine restart` & `docker-machine env` / `eval $(docker-machine env)` may help.

Read the [docs](https://docs.docker.com/engine/installation/mac/) for more details.

```
docker run gliderlabs/alpine echo Hello Rik

Run 'Docket Quickstart Terminal', then `eval $(docker-machine env)`

docker-machine start
docker-machine inspect default
docker-machine restart

docker images
docker images
docker run rikwatson/docker-whale
docker run cellofellow/ffmpeg
docker ps
docker run hello-world
docker run -it ubuntu bash
```

```
service docker[.io] status
```

```
$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
c04b14da8d14: Pull complete
Digest: sha256:0256e8a36e2070f7bf2d0b0763dbabdd67798512411de4cdcf9431a1feb60fd9
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker Hub account:
 https://hub.docker.com

For more examples and ideas, visit:
 https://docs.docker.com/engine/userguide/
```

repository: rikwatson/notes

repo_name: rikwatson/notes


text:
# Inventory Management System
Created by: ITWS Web Science Group 1 Section 2

Members: Logan Ramos, Andrew Qu, Jeff Fang, Jelly Wang

To run please ensure you have Docker, Docker-Compose, and NPM on your system.

This inventory website utilizes the latest Node.js version, latest Angular version, and latest MongoDB version.

In the root directory run docker-compose up. The first time you use it, it will take quite awhile as it fetches all the packages.
If you would like to not have red squigglys in your code editor then I recommend you run npm install in angular-app and express-server so that
your code editor is able to find the packages, however, this is not necessary.

After your docker has started any changes you make will auto update and restart the necessary servers.

Angular Server: localhost:4200
Express Server: lobaclhost:3000
MongoDB: localhost:27017
Mongo's Express interface (sort of like PhpMyAdmin): localhost:8081

license: MIT

repository: rpiambulance/inventory-management

branch_name: refs/heads/master

extension: md

gha_language: JavaScript

gha_license_id: MIT

license_type: permissive

repo_name: rpiambulance/inventory-management


text:
---
title: Pipit
date: 1923-09-01
image: /uploads/2.jpg
tags: fauna
---

![](/uploads/2.jpg)

The Pipit song in many of its phases is strikingly like that of the Rock Wren (Salpinctes obsoletus). It has the same vivacity and ringing quality, though perhaps less power, and the similarity extends to the very phrasing. An alarm note runs pichoo pichoo pichoo, given six or seven times, rapidly and emphatically; while another, wee iich, wee iich, we iich, is rendered, unless my eyes deceive me, with the same springing motion which characterizes the Wren. An ecstasy song of courting time (heard on Mount Rainier) runs twiss twiss twiss twiss (ad lib.), uttered as rapidly as the syllables may be said. It is delivered as the bird describes great slow circles in mid-air; and when the singer is exhausted by his efforts, he falls like a spent rocket to the ground.

[Source](https://flic.kr/p/w7kMUW)

repository: justinjaywang/jekyll-theme-cypress

extension: markdown

repo_name: justinjaywang/jekyll-theme-cypress


text:
# AutoAPI L13 Extensions #2 Changelog

**Level 13** _2nd extension_ (aka **L13.2**) contains only additive updates to the protocol.
These include new properties for existing capabilities with some new custom types, and a few additions to already existing enums.

Changes from L13.1 are divided into these sub-sections:

* [Custom Types](#custom-types)
* [Unit Types](#unit-types)
* [Enums](#enums)
* [Properties](#properties)

## Custom Types

The update brings some new *custom_types* to the spec.

- `acceleration_duration`
- `accelerator_duration`
- `driving_mode_phev`

## Unit Types

A new duration *unit_type* is added to the spec.

- `duration.milliseconds`

## Enums

Some enums have gained new values.

- `charging.status` (added `flap_open`)
- `custom_types.dashboard_light.name` (added `diesel_oil_filter_water_presence`, `engine_drag_torque_control_failure`)
- `custom_types.seat_location` (added `driver`, `passenger`)
- `trips.event` (added `emergency_braking`)

## Properties

New properties added to pre-existing capabilities:

- _charging_
  - `driving_mode_phev`
  - `battery_charge_type`
  - `distance_to_complete_charge`
- _diagnostics_
  - `passenger_airbag_status`
- _race_
  - `accelerator_duration`
- _trips_
  - `braking_count`
- _usage_
  - `acceleration_durations`

repository: highmobility/auto-api

repo_name: highmobility/auto-api


text:
# Events: ScheduledJobs

Actions to perform when the scheduler service exists in the container.

| Subscriber (method)   | Event     | Priority |
|-----------------------|-----------|----------|
| [schedule](#schedule) | `app.cli` | 5        |

## schedule

Add scheduled jobs to scheduler.
For more information, see [Scheduler service](https://github.com/bayfrontmedia/bones/blob/master/docs/services/scheduler.md).

repository: bayfrontmedia/bones-web

gha_language: PHP

repo_name: bayfrontmedia/bones-web


text:
# spring-boot-testcontainers-docker
Spring boot with testcontainers and building in docker

[![Build Status](https://travis-ci.org/modestukasai/spring-boot-testcontainers-docker.svg?branch=master)](https://travis-ci.org/modestukasai/spring-boot-testcontainers-docker)

# How to run
* Run command `./gradlew build` to see that locally the test does not fail.

license: Unlicense


text:
# Authors

This list is sorted by the number of commits per contributor in _descending_ order.

Avatar|Contributor|Contributions
:-:|---|:-:
|[@myii](https://github.com/myii)|57
|[@n-rodriguez](https://github.com/n-rodriguez)|19
|[@dafyddj](https://github.com/dafyddj)|2
|[@herbetom](https://github.com/herbetom)|1

---

Auto-generated by a [forked version](https://github.com/myii/maintainer) of [gaocegege/maintainer](https://github.com/gaocegege/maintainer) on 2020-12-16.

repository: saltstack-formulas/telegraf-formula

gha_language: Jinja

repo_name: saltstack-formulas/telegraf-formula


text:
# module `foundry.https_upload`
Private utility methods to upload files and/or folders to Globus using HTTPS instead of Globus Transfer.

---

## function `upload_to_endpoint`

```python
upload_to_endpoint(
    auths: PubAuths,
    local_data_path: str,
    endpoint_id: str = '82f1b5c6-6e9b-11e5-ba47-22000b92c6ec',
    dest_parent: str = None,
    dest_child: str = None
) → Tuple[str, str]
```

Upload local data to a Globus endpoint using HTTPS PUT requests. Data can be a folder or an individual file.

**Args:**

 - `auths` (PubAuths):  Dataclass of authorizers needed for upload. Includes `transfer_client`, `auth_client_openid`,
 - `and `endpoint_auth_clients`, which is a Dict of `endpoint_id``: AuthClient mappings.
 - `local_data_path` (str):  Path to the local dataset to publish to Foundry via HTTPS. Creates an HTTPS PUT  request to upload the data specified to a Globus endpoint (default is NCSA endpoint) before it is  transferred to MDF.
 - `endpoint_id` (str):  Globus endpoint ID to upload the data to. Default is NCSA endpoint. Must match the  `endpoint_id` auth'd in `auths.auth_client_gcs`.

Returns
------- (str) Globus data source URL: URL pointing to the data on the Globus endpoint

---

_This file was automatically generated via [lazydocs](https://github.com/ml-tooling/lazydocs)._

branch_name: refs/heads/main

gha_language: Python


text:
Meta C - Quasi-quotation of ANSI C99 syntax
-----

Writing C is a labor, but writing Haskell causes you fever.

Let's generate real world codes by statically typed code generator, using Template Haskell.

## Quasi-quotation

Each of the following quasi-quotations convert the inside string into an abstract syntax tree data type defined in `Language.Meta.C99.AST`.

 * Translation unit `[c| ... |]`

 * Statements `[cs| ... |]`

 * Expression `[ce| ... |]`

Every AST data types is an instance of `Show`.

### Example

```hs
import Language.Meta.C99.Quote

-- Translation unit [c| ... |]
translation_unit :: String
translation_unit = show [c|
int main(int argc, char **argv)
{
    printf("hello world!\n");

    return 0;
}
|]

-- Statements [cs| ... |]
statements :: String
statements = show [cs|
    while (1) {
        printf("hello world!\n");
    }
|]

-- Expression [ce| ... |]
expression :: String
expression = show [ce| x * y * z |]
```

## Anti-quotation

 Quoted string can have anti-quotes in the following formats.

 * `${}` takes a `String` variable

 * `${<exp>}` executes arbitrary haskell expression of type `String`

Replacement targets are statements, expressions, external declarations, part of identifiers, and inside of string literals.

### Example

```ghci
> :t [ce| x + ${} |]
[ce| x + ${} |] :: [Char] -> Language.Meta.C99.AST.Exp
> [ce| x + ${} |] "y"
x + y
> :t  [ce| ${} + ${} |]
[ce| ${} + ${} |]
  :: String -> String -> Language.Meta.C99.AST.Exp
> [ce| ${} + ${} |] "x" "y"
x + y
> [ce| x + ${"y"} |]
x + y
> [cs| foo_${}(); |] "bar"
foo_bar();
> [ce| printf("${show [1,2,3,4]}\n") |]
printf("[1,2,3,4]\n")
```

## Limitation

 * Preprocessing is not performed in quoted strings. This means macros for syntax modification could not be parsed.

```c
#define LOOP(i, n) for (i = 0; i < n; ++i)

LOOP(i, 10) {
    // parse error
}
```

 * Comments inside a statement or decalaration causes parse error.

```c
int /* parse error */ x;

struct x {
    int x; // parse error
};
```

 * Context-sensitive portion of grammers will not be parsed appropriately.

```c
typedef int x;

x * x; // either expression (x * x) or declaration (int *x)

x(y); // either function call (x(y)) or declaration (int (y))
```

  However, those kind of misinterpretations do not really matter when you only concern about their literal representations.

 * Quasi-quotations could not be nested inside an anti-quotation.

```hs
code = [c| int x = ${ show [ce| x * x |] }; |] -- quotes can not be nested here
```

 * Trigraph/Digraph is not supported (who knows).

## Standard

C99 (ISO/IEC 9899:TC3)

## License

  MIT

repository: ykst/MetaC

repo_name: ykst/MetaC


text:
# Pachyderm Client for Scala

This is a Scala client for [Pachyderm](https://www.pachyderm.io/).
It uses a modified version of the [pfs.proto](https://github.com/pachyderm/pachyderm/blob/master/src/client/pfs/pfs.proto) file
to automatically generate an asyncrhonous Future-based gRPC client.

Currently the client is pretty barebones to the Protobuf-based client,
but we will be adding some nice abstractions and utilities to make
things like committing multiple files asynchronously easy. In addition,
we will create an Akka-based version of the client that will allow for
truly asynchronous IO and easy integration with Akka-stream based
applications.

## Installation

`pachyderm-client` is cross-compiled for Scala 2.11 and 2.12 and is
available on Maven Central for release versions and OSS Sonatype
Snapshots for snapshot versions.

### Snapshot Versions

```sbt
// Add OSS Sonatype Snapshots repository
resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

// Add pachyderm-client dependency
libraryDependencies ++= "ml.combust.pachyderm" %% "pachyderm-client" % "0.1.0-SNAPSHOT"
```

### Release Versions

Releases are hosted on Maven Central, which is a default SBT resolver.

```sbt
// Add pachyderm-client dependency
libraryDependencies ++= "ml.combust.pachyderm" %% "pachyderm-client" % "0.1.0"
```

## Running Tests

To test locally, follow the [instruction](http://pachyderm.readthedocs.io/en/stable/getting_started/local_installation.html) for getting a local Pachyderm
cluster running. After you have Pachyderm running locally, make sure you
have port forwarding enabled. The tests will use a shell to determine
the host IP for Pachyderm and uses a hardcoded port of 30650.

```bash
sbt pachyderm-client/test
```

## Basic Usage

Make sure you can run the tests using the instructions in the previous
section.

```bash
pachctl port-forward &
```

By default Pachyderm runs on port 30650 and the IP address of the
Pachyderm daemon can be determined using:

```bash
minikube ip
```

Once you have the port and host IP for the Pachyderm daemon, we can
connect to it using the Scala client.

```scala
import sys.process.Process
import ml.combust.pachyderm.client.Client

// Use a shell process to get the host IP for Pachyderm
val hostIp = Process("minikube ip").lineStream.head

// Use default port to connect
val port = 30650

// Connect our gRPC client to Pachyderm
val client = Client(hostIp, port)

// Create a repo
client.createRepo("my_test_repo")

// List all repos
client.listRepo()

// Inspect a repo
client.inspectRepo("my_test_repo")

// Delete a repo
client.deleteRepo("my_test_repo")
```

### Working with Commits

TODO: Still working on nice utilities for simplifying commits

### Block API

TODO: Still need to make the Block API integration

repository: combust/pachyderm-client

repo_name: combust/pachyderm-client


text:
# swagger-express-demo
Demo of swagger with express app

## Overview
Express REST APIs can be created adhering to [OpenAPI spec](https://github.com/OAI/OpenAPI-Specification) using [Swagger editor](http://editor.swagger.io/), [swaggerize-express](https://github.com/krakenjs/swaggerize-express), [Swagger UI](https://github.com/swagger-api/swagger-ui), [swagger-ui-express](https://github.com/scottie1984/swagger-ui-express).

    1. Design your APIs using Swagger editor
    2. Desgin in YAML mode as it is more readable and download the spec in JSON mode.
    3. Install Yoeman - `npm install -g yo`
    4. Install swaggerize-express generator - `npm install -g generator-swaggerize`
    5. Create you project folder and run - `yo swaggerize`
    6. Point to the downloaded swagger spec json and choose express as the framework.
    7. In the generated code, make changes to the express app as per your needs.
    8. This results in a working express app serving your APIs.
    9. To add Swagger UI support in your app, there are two options,
        a. swagger-ui-express to serve default swagger UI.
        b. Directly using swagger ui in a public folder if customization is needed.

repository: theleapofcode/swagger-express-demo

repo_name: theleapofcode/swagger-express-demo


text:
# faq-virtual-agent
Build your faq virtual agent in 5 minutes

1. Run Jupyter notebook for quick changes and experiments
2. Run virtual_agent.py to start the virtual agent on interactive mode. It also auto-trains the virtual agent for the first time on the dataset faqs.csv


text:
###### CS-E4300 Network Security, Aalto University 2021-2022

### Virtual network environment for student projects

_Authors: Tuomas Aura, Aleksi Peltonen, Thanh Bui_

This project contains a testbed network setup for _Vagrant_ and _VirtualBox_. The testbed is intended for a specific course project at _Aalto University_, but it has been used in research for other experiments.

## Network Overview

![Network Setup](./img/setup.png)

The testbed is initially configured so that the clients (IoT devices) in each customer’s network access a local server. Your goal is to relocate the server functionality from the customers’ local networks to a cloud platform, which is represented by the network on the right-hand side. The Router in the above topology represents routing across the Internet between the customer sites and the cloud. The project will mostly require configuring VPN connections and firewall rules on the gateway routers. See the project instructions provided in the course.

Each element of the testbed (i.e. client, server, gateway router is a separate VM that is created based on the base VM. The linked clone VMs are quite memory efficient, and the amount of available memory should not be an issue. The process for creating the testbed will be explained below.

The customer's local network uses the private IP address range <IP_ADDRESS>/16. The client gateways have NATs. The cloud-side gateway, on the other hand, is currently a simple gateway router with no NAT or even firewall configured. The address space <IP_ADDRESS>/12 simulates public, routable IPv4 addresses (even though it really is a private address range). The cloud servers in this case are configured with routable IP addresses. This way, the clients can start communication with the data center, but not the other way around. You may want to change this so that the cloud servers are in a private address space, both for better security and to save on IPv4 addresses.

The Router VM simulates the public Internet between the sites. It also provides a connection to the real Internet, which is needed for downloading software. To enable the routing, you need to start at minimum the client or server VM, the corresponding gateway VMs, and the Router VM. Then, connections from the client or server VM will be routed to the real Internet via the Router.

The Vagrant network (interface _enp0s3_ on each host, IP addresses <IP_ADDRESS>/16) can be mostly ignored. It exists to enable admin access to the VMs with _vagrant ssh_. However, when you modify routing tables, you may want to check with ```route -n``` that this interface does not accidentally become the default gateway on any node. All connections between sites and to the real Internet should be routed via the Router VM.

## Client and Server Apps

In each customer site, i.e. IoT client network, there is one VM (S) with the IP address <IP_ADDRESS> that currently acts as the local server. The server app is placed in the VM at _/home/vagrant/server-app_ on the server. It is written in NodeJS. Use _vagrant ssh_ to connect to the server VM, go to the server app directory, and run ```npm start``` to start the server. Once it is started, it listens on port 8080 for HTTP requests. Similarly, the client app is placed inside each client VM at _/home/vagrant/client-app_. When you start the client app, it tries to send requests to the local server once a second. You can edit the configuration file _config.json_ to change the server address, e.g. to send the requests to a cloud server. You may  modify client and server app and their configuration as needed for moving the server functionality to the cloud, but one goal is to keep the changes relatively small.

## Network Setup

1. Download and install the latest version of [Vagrant](https://www.vagrantup.com/docs/installation).

2. Initialize base VM:

The commands for building the base VM are provided in a simple Makefile (for Linux) and PowerShell script (for Windows). If the scripts do no work on your computer, simply run the commands manually. You only need to build the base VM once.

Linux:

```bash
cd base/
make
```

Windows PowerShell:

```
cd base/
./make.ps1
```

3. Initialize the other VMs:

```bash
vagrant up
```

### Useful Vagrant commands

Initialize a specific VM or all VMs:

```bash
vagrant up [vm]
```

SSH into VM:

```bash
vagrant ssh [vm]
```

Halt and restart one VM or all VMs:

```bash
vagrant halt [vm]
vagrant up [vm]
```

Start from the beginning by destroying and recreating the VMs. *Write you configuration as scripts that can be easily rerun on clean VMs. Do not rely on any VM state that is lost during VM restart or reset!*

```bash
vagrant destroy -f
vagrant up
```

Destroy and recreate one VM or all VMs:

```bash
vagrant destroy [vm]
vagrant up [vm]
```

### Useful commands on guest VMs

```bash
ip a
route -n
ping <IP_ADDRESS>
traceroute -n <IP_ADDRESS>
netcat -l -p 33445
netcat <IP_ADDRESS> 33445
sudo tcpdump -i enp0s8
sudo iptables -L
sudo iptables-save
sudo iptables-save > /etc/iptables/rules.v4
sudo ipsec statusall
sudo ip xfrm policy
sudo ip xfrm state
sudo tcpdump esp
sudo conntrack -L
```
## Useful files on guest VMs

```bash
/etc/ipsec.conf
/etc/ipsec.d/
/etc/ipsec.secrets
/etc/iptables/rules.v4
/var/log/syslog
```

## What should you modify?

You should package your project solution to a small number of scripts and configuration files.

You can make changes to the configuration scripts on the _scripts/_ folder. However, do not modify _router.sh_ because the Router simulates the public Internet, which you are not able to reconfigure.

Additionally, you may want to change the cloud network to use a private IPv4 address space. It may be easiest to modify the IP addresses in _Vagrantfile_. Avoid making other changes to _Vagrantfile_. It is not strictly forbidden, though, if technically justified.


text:
# Printing Portal

Table of Contents

      About The Project

Built With

      Getting Started

Installation

Running The App

Running Unit Tests

Roadmap / Kanban Board

Database Design

Test Coverage

License

Contact

Acknowledgements

## About The Project

This project was created as a simple solution for inventory management of art prints and other print related products.
After login, the user can enter a new print order selecting from the database defined list of designs, paper types and sizes. The order can clear or checkout, at which the user can view the print order history and aggregate print inventory.

This web application was built with Flask blueprints and is designed to be modulary added to other Flask projects.

### Built With

* Flask, Flask-Login, Flask-WTF
* SQLAlchemy, MySQL
* Flask-Migrate

## Getting Started

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

### Installation

1. Clone the repo:
   ```sh
   git clone https://github.com/OrigamiCranes/PrintingPortal.git
   ```
2. Install pip packages:
   ```sh
   pip install requirements.txt
   ```
3. Rename 'example_config.py' to 'config.py', update file variables; SQLALCHEMY_DATABASE_URI and SECRET_KEY

4. Run flask to update database schema:
   ```sh
   flask upgrade
   ```

### Running The App

1. If Windows use flask for development only:
    ```sh
   flask run -h localhost
   ```
2. If Linux use the superior gunicorn deployment:
   ```sh
   gunicorn --workers=2 --bind=<IP_ADDRESS>:5000 app:app
   ```
### Running Unit Tests

1. Run one of the pytest syntax's below:
   ```sh
   pytest --cov=app
   pytest --cov=app --cov-report term-missing
   pytest --cov=app --cov-report html
   ```

## Roadmap / Kanban Board

This app was developed with an agile approach, the roadmap and kanban board can be found in the
[projects section](https://github.com/OrigamiCranes/PrintingPortal/projects/1) on the github repo.

## Database Design

### Printing ERD

The design of the printing ERD evolved over three iterations; MVP, V2 and V3.

* MVP: Covers the PrintOrder form and viewable OrderHistory, along with three single column tables for system dependant variables.

* V2: Adds the PrintInventory to the ERD

* V3: **_(Future release)_** Creates a near identincal twin structure of V2, which allows the user to conduct paper orders for inventory tracking paper supplies.

![Database ERD](./readme/databaseERD.png "Database ERD")

### Authentication ERD

The authentication section of the database is defined the same as the [Miguel Grinberg Flask-login tutorial.](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins)

![Database ERD](./readme/authERD.png "Database ERD")

## Test Coverage
The unit testing assures that all routes are accessible, all database CRUD functions are working correctly and that any error values do not corrupt the database. The tests also check the formfactory outputs the correct forms.

Testing of route form requests was out of the scope of these tests due to the use of QuerySelectFields used in forms, which made direct testing impracticable. This was deemed acceptable as these sections of the code were essentially passing on variables to other route redirects, which have been tested directly.

![Test Coverage](./readme/coverage.png "Database ERD")

## License

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

## Contact

Jack McKeon -<EMAIL_ADDRESS>
Project Link: [https://github.com/OrigamiCranes/PrintingPortal](https://github.com/OrigamiCranes/PrintingPortal)

## Acknowledgements

* QA Academy DevOps Fundamental Project

repository: OrigamiCranes/PrintingPortal

repo_name: OrigamiCranes/PrintingPortal


text:
# Owin
An OWIN server and Web API library for .NET Framework 4.6.1+, Mono and DotNET Core 3+.

## Why?

This project came about because Microsoft's OWIN library only targets .NET Framework, and I had
a need for an OWIN library and Web API framework that targets both .NET Framework and DotNET Core.
The .NET Framework build had to be capable of running under Mono.

I considered using Microsoft's OWIN under the .NET Framework / Mono and DotNet Core's web pages
under DotNET Core. The intention was to write an abstraction layer that would hide the implementation
details from the rest of the program and behind the scenes it would use the appropriate library for
the platform that was being built. However I think that would have got messy, especially considering
that both web API schemes involve base classes for the controllers. Those base classes would be hard
to hide from things that are using the abstraction.

I did consider using Nancy. However, Nancy does not support weak wildcards when configuring HTTP.SYS
profiles and there was no appetite to add support for them. I needed weak wildcard support.

## Packages
* **AWhewell.Owin**: An OWIN compliant server.
* **AWhewell.Owin.Host.HttpListener**: HTTP.sys hosting for OWIN server.
* **AWhewell.Owin.Host.Ram**: In-memory hosting for OWIN server.
* **AWhewell.Owin.Utility**: Utility classes usable with any OWIN server.
* **AWhewell.Owin.WebApi**: Web API framework usable with any OWIN server.

## Interfaces

With the exception of **Owin.Utility**, which is intended to be agnostic to the OWIN implementation
that it is used with, the packages make extensive use of interfaces. The program does not
instantiate classes directly, instead it uses a class factory to create instances of interfaces.

The OWIN library was written for use with [Virtual Radar Server](https://github.com/vradarserver/vrs)
so it uses the same class factory that VRS uses. See the repository for more details:

https://github.com/awhewell/interface-factory

#### Initialisation

You need to initialise the Owin library on startup:

````
using InterfaceFactory;
...
AWhewell.Owin.Implementations.Register(Factory.Singleton);
````

Each package, except Owin.Utility, has its own ````Implementations```` class that needs to be
initialised with ````Factory.Singleton````.

#### Creating an instance of an interface

````
var pipelineBuilder = Factory.Resolve<IPipelineBuilder>();
pipelineBuilder.RegisterCallback(... etc. ...);
````

## Building the Pipeline

Virtual Radar Server has a plugin architecture. Plugins are loaded at runtime. They must
be able to add middleware freely to the OWIN pipeline.

One of the issues that VRS faced with the Microsoft OWIN pipeline is that it needed middleware
to be added in the same order that it appears in the pipeline. That is hard to arrange when some
of the middleware is spread across plugins that are not known about until runtime.

The intention with this library is to support the registration of pipeline middleware in any order.
This support involves associating a priority with each bit of middleware.

1. At program startup the main program and all plugins register callbacks with `IPipelineBuilder`.

   This interface is not a singleton and all parts of the program that want to add to the pipeline
   need to register themselves with the same builder, so it is up to the program to arrange the
   sharing of a single builder instance.

   Each callback registered with the builder is assigned a priority. It is up to the program and
   the plugins to decide how priorities are assigned.

2. Whenever a pipeline needs to be built the program should call `CreatePipeline` on the builder,
   passing into it a new instance of an `IPipelineBuilderEnvironment`.

   The builder will call each callback in ascending order of priority. Each callback is passed the
   pipeline builder environment. The environment has methods on it to register AppFunc builders in
   a similar fashion to Microsoft's OWIN library.

   The environment also has a `Properties` dictionary that contains information about the server
   environment, as per section 4 (Application Startup) of the OWIN 1.0.0 spec.

The result of calling `CreatePipeline` is an `IPipeline` object. The pipeline has a `ProcessRequest`
method that can be used to send a request (as described by a standard OWIN environment dictionary)
through the pipeline.

### Middleware vs. Stream Manipulators

The Microsoft OWIN library breaks middleware into discrete functions that are chained together
to form the processing pipeline for a web request.

The **Owin** package adds the concept of stream manipulators. Virtual Radar Server has a requirement
for tasks that modify the response that middleware creates - for example, a task that might compress
the result if the request asked for compression. These tasks differ from normal middleware in that
they must not be skippable. Normal middleware will not be called if an earlier middleware function
decided not to call the next middleware in the chain. That can't happen with stream manipulators,
they are always called regardless of what happened in the middleware chain.

The `IPipelineBuilderEnvironment` object has a method called `UseStreamManipulatorBuilder` which
creates an AppFunc middleware function. Stream manipulators are identical to middleware in all but
three aspects:

1. They have their own set of priorities and are always called *after* the middleware chain has
   been called.

2. The builder is passed a "next" AppFunc, just like a middleware builder. However, this "next"
   AppFunc is a stub. It does not matter whether the stream manipulator AppFunc calls it or not,
   it will not influence whether the other stream manipulators get called.

3. If a stream manipulator is registered then the `IPipeline` implementation will replace the response
   stream with a memory stream. It will copy the content of the memory stream back to the original
   response stream once all of the stream manipulators have finished running.

   The switching out of the host's response stream with a memory stream lets stream manipulators work
   with hosts that use a forward-only response stream.

## Building and Running the Server

The **Owin** package only deals with building and processing the pipeline. It declares an
interface for hosts (`IHost`) but it does not contain an implementation.

As of time of writing there are two implementations of `IHost`:

* An `HttpListener` based implementation in **Owin.Host.HttpListener**. The interface is
  `IHostHttpListener`.
* An in-memory implementation in **Owin.Host.Ram**. The interface is `IHostRam`.

Every host has some standard properties that need to be supplied (the port to listen on etc., see
`IHost`).

Once a host has been instantiated and its properties set up you need to initialise it once with
a call to `Initialise`. This method is passed a pipeline builder and an environment. The host
sets up the environment properties, calls the builder to create a pipeline and then uses the
resulting pipeline to process requests.

This means that pipeline instances are tied to a single instance of a host, they are not shared
between hosts.

`IHost` contains methods to start and stop the server.

## Web API

One of the main reasons for writing a proprietary OWIN server for Virtual Radar Server is because
Microsoft's Web API is not cross platform. VRS needs a web API that runs unchanged across all three
.NET platforms.

The **Owin.WebApi** package is similar in operation to Microsoft's Web API 2 but with some notable
differences:

1. Controllers do not have a base class. Instead they must implement `IApiController`. The interface
   only has one property - `OwinEnvironment`, which is an environment dictionary. This always gets
   filled before the route method is called.

2. Public methods on a controller are not automatically exposed as endpoints. You must expose every
   endpoint with the `Route` attribute. This is more cumbersome than Microsoft's approach but it
   should make it harder to accidentally expose methods.

3. You can tag static methods as routes. The restriction is that the method must accept an OWIN
   environment dictionary as one of its parameters.

4. You can tag void methods as routes. The route will have to set up the OWIN environment for itself
   if it wants to return anything, although if it doesn't assign a status code then the API will
   return 200 on its behalf.

### Adding the Web API to a Pipeline

You must register a callback with the `IPipelineBuilder` that the program is using. The callback
must instantiate `IWebApiMiddleware`. This interface has a method called `AppFuncBuilder`, you
call that to obtain a standard OWIN **AppFunc** and then pass that to the builder environment
function `UseMiddlewareBuilder`.

The `IWebApiMiddleware` has properties that let you configure the web API's behaviour.

### Use with other OWIN environments

The web API depends on **Owin.Utility** but neither the web API nor the utility package depend on
the **Owin** package. You should be able to use the web API with any OWIN environment. You just
need to arrange for a call to `IWebApiMiddleware.AppFuncBuilder` and then add it to the OWIN
pipeline as you would any other bit of middleware.

## Utility

The **Owin.Utility** package is a set of enums and helper classes that are agnostic to the
OWIN library in use. You should be able to use them with any OWIN environment.

The library does not use the class factory. It has no dependencies on any other package.

repository: awhewell/owin

gha_language: C#

repo_name: awhewell/owin


text:
#### `master` [![CircleCI](https://circleci.com/gh/PMA-2020/ppp-web/tree/master.svg?style=svg&circle-token=0b12f45f6961554acbe0c97101b4a61cbed320ca)](https://circleci.com/gh/PMA-2020/ppp-web/tree/master) |  `develop` [![CircleCI](https://circleci.com/gh/PMA-2020/ppp-web/tree/develop.svg?style=svg&circle-token=0b12f45f6961554acbe0c97101b4a61cbed320ca)](https://circleci.com/gh/PMA-2020/ppp-web/tree/develop)

# PPP
## About
PPP is a project with the purpose of helping people convert XlsForm Excel files into more human-readable, printable formats, commonly called "paper questionnaires". Officially, PPP stands for "Pretty PDF Printer", but other formats are supported. The project consists of...

- A [web application](https://github.com/pma-2020/ppp-web)
- A [command line tool](https://github.com/pma-2020/ppp)

Both tools are open source and free to install. You can also use it online with no installation necessary, at http://ppp.pma2020.org.

#### Samples
- Source Excel file: [demo.xlsx](docs/demo.xlsx)
- Converted to PDF: [demo.pdf](docs/demo.pdf)
- Converted to DOC: [demo.doc](docs/demo.doc)
- Manually saved as DOCX from DOC: [demo.docx](docs/demo.docx)
- Converted to HTML: [demo.html](docs/demo.html)

**Example Screenshot**

![demo.png](docs/demo.png)

## Application Internals

Application contains only one page with web form, where user can upload an ODK XlsForms file
for conversion to HTML, PDF of DOC format.

#### UI libraries:
- [Twitter Bootstrap](http://getbootstrap.com/)
- [Bootstrap File Input](http://plugins.krajee.com/file-input)
- [jQuery v2.2.4](https://jquery.com/)
- [Notify.js](https://notifyjs.com/)

#### Backend libraries:
- [Flask](http://flask.pocoo.org/)
- [wkhtmltopdf](https://wkhtmltopdf.org/)

#### Tips
- Backend: conversion to DOC format implemented as conversion to HTML file and returning this HTML file to user
with .doc extension instead of .html, as office programs understands how to render such files.
- Backend: conversion to PDF format implemented as conversion to HTML with next conversion to PDF using **wkhtmltopdf** external tool.
- UI: After successful uploading, form will be cleared automatically.
- UI: If something was wrong while processing the file, page will be reloaded and error message will be shown.
- UI: manually selecting/deselecting conversion options will activate "Custom" preset button.

# Deployment

#### 1. Update system and install required packages
This deployment guide is written for [*Ubuntu*](https://www.linode.com/docs/getting-started/#ubuntu-debian). For other Linux distributions, please refer to this [handy setup guide](https://www.linode.com/docs/getting-started/#install-software-updates), especially if using *Linode*.

`apt-get update && apt-get upgrade`

> **Note**
> Ubuntu may prompt you when the Grub package is updated. If prompted, select keep the local version currently installed.

`apt-get install htop libfontconfig1 libxrender1 python3-pip python3-dev python3-venv nginx git vim`

#### 2. Clone project from repo

`cd /opt`

`/opt $` `git clone https://github.com/PMA-2020/ppp-web.git`

#### 3. Create virtual environment

`/opt $` `cd ppp-web`

`/opt/ppp-web $` `python3 -m venv .venv`

`/opt/ppp-web $` `source .venv/bin/activate`

`/opt/ppp-web $` `pip install --upgrade pip`

#### 4. Dependencies
Install project dependencies

`/opt/ppp-web $` `pip install -r requirements.txt`

Install pmix package

`/opt/ppp-web $ pip install -r https://raw.githubusercontent.com/<git-suburl>/requirements.txt`
> **Example**
> `pip install -r https://raw.githubusercontent.com/jkpr/pmix/develop/requirements.txt`

> **Note**
> You may experience a `DistutilsError` related to the `cairocffi` package. If this occurs, it is likely OK to ignore, as this is a peer dependency and not required for PPP-Web.

`/opt/ppp-web $ pip install https://github.com/<git-suburl>`
> **Examples**
> `pip install https://github.com/jkpr/pmix/archive/develop.zip`
> `pip install https://github.com/joeflack4/pmix/archive/ppp.zip`

#### 5. Required Configuration
##### Change Python executable path
Edit config.py
`/opt/ppp-web $` `cd ppp_web`
`/opt/ppp-web/ppp_web $` `vim app_instance/config.py`

Set Python executable variable
`PYTHON_PATH='/opt/ppp-web/.venv/bin/python3'`

##### Set execution flag for dependency *wkhtmltopdf*

`/opt/ppp-web/ppp_web $` `chmod +x bin/wkhtmltopdf`

#### 6. Set up logging
`mkdir logs/`
`touch access-logfile.log && touch error-logfile.log`

#### 7. Run server process
Run the app_instance in background

`/opt/ppp-web/ppp_web $` `gunicorn -b <IP_ADDRESS>:8080 run:app_instance &`

Open web interface at address

`https://<server-ip>:8080`

You're finished!

## Maintenance
### Upgrading PPP-Web
#### Log in to server & activate environment
> Common Workflows > [Logging in to server](#logging-in-to-server)
> Common Workflows > [Activate virtual environment](#activate-virtual-environment)

There are several options from here. One option to get changes is to checkout a
remote branch locally and reapply a change *config.py* as shown in the first
part of step (5) in the *Deployment* section. Another option is to back up and
clone a fresh copy of the repo. Another option is to stash any current changes,
rebase/merge, and recover the stash. Another option is to commit any current
changes and then do a rebase of the/a remote branch onto the/a local one.
That's the one we'll show here.

#### Backup current install (optional)
This step is optional, as git in itself is a backup mechanism.

`cd /opt/`
`mkdir _archive` *(if it doesn't exist)*
`mv ppp-web _archive/DATE`
> **Example**
> `mv ppp-web _archive/2018-02-20`

#### Commit local changes
Add local changes to staging
`git add .`

Commit local changes. If all you've done during/since deployment is change
config.py, the following message should do.
`git commit -m "Updated PYTHON_PATH path in config.py during deployment
installation process."`

#### Get remote changes
Add any additonal remotes if required to fetch from

`git remote add trunk https://github.com/PMA-2020/ppp-web.git`
> **Example**
> ```
> git remote add trunk https://github.com/PMA-2020/ppp-web.git && \
> git remote add joeflack4 https://github.com/joeflack4/ppp-web.git
> ```

Fetch changes

`git fetch --all`

Merge in changes using rebase
`git rebase REMOTE/BRANCH`
> **Example**
> `git rebase trunk/master`

#### [Start](#starting-the-server) or [restart](#restarting-the-server) server
> Common Workflows > [Starting the server](#starting-the-server)

### Upgrading Dependencies
#### Log in to server & activate environment
> Common Workflows > [Logging in to server](#logging-in-to-server)
> Common Workflows > [Activate virtual environment](#activate-virtual-environment)

#### Upgrade dependency
`python -m pip install <url-to-dependency> --upgrade`

> **Example**
> `python -m pip install git+https://github.com/jkpr/pmix@develop --upgrade`

#### Restart server
> Common Workflows > [Restart server](#restarting-the-server)

## Common Workflows
### Logging in to server
`ssh <server>` and enter password when prompted.

> **Examples**
> Production<EMAIL_ADDRESS>> Staging<EMAIL_ADDRESS>
### Starting the server
#### Activate environment
> Common Workflows > [Activate virtual environment](#activate-virtual-environment)

#### Run server process
`cd /opt/ppp-web/ppp_web`
`/opt/ppp-web/ppp_web $` `gunicorn -b <IP_ADDRESS>:8080 run:app_instance &`

### Restarting the server
#### Find process ID
The server that PPP-Web uses is called "gunicorn", so...
`ps -e | grep gunicorn`

#### Kill process
`kill -9 <ID>`, where "<ID>" is the one found in previous step.
#### Start new process
> Common Workflows > [Starting the server](#starting-the-server)

### Activate virtual environment
`cd /opt/ppp-web`
`/opt/ppp-web $` `source .venv/bin/activate`


text:
# Abstract #

Enhancements to deep content-based music recommendation

Several advancements have been made in this area, including a
method which predicts latent factors from raw audio signals using
convolutional neural networks. Its input consist of embeddings of
the audio signals, generated by commonly used audio
representation methods.
In the field of neural networks and raw audio signals, a recent post
by DeepMind presented a deep generative model of raw audio
waveforms. This model includes neural network layers which can
be used to compute audio signal embeddings.
We present a combination of the two methods mentioned above –
a neural network which predicts latent factors from raw audio
signals, based on pre-trained layers which compute audio signal
embeddings.

This work presents a novel approach for audio
content based music recommendation using song embedding
instead of audio data processing representations, with the notion
of the embedding using the entirety of the audio file, while
preprocessing techniques lose data when capturing only specific
signals such as frequency over time.

Testing shows that this algorithm performs roughly
the same on MAP and AUC as the latest state of the art (referred to as the original
algorithm), but with 1/38 the size of audio data representation.
This fact has significant implications for storage and memory
requirements, as well as reduced training times

## Authors ##

Daniel Marcous
<EMAIL_ADDRESS>
Yotam Sandbank
<EMAIL_ADDRESS>


text:
Automated organization checkup
----------

If you don't know what's up with an org, there are a few easy starting
points

First of all, run the automated org association checker:

    fixie:0 > Fixie::CheckOrgAssociations.check_associations("acme")
    Org acme is ok (6 users)

If it reports a problem with a user, you may be able to fix it
automatically:

    fixie:0 > Fixie::CheckOrgAssociations.fix_association("acme", "mary")

This might need to be run multiple times to fix all of the errors.

Removing a user completely from an org
-----------

    [1] fixie(main)> ChefFixie::CheckOrgAssociations.remove_association('the_org', 'the_user')

This removes the user from the org, and removes them from all org
groups. However, if the user has been individually added to an ACL we
don't fix that up; it would require enumeration of the whole org, and
that hasn't been implemented.

repository: chef/fixie

gha_language: Ruby

repo_name: chef/fixie


text:
# Script: info-publicip

This script shows the public IP of the current connection.

![info-publicip](screenshots/1.png)

## Dependencies

* `curl`

## Module

```ini
[module/info-publicip]
type = custom/script
exec = ~/polybar-scripts/info-publicip.sh
interval = 60
```

repository: onokatio/polybar-scripts

gha_license_id: Unlicense

repo_name: onokatio/polybar-scripts


text:
# Plate node id plugin

This package implements the node id plugin for Plate. It allows adding a
unique id to all nodes, which is useful for features like drag & drop.

## Documentation

Check out [Playground](https://platejs.org/docs/playground).

## License

[MIT](../../LICENSE)

repository: udecode/plate

gha_language: TypeScript

gha_license_id: NOASSERTION

repo_name: udecode/plate


text:
---
jupyter:
  jupytext:
    notebook_metadata_filter: all
    text_representation:
      extension: .md
      format_name: markdown
      format_version: '1.1'
      jupytext_version: 1.1.1
  kernelspec:
    display_name: Python 2
    language: python
    name: python2
  plotly:
    description: How to make an interactive filled-chord diagram in Python with Plotly
      and iGraph.
    display_as: scientific
    language: python
    layout: base
    name: Filled Chord Diagram
    order: 25
    page_type: u-guide
    permalink: python/filled-chord-diagram/
    thumbnail: thumbnail/filled-chord.jpg
---

# Filled-Chord Diagrams with Plotly

Circular layout or [Chord diagram](https://en.wikipedia.org/wiki/Chord_diagram) is a method of visualizing  data that describe relationships. It was intensively promoted  through [Circos](http://circos.ca/), a software package in Perl that  was initially designed for displaying genomic data.

M Bostock developed reusable charts  for [chord diagrams](http://bl.ocks.org/mbostock/4062006) in d3.js. Two years ago on [stackoverflow](http://stackoverflow.com/questions/19105801/chord-diagram-in-python), the existence of a Python package for plotting chord diagrams was addressed, but the question was closed due to being *off topic*.
 Here we show that a chord diagram can be generated in Python with Plotly. We illustrate the method of generating a chord diagram from data recorded in a square matrix. The rows and columns represent the same entities.

This example considers a community of 5 friends on Facebook. We record the number of comments posted by each member on the other friends' walls. The data table is given in the next cell:

```python
import plotly.plotly as py
import plotly.figure_factory as ff
import plotly.graph_objs as go

data = [['', 'Emma', 'Isabella', 'Ava', 'Olivia', 'Sophia', 'row-sum'],
        ['Emma', 16, 3, 28, 0, 18, 65],
        ['Isabella', 18, 0, 12, 5, 29, 64],
        ['Ava', 9, 11, 17, 27, 0, 64],
        ['Olivia', 19, 0, 31, 11, 12, 73],
        ['Sophia', 23, 17, 10, 0, 34, 84]]

table = ff.create_table(data, index=True)
py.iplot(table, filename='Data-Table')
```

The aim of our visualization is to illustrate the total number of posts by each community member, and the
flows of posts between pairs of friends.

```python
import numpy as np

matrix=np.array([[16,  3, 28,  0, 18],
                 [18,  0, 12,  5, 29],
                 [ 9, 11, 17, 27,  0],
                 [19,  0, 31, 11, 12],
                 [23, 17, 10,  0, 34]], dtype=int)

def check_data(data_matrix):
    L, M=data_matrix.shape
    if L!=M:
        raise ValueError('Data array must have (n,n) shape')
    return L

L=check_data(matrix)
```

A chord diagram encodes information in two graphical objects:
  - ideograms, represented by   distinctly colored arcs of circles;
  - ribbons, that are planar shapes bounded by two quadratic Bezier curves and two arcs of circle,that can degenerate to a point;

### Ideograms ###

Summing up the entries on each matrix row, one gets a value (in our example this value is equal to the number of posts by a community member).
Let us denote by `total_comments` the total number of posts recorded in this community.

Theoretically the interval `[0, total_comments)` is mapped linearly onto the unit circle, identified with the interval $[0,2\pi)$.

For a better looking plot one proceeds as follows: starting from the angular position $0$, in counter-clockwise direction, one draws successively, around the unit circle,  two parallel arcs of length equal to a mapped row sum value, minus a fixed gap. Click the image below:

Now we define the functions that process  data in order to get ideogram ends.

As we stressed the unit circle is oriented counter-clockwise.
In order to get  an arc of circle of  end angular
coordinates $\theta_0<\theta_1$, we define a function `moduloAB` that resolves the case when an arc contains
the  point of angular coordinate $0$ (for example $\theta_0=2\pi-\pi/12$, $\theta_1=\pi/9$). The function corresponding to $a=-\pi, b=\pi$  allows to map the interval $[0,2\pi)$ onto $[-\pi, \pi)$. Via this transformation we have:

$\theta_0\mapsto \theta'_0=-\pi/12$, and

$ \theta_1=\mapsto \theta'_1=\pi/9$,

and now $\theta'_0<\theta'_1$.

```python
PI=np.pi

def moduloAB(x, a, b): #maps a real number onto the unit circle identified with
                       #the interval [a,b), b-a=2*PI
        if a>=b:
            raise ValueError('Incorrect interval ends')
        y=(x-a)%(b-a)
        return y+b if y<0 else y+a

def test_2PI(x):
    return 0<= x <2*PI
```

Compute the row sums and the lengths of corresponding ideograms:

```python
row_sum=[np.sum(matrix[k,:]) for k in range(L)]

#set the gap between two consecutive ideograms
gap=2*PI*0.005
ideogram_length=2*PI*np.asarray(row_sum)/sum(row_sum)-gap*np.ones(L)
```

The next function returns the list of  end angular coordinates for each ideogram arc:

```python
def get_ideogram_ends(ideogram_len, gap):
    ideo_ends=[]
    left=0
    for k in range(len(ideogram_len)):
        right=left+ideogram_len[k]
        ideo_ends.append([left, right])
        left=right+gap
    return ideo_ends

ideo_ends=get_ideogram_ends(ideogram_length, gap)
ideo_ends
```

The function `make_ideogram_arc` returns equally spaced points on an ideogram arc, expressed as complex
numbers in polar form:

```python
def make_ideogram_arc(R, phi, a=50):
    # R is the circle radius
    # phi is the list of ends angle coordinates of an arc
    # a is a parameter that controls the number of points to be evaluated on an arc
    if not test_2PI(phi[0]) or not test_2PI(phi[1]):
        phi=[moduloAB(t, 0, 2*PI) for t in phi]
    length=(phi[1]-phi[0])% 2*PI
    nr=5 if length<=PI/4 else int(a*length/PI)

    if phi[0] < phi[1]:
        theta=np.linspace(phi[0], phi[1], nr)
    else:
        phi=[moduloAB(t, -PI, PI) for t in phi]
        theta=np.linspace(phi[0], phi[1], nr)
    return R*np.exp(1j*theta)
```

The real and imaginary parts of these complex numbers will be used to define the ideogram as a [Plotly
shape](https://plot.ly/python/shapes/) bounded by a SVG path.

```python
z=make_ideogram_arc(1.3, [11*PI/6, PI/17])
print z
```

Set ideograms labels and colors:

```python
labels=['Emma', 'Isabella', 'Ava', 'Olivia', 'Sophia']
ideo_colors=['rgba(244, 109, 67, 0.75)',
             'rgba(253, 174, 97, 0.75)',
             'rgba(254, 224, 139, 0.75)',
             'rgba(217, 239, 139, 0.75)',
             'rgba(166, 217, 106, 0.75)']#brewer colors with alpha set on 0.75
```

### Ribbons in a chord diagram ###

While ideograms illustrate how many comments posted each member of the Facebook community,  ribbons
give a comparative information on the flows of comments from one friend to another.

To illustrate this flow we map data onto the unit circle. More precisely, for each matrix row, $k$, the application:

`t`$\mapsto$ `t*ideogram_length[k]/row_sum[k]`

maps the interval `[0, row_sum[k]]` onto
the interval `[0, ideogram_length[k]]`. Hence each entry `matrix[k][j]` of the $k^{th}$  row is mapped to `matrix[k][j]*ideogram_length[k]/row_value[k]`.

The function `map_data` maps all matrix entries to the corresponding values in the intervals associated to ideograms:

```python
def map_data(data_matrix, row_value, ideogram_length):
    mapped=np.zeros(data_matrix.shape)
    for j  in range(L):
        mapped[:, j]=ideogram_length*data_matrix[:,j]/row_value
    return mapped

mapped_data=map_data(matrix, row_sum, ideogram_length)
mapped_data
```

- To each pair of values `(mapped_data[k][j], mapped_data[j][k])`, $k<=j$,  one associates a ribbon, that is a curvilinear filled rectangle (that can be degenerate), having as opposite sides two subarcs of the $k^{th}$ ideogram, respectively $j^{th}$ ideogram, and two arcs of quadratic Bézier curves.

Here we illustrate the ribbons associated to pairs `(mapped_data[0][j], mapped_data[j][0])`, $j=\overline{0,4}$,
that illustrate the flow of comments between Emma and all other friends, and  herself:

- For a better looking chord diagram,
[Circos documentation](http://circos.ca/presentations/articles/vis_tables1/) recommends to sort increasingly each row of the mapped_data.

The  array `idx_sort`, defined below, has on each row the indices that sort the corresponding row in `mapped_data`:

```python
idx_sort=np.argsort(mapped_data, axis=1)
idx_sort
```

In the following we call ribbon ends, the lists `l=[l[0], l[1]]`, `r=[r[0], r[1]]` having as elements the angular coordinates
of the ends of arcs that are opposite sides in a ribbon. These arcs are sub-arcs in the internal boundaries of
the ideograms, connected by the ribbon
(see the image above).

- Compute the ribbon ends  and store them as tuples
in a list of lists ($L\times L$):

```python
def make_ribbon_ends(mapped_data, ideo_ends,  idx_sort):
    L=mapped_data.shape[0]
    ribbon_boundary=np.zeros((L,L+1))
    for k in range(L):
        start=ideo_ends[k][0]
        ribbon_boundary[k][0]=start
        for j in range(1,L+1):
            J=idx_sort[k][j-1]
            ribbon_boundary[k][j]=start+mapped_data[k][J]
            start=ribbon_boundary[k][j]
    return [[(ribbon_boundary[k][j],ribbon_boundary[k][j+1] ) for j in range(L)] for k in range(L)]

ribbon_ends=make_ribbon_ends(mapped_data, ideo_ends,  idx_sort)
print 'ribbon ends starting from the ideogram[2]\n', ribbon_ends[2]
```

We note that `ribbon_ends[k][j]` correspond to `mapped_data[i][idx_sort[k][j]]`, i.e. the length of the arc of ends
in `ribbon_ends[k][j]` is equal to `mapped_data[i][idx_sort[k][j]]`.

Now we define a few functions that compute the  control points for Bézier ribbon sides.

The function `control_pts` returns the cartesian coordinates of  the  control points, $b_0, b_1, b_2$, supposed as being  initially located on the unit circle, and thus defined only by their angular coordinate.  The angular coordinate
of the point $b_1$ is the mean of angular coordinates of the points $b_0, b_2$.

Since for a  Bézier ribbon side only $b_0, b_2$ are placed on the unit circle, one gives `radius` as a parameter that controls position of $b_1$.  `radius` is the distance  of $b_1$ to the circle center.

```python
def control_pts(angle, radius):
    #angle is a  3-list containing angular coordinates of the control points b0, b1, b2
    #radius is the distance from b1 to the  origin O(0,0)

    if len(angle)!=3:
        raise InvalidInputError('angle must have len =3')
    b_cplx=np.array([np.exp(1j*angle[k]) for k in range(3)])
    b_cplx[1]=radius*b_cplx[1]
    return zip(b_cplx.real, b_cplx.imag)
```

```python
def ctrl_rib_chords(l, r, radius):
    # this function returns a 2-list containing control polygons of the two quadratic Bezier
    #curves that are opposite sides in a ribbon
    #l (r) the list of angular variables of the ribbon arc ends defining
    #the ribbon starting (ending) arc
    # radius is a common parameter for both control polygons
    if len(l)!=2 or len(r)!=2:
        raise ValueError('the arc ends must be elements in a list of len 2')
    return [control_pts([l[j], (l[j]+r[j])/2, r[j]], radius) for j in range(2)]
```

Each ribbon is colored with the color of one of the two  ideograms it connects.
We define an L-list of L-lists of colors for ribbons. Denote it by `ribbon_color`.

`ribbon_color[k][j]` is the Plotly color string for the ribbon associated to `mapped_data[k][j]` and `mapped_data[j][k]`, i.e. the ribbon connecting two subarcs in the $k^{th}$, respectively, $j^{th}$ ideogram. Hence  this structure is symmetric.

Initially we define:

```python
ribbon_color=[L*[ideo_colors[k]] for k in range(L)]
```

and then eventually we change the color in a few positions.

For our example we change:

```python
ribbon_color[0][4]=ideo_colors[4]
ribbon_color[1][2]=ideo_colors[2]
ribbon_color[2][3]=ideo_colors[3]
ribbon_color[2][4]=ideo_colors[4]
```

The symmetric locations are not modified, because  we do not access
`ribbon_color[k][j]`, $k>j$, when drawing the ribbons.

Functions that return the Plotly SVG paths that are  ribbon boundaries:

```python
def make_q_bezier(b):# defines the Plotly SVG path for a quadratic Bezier curve defined by the
                     #list of its control points
    if len(b)!=3:
        raise valueError('control poligon must have 3 points')
    A, B, C=b
    return 'M '+str(A[0])+',' +str(A[1])+' '+'Q '+\
                str(B[0])+', '+str(B[1])+ ' '+\
                str(C[0])+', '+str(C[1])

b=[(1,4), (-0.5, 2.35), (3.745, 1.47)]

make_q_bezier(b)
```

`make_ribbon_arc`  returns the Plotly SVG path corresponding to an arc represented by its end angular coordinates `theta0, theta1`.

```python
def make_ribbon_arc(theta0, theta1):

    if test_2PI(theta0) and test_2PI(theta1):
        if theta0 < theta1:
            theta0= moduloAB(theta0, -PI, PI)
            theta1= moduloAB(theta1, -PI, PI)
            if theta0*theta1>0:
                raise ValueError('incorrect angle coordinates for ribbon')

        nr=int(40*(theta0-theta1)/PI)
        if nr<=2: nr=3
        theta=np.linspace(theta0, theta1, nr)
        pts=np.exp(1j*theta)# points on arc in polar complex form

        string_arc=''
        for k in range(len(theta)):
            string_arc+='L '+str(pts.real[k])+', '+str(pts.imag[k])+' '
        return   string_arc
    else:
        raise ValueError('the angle coordinates for an arc side of a ribbon must be in [0, 2*pi]')

make_ribbon_arc(np.pi/3, np.pi/6)
```

Finally we are ready to define data and layout for the Plotly plot of the chord diagram.

```python
def make_layout(title, plot_size):
    axis=dict(showline=False, # hide axis line, grid, ticklabels and  title
          zeroline=False,
          showgrid=False,
          showticklabels=False,
          title=''
          )

    return go.Layout(title=title,
                  xaxis=dict(axis),
                  yaxis=dict(axis),
                  showlegend=False,
                  width=plot_size,
                  height=plot_size,
                  margin=dict(t=25, b=25, l=25, r=25),
                  hovermode='closest',
                  shapes=[]# to this list one appends below the dicts defining the ribbon,
                           #respectively the ideogram shapes
                 )
```

Function that returns the Plotly shape of an ideogram:

```python
def make_ideo_shape(path, line_color, fill_color):
    #line_color is the color of the shape boundary
    #fill_collor is the color assigned to an ideogram
    return  dict(
                  line=dict(
                  color=line_color,
                  width=0.45
                 ),

            path=  path,
            type='path',
            fillcolor=fill_color,
            layer='below'
        )

```

We generate two types of ribbons: a ribbon connecting subarcs in two distinct ideograms, respectively
a ribbon from one ideogram to itself (it corresponds to `mapped_data[k][k]`, i.e. it gives the flow of comments
from a community member to herself).

```python
def make_ribbon(l, r, line_color, fill_color, radius=0.2):
    #l=[l[0], l[1]], r=[r[0], r[1]]  represent the opposite arcs in the ribbon
    #line_color is the color of the shape boundary
    #fill_color is the fill color for the ribbon shape
    poligon=ctrl_rib_chords(l,r, radius)
    b,c =poligon

    return  dict(
                line=dict(
                color=line_color, width=0.5
            ),
            path=  make_q_bezier(b)+make_ribbon_arc(r[0], r[1])+
                   make_q_bezier(c[::-1])+make_ribbon_arc(l[1], l[0]),
            type='path',
            fillcolor=fill_color,
            layer='below'
        )

def make_self_rel(l, line_color, fill_color, radius):
    #radius is the radius of Bezier control point b_1
    b=control_pts([l[0], (l[0]+l[1])/2, l[1]], radius)
    return  dict(
                line=dict(
                color=line_color, width=0.5
            ),
            path=  make_q_bezier(b)+make_ribbon_arc(l[1], l[0]),
            type='path',
            fillcolor=fill_color,
            layer='below'
        )

def invPerm(perm):
    # function that returns the inverse of a permutation, perm
    inv = [0] * len(perm)
    for i, s in enumerate(perm):
        inv[s] = i
    return inv

layout=make_layout('Chord diagram', 400)

```

Now let us explain the key point of associating  ribbons  to right data:

From the definition of `ribbon_ends` we notice that `ribbon_ends[k][j]` corresponds to data stored in
`matrix[k][sigma[j]]`, where `sigma` is the permutation of indices $0, 1, \ldots L-1$, that sort the row k in `mapped_data`.
If `sigma_inv` is the inverse permutation of `sigma`, we get that to `matrix[k][j]` corresponds the
`ribbon_ends[k][sigma_inv[j]]`.

`ribbon_info` is a list of dicts setting the information that is displayed when hovering the mouse over the  ribbon ends.

Set the radius of Bézier control point, $b_1$, for each ribbon associated to a diagonal data entry:

```python
radii_sribb=[0.4, 0.30, 0.35, 0.39, 0.12]# these value are set after a few trials
```

```python
ribbon_info=[]
for k in range(L):

    sigma=idx_sort[k]
    sigma_inv=invPerm(sigma)
    for j in range(k, L):
        if matrix[k][j]==0 and matrix[j][k]==0: continue
        eta=idx_sort[j]
        eta_inv=invPerm(eta)
        l=ribbon_ends[k][sigma_inv[j]]

        if j==k:
            layout['shapes'].append(make_self_rel(l, 'rgb(175,175,175)' ,
                                    ideo_colors[k], radius=radii_sribb[k]))
            z=0.9*np.exp(1j*(l[0]+l[1])/2)
            #the text below will be displayed when hovering the mouse over the ribbon
            text=labels[k]+' commented on '+ '{:d}'.format(matrix[k][k])+' of '+ 'herself Fb posts',
            ribbon_info.append(go.Scatter(x=[z.real],
                                       y=[z.imag],
                                       mode='markers',
                                       marker=dict(size=0.5, color=ideo_colors[k]),
                                       text=text,
                                       hoverinfo='text'
                                       )
                              )
        else:
            r=ribbon_ends[j][eta_inv[k]]
            zi=0.9*np.exp(1j*(l[0]+l[1])/2)
            zf=0.9*np.exp(1j*(r[0]+r[1])/2)
            #texti and textf are the strings that will be displayed when hovering the mouse
            #over the two ribbon ends
            texti=labels[k]+' commented on '+ '{:d}'.format(matrix[k][j])+' of '+\
                  labels[j]+ ' Fb posts',

            textf=labels[j]+' commented on '+ '{:d}'.format(matrix[j][k])+' of '+\
            labels[k]+ ' Fb posts',
            ribbon_info.append(go.Scatter(x=[zi.real],
                                       y=[zi.imag],
                                       mode='markers',
                                       marker=dict(size=0.5, color=ribbon_color[k][j]),
                                       text=texti,
                                       hoverinfo='text'
                                       )
                              ),
            ribbon_info.append(go.Scatter(x=[zf.real],
                                       y=[zf.imag],
                                       mode='markers',
                                       marker=dict(size=0.5, color=ribbon_color[k][j]),
                                       text=textf,
                                       hoverinfo='text'
                                       )
                              )
            r=(r[1], r[0])#IMPORTANT!!!  Reverse these arc ends because otherwise you get
                          # a twisted ribbon
            #append the ribbon shape
            layout['shapes'].append(make_ribbon(l, r, 'rgb(175,175,175)' , ribbon_color[k][j]))

```

`ideograms` is a list of dicts that set the position, and color of ideograms, as well as the information associated to each ideogram.

```python
ideograms=[]
for k in range(len(ideo_ends)):
    z= make_ideogram_arc(1.1, ideo_ends[k])
    zi=make_ideogram_arc(1.0, ideo_ends[k])
    m=len(z)
    n=len(zi)
    ideograms.append(go.Scatter(x=z.real,
                             y=z.imag,
                             mode='lines',
                             line=dict(color=ideo_colors[k], shape='spline', width=0.25),
                             text=labels[k]+'<br>'+'{:d}'.format(row_sum[k]),
                             hoverinfo='text'
                             )
                     )

    path='M '
    for s in range(m):
        path+=str(z.real[s])+', '+str(z.imag[s])+' L '

    Zi=np.array(zi.tolist()[::-1])

    for s in range(m):
        path+=str(Zi.real[s])+', '+str(Zi.imag[s])+' L '
    path+=str(z.real[0])+' ,'+str(z.imag[0])

    layout['shapes'].append(make_ideo_shape(path,'rgb(150,150,150)' , ideo_colors[k]))

data = go.Data(ideograms+ribbon_info)
fig = go.Figure(data=data, layout=layout)

import plotly.offline as off
off.init_notebook_mode()

off.iplot(fig, filename='chord-diagram-Fb')
```

```python
from plotly.offline import init_notebook_mode
init_notebook_mode(connected=True)

data = go.Data(ribbon_info+ideograms)
fig = go.Figure(data=data, layout=layout)

py.iplot(fig, filename='chord-diagram-Fb')
```

Here is a chord diagram associated to a community of 8 Facebook friends:

```python
from IPython.display import display, HTML

display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))

! pip install publisher --upgrade
import publisher
publisher.publish(
    'filled-chord.ipynb', 'python/filled-chord-diagram/', 'Python Filled Chord Diagram',
    'How to make an interactive filled-chord diagram in Python with Plotly and iGraph. ',
    name = 'Filled Chord Diagram',
    title = "Filled Chord Diagram | Plotly",
    thumbnail='thumbnail/filled-chord.jpg', language='python',
    has_thumbnail='true', display_as='scientific', order=25,
    ipynb= '~notebook_demo/191')
```

```python

```


text:
## Description

A pattern that creates a drop area for uploading multiple files in a prototype or production website, without the need for programming JavaScript.

Based on fineuploader.  -http://fineuploader.com/

## Documentation

Property | Value | Default | Type | Description
---------|-------|---------|------|------------
ajaxUpload | `true`, `false` | `true` | boolean | For letting the widget upload the files via ajax. If false the form will act like a normal form.
autoCleanResults | `true`, `false` | `true` | boolean | Condition value for the file preview in div element to fadeout after file upload is completed.
baseUrl | _url string_ | _null_ | string | To be used in conjunction with relativePath to generate submission urls based on related items.
className | _class name_ | `upload` | string | Value for class attribute in the form element.
clickable | `true`, `false` | `false` | boolean | If you can click on container to also upload.
container | | `''` | selector | JavaScript selector for where to put upload stuff into in case of form. If not provided it will be place before the first submit button.
currentPath | _path string_ | _null_ | string | Current path related items is starting with.
initialFolder | _UID string_ | _null_ | string | UID of initial folder related items widget should have selected.
paramName | _name attr_ | `file` | string | Value for name attribute in the file input element.
previewsContainer | | `.previews` | selector | JavaScript selector for file preview in div element.
relatedItems | _JS object_ | `{ attributes: ["UID", "Title", "Description", "getURL", "Type", "path", "ModificationDate"], batchSize: 20, basePath: "/", vocabularyUrl: null, width: 500, maximumSelectionSize: 1, placeholder: "Search for item on site..." }` | object | Related items pattern options. Will only use only if relativePath is used to use correct upload destination.
relativePath | _path string_ | _null_ | string | Again, to be used with baseUrl to create upload url.
resultTemplate | _html string_ | `<div class="dz-notice"><p>Drop files here...</p></div><div class="upload-previews"/>` | string | HTML template for the element that will contain file information.
showTitle | `true`, `false` | `true` | boolean | Show/hide the h1 title.
url | _url string_ | _null_ | string | If not used with a form, this option must provide the URL to submit to or baseUrl with relativePath needs to be used.
wrap | `true`, `false` | `false` | boolean | True or false for wrapping this element using the value of wrapperTemplate.
wrapperTemplate | _html string_ | `<div class="upload-container"/>`| string | HTML template for wrapping around with this element.

repository: fulv/pat-upload

repo_name: fulv/pat-upload


text:
The 10th uniform polyhedron is the Octahedron; it has Wythoff symbol 4|2
3. Its dual is the cube. The pattern of polygons round each vertex is
(3,3,3,3); its symmetry group is the octahedral group S4.

It has:

Euler characteristic: 2

Density: 1

Number of vertices: 6

Number of edges: 12

Number of faces: 8 (=8 triangles).

Its circumradius is $ \sqrt{2} / 2 $ and its volume is $ \sqrt{2} / 3  $
if the edge length is 1.


text:
# Inheritance
Inheritance allows a *child [class](https://github.com/PlasmaEngine/PlasmaDocs/blob/master/plasma_editor_documentation/plasmamanual/lightning_in_plasma/classes.markdown) to automatically receive all of the data and functionality defined within the base* class.

```name=Feline, lang=csharp
class Feline
{
  constructor() { }
}
```

```name=Lion, lang=csharp
// A colon designates an identifier for a base class follows.
class Lion : Feline
{
  // a constructor is not necessary when one is inherited from the base class.
}
```
```name=Using Feline & Lion, lang=csharp
var cat = new Feline();
var simba = new Lion(); // Instantiated from the inherited constructor
```

In the above example the variable `simba` can be instantiated as a `Lion` using the constructor from `Feline`.

 # The **base** Keyword
The **base** [keyword](https://github.com/PlasmaEngine/PlasmaDocs/blob/master/plasma_editor_documentation/plasmamanual/lightning_in_plasma/keywords.markdown) is for use when defining an inherited class; it allows you to call the constructor of the base class being inherited from before running an explicitly defined constructor.

```name=Animal, lang=csharp
class Animal
{
  var Legs : Integer = 4;

  constructor() { }
  constructor(legs : Integer)
  {
      this.Legs = legs;
  }

  function ToString() : String
  {
    var builder = new StringBuilder();
    builder.Write("Legs: ");
    builder.Write(this.Legs);
    return builder.ToString();
  }
}
```
The class animal defines a **non-default** constructor which takes a number of legs for the animal as a parameter.

```name=Human, lang=csharp
class Human : Animal
{
  constructor() : base(2) { }
}
```
The class `Human` which inherits from `Animal` can use `Animal`'s constructor by using the `base` keyword. In this situation either the default or non-default constructor from `Animal` could be called using based. Which constructor is called is determined by the parameters passed to the `()` after the`base` keyword. Because `2` is passed to the `base` keyword the **non-default** constructor of `Animal` is called before any implementation within the defined **default** constructor of `Human`.

```name=Using Animal & Human, lang=csharp
var animal : Animal = new Animal();
Console.WriteLine(animal.ToString()); // Legs: 4

var jerry = new Human();
Console.WriteLine(jerry.ToString());  // Legs: 2
```
In this runtime example both `Animal` and `Human` are instantiated using their default constructor.

```name=Console Output, lang=csharp
---------------- Begin Game ---------------
Legs: 4
Legs: 2
```
As can be seen in the console output the `Human` **default** constructor calls the **non-default** constructor of `Animal` and passes it `2`.

 # Classes & Structs
Although Lightning currently does not throw an error, erratic and unexpected behavior will result from having a class inherit from a struct and vice versa. **i.e.**

```name=Incompatible Inheritance, lang=csharp
// Mismatching the struct/class between parent and child
struct MyBaseStruct
{
  constructor()
  {
  }
}
class MyClass : MyBaseStruct
{
  constructor() : base()
  {
  }
}
```
```name=Console WriteLine
// Leads to issues such as the inability to cast to the base class type.
var incompatible: MyClass = new MyClass();
Console.WriteLine(typeid(incompatible).Name);                 // MyClass
Console.WriteLine(typeid(incompatible as MyBaseStruct).Name); // This won't compile.
```

 # The Virtual Keyword

Virtual is used to give Base classes the ability to determine some functions as being able to be *overridden* by its derived classes. The new `Speak` function defined in `Animal` will serve as an example:

```name=Applying Virtual to a Function,lang=csharp
class Animal
{
  var Legs:Integer = 4;

  constructor() { }

  constructor(legs : Integer)
  {
    this.Legs = legs;
  }

  function ToString() : String
  {
    var builder = new StringBuilder();
    builder.Write("Legs: ");
    builder.Write(this.Legs);
    return builder.ToString();
  }

  [Virtual]
  function Speak() : String
  {
    return "...";
  }
}
```

By default, animals don't say anything, so a string that says `...` is returned. It is known that there are animals that do speak, so the `[Virtual]` attribute is added to the function to let other developers know that if a class is is **derived** from `Animal`, the functionality of `Speak` may be overridden.

```name=Animal, lang=csharp
class Human : Animal
{
  constructor() : base(2) { }

  [Override]
  function Speak() : String
  {
    return "Hello";
  }
}
```
Humans do speak, so changeing the funcitonality of `Human.Speak` to say something other than `...` makes perfect sense. The `[Override]` attribute applied to `Speak` marks this implementation of the `Speak` function to replace `Animal.Speak` which is marked as `[Virtual]`.

This can also be extended to other classes like a Cat:

```name=Cat, lang=csharp
class Cat : Animal
{
  // Cats have 4 legs, so let's update the constructor
  constructor() : base(4) { }

  [Override]
  function Speak() : String
  {
    return "Meow";
  }
}
```

Now, this is great in the fact that we can now do something like the following:

```name=Using Overridden Functions, lang=csharp
var animal = Animal();
Console.WriteLine(animal.Speak());

var human = Human();
Console.WriteLine(human.Speak());

var cat = Cat();
Console.WriteLine(cat.Speak());
```

```name=Console Output
...
Hello
Meow
```

The real magic of inheritance comes in the idea that a class of a **derived** class can be stored in a variable that matches the type of the **base** class.

```lang=csharp
var humanIsAnAnimal : Animal = Human();
Console.WriteLine(humanIsAnAnimal.Speak());
```

Even though the variable is of type Animal, the Human version of the function is called:

```name=Console Output
Hello
```

This is because whenever a virtual method is called, the run-time type of the object is checked for an **overriding member**. The overriding member in the most derived class will then be called, which might be the original function if the derived class(es) have not overridden it.

This can be quite useful with an array of Animals.

```name=Array of Animals, lang=csharp
var a : Animal = Animal();
var b : Human = Human();
var c : Animal = Human();
var d : Cat = Cat();

var array : Array[Animal] = Array[Animal](){a,b,c,d};

foreach (var animal in array)
{
  Console.WriteLine(animal.Speak());
}
```

```name=Console Output, lang=csharp
...
Hello
Hello
Meow
```

 # Calling Parent Functions

It's also possible to call the parent version of a function from a child class. In order to do this, the object must be cast to the base type and then use the non-virtual operator (~>) to call the base version:

```name=Calling **base** Function from Derived, lang=csharp
var d : Cat = Cat();
(d as Animal)~>Speak();
```
```name=Console Output, lang=csharp
...
```

 # Related Materials
 ## Manual
- [attributes](https://github.com/PlasmaEngine/PlasmaDocs/blob/master/plasma_editor_documentation/plasmamanual/lightning_in_plasma/attributes.markdown)

repository: JeremiasBulanadi/PlasmaDocs

repo_name: JeremiasBulanadi/PlasmaDocs


text:
# Tic Tac Toe WPF Application

This is a windows app for tic tac toe game

![Tic Tac Toe game](https://github.com/rifayetazamtalukder/TicTacToeWPFApplication/blob/master/tic%20tac%20toe%20game.PNG)


text:
---
layout: post
title: From the deck to the bin
---

DEC2BIN
27.9.2018

    Starting point:
    We started with our blogs that we made last week (see 'Cypher Solver' - lesson 3)

    Target for this lesson?
    The target for this lesson was to sereate a converter from text to Ascii*.

    Did I reach my target?
    I achieved my target.

    How did you use your learning habits this week?

    Persevering:
    I had to persevere through not knowing what to do to thinking about an easy way of doing it.

    Questioning:
    When the code went wrong I had to question each character to find out what was wrong with it.

    Independence:
    I worked out how to do this by myself without any help.

    Reflecting:
    We were told that we could get the whole thing done with code online so I had to look though the internet to find it.

    Engagement:
    I had to be engaged at the beginning while we were being briefed so that I knew what I had to do.


text:
# Mount network drive guide
#### Mounting Network or SMB network drive to local directory.
#### This tutorial is made from [SpaceRex](https://youtu.be/RIS482WvbM4)'s youtube tutorial, If you like a video walkthrough, go check out his video.

### 1) Install cifs-utils

```
sudo apt-get install cifs-utils
```

### 2) Make directory for mountpoint
- The location is generally preferred in your home directory.
- Change the folder name ```mountpoint``` to your liking.

```
mkdir ~/mountpoint
```

- To check your folder, use ```ls``` to see if the folder has been made.

### 3) Find user id
- The user id is used to specify the accessibility of the folder

```
id
```

- Locate the ```uid=1000(user_name)``` it usually the frist one, and the id usually is '1000'.
- If you have multiple users on the system, then check by the ```(user_name)```.

### 4) Manually mount the drive
- Change ```remotename``` to your smb username.
- Change ```remotepassword``` to your smb password.
- Change ```<IP_ADDRESS>/remotedirectory``` to your smb server's ip and directory that you wish to mount.
- Change ```mountpoint``` to your local mountpoint name.

```
sudo mount -t cifs -o username=remotename,password=remotepassword,uid=1000 //<IP_ADDRESS>/remotedirectory ~/mountpoint
```

- [[mount]](https://www.computerhope.com/unix/umount.htm) **-t** Mount type e.g. ```cifs```
- [[cifs]](https://linux.die.net/man/8/mount.cifs) **-o** optional parameters e.g. ```username``` (smb file system), ```password```
- If your remote directory has space between the naming, add single quote ```''``` to the command e.g. ```... //<IP_ADDRESS>/'remote directory' ...```
- If your smb password has special characters e.g. ```#$^&*!',.``` then the connection will fail, one of the solution is use ```credentials``` file. (will be mentioned later on)

#### 4.1) Mount check
- After you hit enter, check if the mount was successful.
- You can use the GUI file manager, or use command like ``` ls ``` to check.
- If you see your remote files/folders mean the connection is established successfully.

```
ls ~/mountpoint
```
- That is for the basic, if you only wanted to mount it this time, then you are done!
- If you want to mount if every time during startup, then continue reading.
---

### 5) Secure your info with credentials
- By default, everyone can read the fstab file, thus if you using plain text username and password like above, your smb server might get an unwanted visit.
- By using credentials file, you get to use a more complex password with special characters e.g. ```#$^&*()!',.``` to ferder secure your account.
- The process of creating the credentials file must be under root for security.
- Change the name ```.key``` to your liking, but you must add period ```.``` at the beginning of the filename to hide it. e.g ```.tomysmb```, ```.toserver```, ```.totallynotusernameandpassword```...

#### 5.1) creating credentials file
- [[nano]](https://www.nano-editor.org/) Nano is my preferred of text editor, you can use whatever you like. e.g. *vi* , *vim*

```
sudo su
nano /root/.key
```

#### 5.2) set username and password
- After changing the username and password to yours, **save** ```Ctrl+O``` and **exit** ```Ctrl+X``` .

```
username=remotename
password=remotepassword
```
#### 5.3) Changing the credentials file permission to root only

```
chmod 700 /root/.key
```

- [[chmod]](https://www.computerhope.com/unix/uchmod.htm) Set the permissions of files or directories.

### 6) Mount the drive during startup
- After making and securing the credentials file, is time to edite the ```fstab``` file.

```
sudo nano /etc/fstab
```

- Create a new line
- Type in the following

```
//<IP_ADDRESS>/remotedirectory /home/user_name/mountpoint cifs credentials=/root/.key,uid=1000 0 0
```
- Change ```<IP_ADDRESS>/remotedirectory``` to your smb server's ip and directory that you wish to mount.
- Change ```.../user_name/mountpoint``` to your username and mountpoint name.
- Change ```.../.key``` to your credentials filename.
- If your remote directory has space between the naming, replace the space with ```\040``` e.g. ```... //<IP_ADDRESS>/remote\040directory ...```
- [[fstab]](https://help.ubuntu.com/community/Fstab)  Is a file that automate the process of mounting partition of the internal devices, CD/DVD devices, and network shares (samba/nfs/sshfs).

### 7) Testing

- To test mounting, run ```sudo mount -a```
- If mount successfully, then ```reboot``` to see if it also works on startup.

## You are done!

### Softwares
1. [[cifs-utils]](https://wiki.samba.org/index.php/LinuxCIFS_utils) Tool to mount SMB/CIFS shares on Linux.

repository: berryflake/linuxgoody

repo_name: berryflake/linuxgoody


text:
# The Fracking Weather

A copy of a glorious app and in homage to a glorious television saga. This app will tell you the fracking weather.

## Getting Started

Make sure to have Rails 5.2.1 and Ruby 2.4.1 installed.

### Running Locally

To run locally.

* attempt to get an API Key from [WeatherUnderground](https://www.wunderground.com/)
* clone down the repo
* `bundle install`
* `rails db:setup`
* `touch .env`
* enter API key into `.env` file from above step into with the key `WEATHER_API_KEY`
* `rails server`

And now you can see the fracking weather LOCALLY!

## Running the tests

* `rake db:test:prepare` just in case
* `rspec`

## Deployment

This app is live. You can find out the fracking weather [RIGHT HERE](http://the-fracking-weather.herokuapp.com/)!

## Built With

* [Rails](https://api.rubyonrails.org/) - The web framework used
* [Geocoder](https://github.com/alexreisner/geocoder) - Used to geocode searches
* [WeatherUnderground](https://www.wunderground.com/) - Used for weather feeds
* [The Fucking Weather](http://thefuckingweather.com/) - Used for inspiration
* [Battlestar Galactica](https://en.wikipedia.org/wiki/Battlestar_Galactica_(2004_TV_series)) - Used for more inspiration

## Authors

* **Ben Jacobs** - *Initial work* - [Benjaminpjacobs](https://github.com/Benjaminpjacobs)

## License

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

repository: Benjaminpjacobs/the-fracking-weather

repo_name: Benjaminpjacobs/the-fracking-weather


text:
# remark-retext [![Build Status][travis-badge]][travis] [![Coverage Status][codecov-badge]][codecov]

Bridge / mutate from [**remark**][remark] to [**retext**][retext].

## Installation

[npm][]:

```bash
npm install remark-retext
```

## Usage

Say we have the following file, `example.md`:

```markdown
## Hello guys!
```

And our script, `example.js`, looks as follows:

```javascript
var vfile = require('to-vfile');
var report = require('vfile-reporter');
var unified = require('unified');
var parse = require('remark-parse');
var stringify = require('remark-stringify');
var remark2retext = require('remark-retext');
var english = require('retext-english');
var equality = require('retext-equality');

unified()
  .use(parse)
  .use(remark2retext, unified().use(english).use(equality))
  .use(stringify)
  .process(vfile.readSync('example.md'), function (err, file) {
    console.error(report(err || file));
  });
```

Now, running `node example` yields:

```text
example.md
  1:10-1:14  warning  `guys` may be insensitive, use `people`, `persons`, `folks` instead  gals-men  retext-equality

⚠ 1 warning
```

## API

### `origin.use(remark2retext, destination[, options])`

Either bridge or mutate from [**remark**][remark] ([MDAST][]) to
[**retext**][retext] ([NLCST][]).

###### `destination`

`destination` is either a parser or a processor.

If a [`Unified`][processor] processor is given, runs the destination
processor with the new NLCST tree, then, after running discards that
tree and continues on running the origin processor with the original
tree ([bridge-mode][bridge]).

If a parser (such as [**parse-latin**][latin], [**parse-english**][english],
or [**parse-dutch**][dutch]) is given, passes the tree to further
plug-ins (mutate-mode).

###### `options`

Passed to [`mdast-util-to-nlcst`][to-nlcst].

## Related

*   [`rehype-retext`](https://github.com/wooorm/rehype-retext)
    — Transform HTML to [NLCST][]
*   [`remark-rehype`](https://github.com/wooorm/remark-rehype)
    — Transform markdown to HTML
*   [`rehype-remark`](https://github.com/wooorm/rehype-remark)
    — Transform HTML to markdown
*   [`mdast-util-to-nlcst`][to-nlcst]
    — Underlying algorithm

## License

[MIT][license] © [Titus Wormer][author]

<!-- Definitions -->

[travis-badge]: https://img.shields.io/travis/wooorm/remark-retext.svg

[travis]: https://travis-ci.org/wooorm/remark-retext

[codecov-badge]: https://img.shields.io/codecov/c/github/wooorm/remark-retext.svg

[codecov]: https://codecov.io/github/wooorm/remark-retext

[npm]: https://docs.npmjs.com/cli/install

[license]: LICENSE

[author]: http://wooorm.com

[mdast]: https://github.com/wooorm/mdast

[remark]: https://github.com/wooorm/remark

[retext]: https://github.com/wooorm/retext

[processor]: https://github.com/wooorm/unified#processor

[bridge]: https://github.com/wooorm/unified#bridge

[nlcst]: https://github.com/wooorm/nlcst

[latin]: https://github.com/wooorm/parse-latin

[english]: https://github.com/wooorm/parse-english

[dutch]: https://github.com/wooorm/parse-dutch

[to-nlcst]: https://github.com/syntax-tree/mdast-util-to-nlcst

repository: vinayakgrynn/gatsby-scotch-blog

gha_language: CSS

repo_name: vinayakgrynn/gatsby-scotch-blog


text:
# sysadmin-resources
Sysadmin resources for developers

* [DigitalOcean Community](https://www.digitalocean.com/community/tutorials) - Awesome step-by-step tutorials that are easy to follow.
* [Servers for Hackers](https://serversforhackers.com/) - Video tutorials about a lot of sysadmin stuff.
* [nixCraft](http://www.cyberciti.biz/) - A lot of Linux tutorials and advice.

Have more awesome resources that should be added in here? Please send a PR!

repository: dhamaniasad/sysadmin-resources

repo_name: dhamaniasad/sysadmin-resources


text:
---
uid: Guides.ContextCommands.Creating
title: Creating Context Commands
---

# Creating context menu commands.

There are two kinds of Context Menu Commands: User Commands and Message Commands.
Each of these have a Global and Guild variant.
Global menu commands are available for every guild that adds your app. An individual app's global commands are also available in DMs if that app has a bot that shares a mutual guild with the user.

Guild commands are specific to the guild you specify when making them. Guild commands are not available in DMs. Command names are unique per application within each scope (global and guild). That means:

- Your app cannot have two global commands with the same name
- Your app cannot have two guild commands within the same name on the same guild
- Your app can have a global and guild command with the same name
- Multiple apps can have commands with the same names

[!IMPORTANT]
> Apps can have a maximum of 5 global context menu commands,
> and an additional 5 guild-specific context menu commands per guild.

## UserCommandBuilder

The context menu user command builder will help you create user commands. The builder has these available fields and methods:

| Name     | Type     | Description                                                                                |
| -------- | -------- | ------------------------------------------------------------------------------------------------ |
| Name     | string   | The name of this context menu command.                                                           |
| WithName | Function | Sets the field name.                                                                             |
| Build    | Function | Builds the builder into the appropriate `UserCommandProperties` class used to make Menu commands |

## MessageCommandBuilder

The context menu message command builder will help you create message commands. The builder has these available fields and methods:

| Name     | Type     | Description                                                                                |
| -------- | -------- | --------------------------------------------------------------------------------------------------- |
| Name     | string   | The name of this context menu command.                                                              |
| WithName | Function | Sets the field name.                                                                                |
| Build    | Function | Builds the builder into the appropriate `MessageCommandProperties` class used to make Menu commands |

> [!NOTE]
> Context Menu command names can be upper and lowercase, and use spaces.
> They cannot be registered pre-ready.

Let's use the user command builder to make a global and guild command.

```cs
// Let's hook the ready event for creating our commands in.
client.Ready += Client_Ready;

...

public async Task Client_Ready()
{
    // Let's build a guild command! We're going to need a guild so lets just put that in a variable.
    var guild = client.GetGuild(guildId);

    // Next, lets create our user and message command builder. This is like the embed builder but for context menu commands.
    var guildUserCommand = new UserCommandBuilder();
	var guildMessageCommand = new MessageCommandBuilder();

    // Note: Names have to be all lowercase and match the regular expression ^[\w -]{3,32}$
    guildUserCommand.WithName("Guild User Command");
	guildMessageCommand.WithName("Guild Message Command");

    // Descriptions are not used with User and Message commands
    //guildCommand.WithDescription("");

    // Let's do our global commands
    var globalUserCommand = new UserCommandBuilder();
    globalUserCommand.WithName("Global User Command");
	var globalMessageCommand = new MessageCommandBuilder();
	globalMessageCommand.WithName("Global Message Command");

    try
    {
        // Now that we have our builder, we can call the BulkOverwriteApplicationCommandAsync to make our context commands. Note: this will overwrite all your previous commands with this array.
        await guild.BulkOverwriteApplicationCommandAsync(new ApplicationCommandProperties[]
        {
            guildUserCommand.Build(),
            guildMessageCommand.Build()
        });

        // With global commands we dont need the guild.
        await client.BulkOverwriteGlobalApplicationCommandsAsync(new ApplicationCommandProperties[]
        {
            globalUserCommand.Build(),
            globalMessageCommand.Build()
        });
    }
    catch(ApplicationCommandException exception)
    {
        // If our command was invalid, we should catch an ApplicationCommandException. This exception contains the path of the error as well as the error message. You can serialize the Error field in the exception to get a visual of where your error is.
        var json = JsonConvert.SerializeObject(exception.Error, Formatting.Indented);

        // You can send this error somewhere or just print it to the console, for this example we're just going to print it.
        Console.WriteLine(json);
    }
}

```

> [!NOTE]
> Application commands only need to be created once. They do _not_ have to be
> 'created' on every startup or connection.
> The example simple shows creating them in the ready event
> as it's simpler than creating normal bot commands to register application commands.

branch_name: refs/heads/dev