text:
ts-bus

#### A lightweight TypeScript event bus to help manage your application architecture

[![Build Status](https://travis-ci.org/ryardley/ts-bus.svg?branch=master)](https://travis-ci.org/ryardley/ts-bus)
[![codecov](https://codecov.io/gh/ryardley/ts-bus/branch/master/graph/badge.svg)](https://codecov.io/gh/ryardley/ts-bus)
[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/ryardley/ts-bus/blob/master/LICENSE)

### Example

```ts
import { EventBus, createEventDefinition } from "ts-bus";

// Define Event
export const someEvent = createEventDefinition<{ url: string }>()("SOME_EVENT");

// Create bus
const bus = new EventBus();

// Subscribe
bus.subscribe(someEvent, event => {
  alert(event.payload.url);
});

// Publish
bus.publish(someEvent({ url: "https://github.com" }));
```

### Rationale

We want to write loosely coupled highly cohesive applications and one of the best and easiest ways to do that is to use an event bus as a management layer for our applications.

This is the kind of thing that you could use effectively in most applications.

For my purposes I wanted a system that:

- Is framework agnostic can support Vue, React or Angular.
- Could enable micro-frontends / microlithic architecture.
- Can easily use React hooks to reduce state in the case of React.
- Does not conflate eventing with state management.
- Has really good TypeScript support.

### Alternatives

- Redux - conflates state management with eventing and causes complexity around async as a result. Redux has a highly invasive syntax that is difficult to remove or abstract out of an application. React comes with state management out of the box these days anyway. See my article ["Life after Redux"](https://itnext.io/life-after-redux-21f33b7f189e?source=friends_link&sk=a2566ae4b3b28797505a1295d70392fe)
- RxJS - could make a great event bus but feels too heavy handed for use with many projects.
- Node `events` - is a little too much API for what I need here. This lib actually decorates the `EventEmitter2` package. In the future I may remove it to become dependency free.

## Installation

Use your favourite npm client to install ts-bus. Types are included automatically.

Npm:

```bash
npm install ts-bus
```

Yarn:

```bash
yarn add ts-bus
```

## Example applications

[With Redux Devtools](examples/with-redux-dev-tools).

## Usage

### Create a bus

Create your EventBus globally somewhere:

```ts
// bus.ts
import { EventBus } from "ts-bus";
export const bus = new EventBus();
```

### Declare events

Next create some Events:

```ts
// events.ts
import { createEventDefinition } from "ts-bus";

export const taskCreated = createEventDefinition<{
  id: string;
  listId: string;
  value: string;
}>()("task.created");

export const taskLabelUpdated = createEventDefinition<{
  id: string;
  label: string;
}>()("task.label.updated");
```

Notice `createEventDefinition()` will often be called with out a runtime check argument and it returns a function that accepts the event type as an argument. Whilst possibly a tiny bit awkward, this is done because it is [the only way we can allow effective discriminated unions](https://github.com/ryardley/ts-bus/issues/9). See [switching on events](#switching-on-events-and-discriminated-unions).

### Runtime payload checking

You can also provide a predicate to do runtime payload type checking in development. This is useful as a sanity check if you are working in JavaScript:

```js
import p from "pdsl";

// pdsl creates predicate functions
const isLabel = p`{
  id: string,
  label: string,
}`;

export const taskLabelUpdated = createEventDefinition(isLabel)(
  "task.label.updated"
);

taskLabelUpdated({ id: "abc" }); // {"id":"abc"} does not match expected payload.
```

These warnings are suppressed in production.

### Subscribing

```ts
import { taskLabelUpdated, taskCreated } from "./event";
import { bus } from "./bus";

// You can subscribe using the event creator function
bus.subscribe(taskLabelUpdated, event => {
  const { id, label } = event.payload; // Event is typed
  doSomethingWithLabelAndId({ id, label });
});
```

### Unsubscribing

To unsubscribe from an event use the returned unsubscribe function.

```ts
const unsubscribe = bus.subscribe(taskLabelUpdated, event => {
  // ...
});

unsubscribe(); // removes event subscription
```

### Subscribing with a type string

You can use the event type to subscribe.

```ts
bus.subscribe("task.created", event => {
  // ...
});
```

Or you can use [wildcards](#wildcard-syntax):

```ts
bus.subscribe("task.**", event => {
  // ...
});
```

### Subscribing with a predicate function

You can also subscribe using a predicate function to filter events.

```ts
// A predicate
function isSpecialEvent(event) {
  return event.payload && event.payload.special;
}

bus.subscribe(isSpecialEvent, event => {
  // ...
});
```

You may find [pdsl](https://github.com/ryardley/pdsl) a good fit for creating predicates.

### Subscription syntax

As you can see above you can subscribe to events by using the `subscribe` method of the bus.

```ts
const unsubscriber = bus.subscribe(<string|eventCreator|predicate>, handler);
```

This subscription function can accept a few different options for the first argument:

- A `string` that is the specific event type or a wildcard selector eg. `mything.**`.
- An `eventCreator` function returned from `createEventDefinition<PayloadType>()("myEvent")`
- A `predicate` function that will only subscribe to events that match the predicate. Note the predicate function matches the entire `event` object not just the payload. Eg. `{type:'foo', payload:'foo'}`

The returned `unsubscribe()` method will unsubscribe the specific event from the bus.

### Publishing events

Now let's publish our events somewhere

```ts
// publisher.ts
import { taskLabelUpdated, taskCreated } from "./events";
import { bus } from "./bus";

function handleUpdateButtonClicked() {
  bus.publish(taskLabelUpdated({ id: "638", label: "This is an event" }));
}

function handleDishesButtonClicked() {
  bus.publish(
    taskCreated({ id: "123", listId: "345", value: "Do the dishes" })
  );
}
```

### Using a plain event object

If you want to avoid the direct dependency with your event creator you can use the plain event object:

```tsx
bus.publish({
  type: "kickoff.some.process",
  payload: props.data
});
```

### Republishing events

Lets say you have received a remote event from a websocket and you need to prevent it from being automatically redispatched you can provide custom metadata with each publication of an event to prevent re-emmission of events over the socket.

```ts
import p from "pdsl";

// get an event from a socket
socket.on("event-sync", (event: BusEvent<any>) => {
  bus.publish(event, { remote: true });
});

// This is a shorthand utility that creates predicate functions to match based on a given object shape.
// For more details see https://github.com/ryardley/pdsl
const isSharedAndNotRemoteFn = p`{
  type: ${/^shared\./},
  meta: {
    remote: !true
  }
}`;

// Prevent sending a event-sync if the event was remote
bus.subscribe(isSharedAndNotRemoteFn, event => {
  socket.emit("event-sync", event);
});
```

### Switching on Events and Discriminated Unions

```ts
// This function creates foo events
const fooCreator = createEventDefinition<{
  foo: string;
}>()("shared.foo");

// This function creates bar events
const barCreator = createEventDefinition<{
  bar: string;
}>()("shared.bar");

// Create a union type to represent your app events
type AppEvent = ReturnType<typeof fooCreator> | ReturnType<typeof barCreator>;

bus.subscribe("shared.**", (event: AppEvent) => {
  switch (event.type) {
    case String(fooCreator):
      // compiler is happy about payload having a foo property
      alert(event.payload.foo.toLowerCase());
      break;
    case String(barCreator):
      // compiler is happy about payload having a bar property
      alert(event.payload.bar.toLowerCase());
      break;
    default:
  }
});
```

### Wildcard syntax

You can namespace your events using period delimeters. For example:

```
"foo.*" matches "foo.bar"
"foo.*.thing" matches "foo.fing.thing"
"**" matches everything eg "foo" or "foo.bar.baz"
"*" matches everything within a single namespace eg. "foo" but not "foo.bar"
```

This is inherited directly from EventEmitter2 which ts-bus currently uses under the hood.

## React extensions

Included with `ts-bus` are some React hooks and helpers that provide a bus context as well as facilitate state management within React.

### BusProvider

Wrap your app using the `BusProvider`

```tsx
import React from "react";
import App from "./App";

import { EventBus } from "ts-bus";
import { BusProvider } from "ts-bus/react";

// global bus
const bus = new EventBus();

// This wraps React Context and passes the bus to the `useBus` hook.
export default () => (
  <BusProvider value={bus}>
    <App />
  </BusProvider>
);
```

### useBus

Access the bus instance with `useBus`

```tsx
// Dispatch from deep in your application somewhere...
import { useBus } from "ts-bus/react";
import { kickoffSomeProcess } from "./my-events";

function ProcessButton(props) {
  // Get the bus passed in from the top of the tree
  const bus = useBus();

  const handleClick = React.useCallback(() => {
    // Fire the event
    bus.publish(kickoffSomeProcess(props.data));
  }, [bus]);

  return <Button onClick={handleClick}>Go</Button>;
}
```

### useBusReducer

This connects state changes to bus events via a state reducer function.

Its signature is similar to useReducer except that it returns the state object instead of an array:

Example:

```ts
function init(initCount: number) {
  return { count: initCount };
}
const state = useBusReducer(reducer, initCount, init);
```

```tsx
import { useBus, useBusReducer } from "ts-bus/react";

const initialState = { count: 0 };

function reducer(state, event) {
  switch (event.type) {
    case "counter.increment":
      return { count: state.count + 1 };
    case "counter.decrement":
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const bus = useBus();
  const state = useBusReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => bus.publish({ type: "counter.increment" })}>
        +
      </button>
      <button onClick={() => bus.publish({ type: "counter.decrement" })}>
        -
      </button>
    </>
  );
}
```

### Custom subscriber function

You can configure `useBusReducer` with a custom `subscriber` passing in an options object.

```ts
// get a new useReducer function
const useReducer = useBusReducer.configure({
  subscriber: (dispatch, bus) => {
    bus.subscribe("count.**", dispatch);
  }
});

const state = useReducer(/*...*/);
```

NOTE: Boilerplate can be reduced by using the `reducerSubscriber` function.

```ts
useBusReducer.configure({
  subscriber: reducerSubscriber("count.**")
});
```

#### Usage with Redux dev tools

You can use ts-bus with Redux Devtools by using [Reinspect](https://github.com/troch/reinspect).

Here is an example:

```tsx
import React from "react";
import { StateInspector, useReducer } from "reinspect";
import { EventBus, createEventDefinition } from "ts-bus";
import { BusProvider, useBus, useBusReducer } from "ts-bus/react";

const bus = new EventBus();

export default function AppWrapper() {
  return (
    <BusProvider value={bus}>
      <StateInspector name="App">
        <App />
      </StateInspector>
    </BusProvider>
  );
}

const useConfiguredBusReducer = useBusReducer.configure({
  useReducer: (reducer, initState, initializer) =>
    useReducer(reducer, initState, initializer, "appreducer") // passing in the reinspect id
});

const increment = createEventDefinition<void>()("increment");
const decrement = createEventDefinition<void>()("decrement");

function App() {
  const b = useBus();
  const state = useConfiguredBusReducer(
    (state, action) => {
      switch (action.type) {
        case `${increment}`: {
          return {
            ...state,
            count: state.count + 1
          };
        }
        case `${decrement}`: {
          return {
            ...state,
            count: state.count - 1
          };
        }
      }
      return state;
    },
    { count: 0 }
  );

  return (
    <div>
      <button onClick={() => b.publish(decrement())}>-</button>
      {state.count} <button onClick={() => b.publish(increment())}>+</button>
    </div>
  );
}
```

#### useBusReducer configuration

Available options:

| Option     | Description                               |
| ---------- | ----------------------------------------- |
| subscriber | Reducer subscriber definition             |
| useReducer | Alternate React.useReducer implementation |

### useBusState

This connects state changes to bus events via a useState equivalent function.

```tsx
import { useBus, useBusState } from "ts-bus/react";

const setCountEvent = createEventDefinition<number>()("SET_COUNT");

function Counter() {
  const bus = useBus();
  const count = useBusState(0, setCountEvent);

  return (
    <>
      Count: {count}
      <button onClick={() => bus.publish(setCountEvent(count + 1))}>+</button>
      <button onClick={() => bus.publish(setCountEvent(count - 1))}>-</button>
    </>
  );
}
```

#### useBusState configuration

You can configure useBusState with a subscriber passing in an options object.

```ts
// get a new useState function
const useState = useBusState.configure({
  subscriber: (dispatch, bus) => bus.subscribe("**", ev => dispatch(ev.payload))
});

const state = useState(/*...*/);
```

NOTE: The boilerplate code can be reduced by using the stateSubscriber function.

```ts
const useState = useBusState.configure({
  subscriber: stateSubscriber("**")
});
```

Available options:

| Option     | Description                 |
| ---------- | --------------------------- |
| subscriber | State subscriber definition |

repository: busster/pup-server

repo_name: busster/pup-server


text:
# hosts

> Unified hosts file

Point your device at: https://tlvince.com/hosts/hosts

Based on [StevenBlack/hosts](https://github.com/StevenBlack/hosts). Rebuilds nightly via [GitHub Actions](https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site#creating-a-custom-github-actions-workflow-to-publish-your-site).

## Author

© 2023 Tom Vincent<EMAIL_ADDRESS>(https://tlvince.com)

## License

Released under the [MIT license](http://tlvince.mit-license.org).

license: MIT

repository: tlvince/hosts

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: tlvince/hosts


text:
# Query Support ⚠Deprecated⚠

Query allows you to run almost SQL style lookups against the data sitting on the ledger. These query only support the SELECT lookup.

```typescript
this.query
        .sql(`SELECT * FROM X WHERE [property] = ${stringVar}`)
        .then(doc => {
          if (doc.length > 0) {
            return reject("No States Found");
          }
          return resolve(true);
        })
        .catch(() => {
          reject("Query Error");
        });
```

##### Getting Started

You need to extend your class as :

```typescript
export default class [name] extends Query { }
```

Then to query the ledger you can run the above code anywhere inside the contract

```typescript
export default class [name] extends Query {
	...
    private myFunc(): void {
        this.query.sql("statement").then().catch();
    }
}
```

repository: activeledger/activeledger

gha_language: TypeScript

gha_license_id: MIT

repo_name: activeledger/activeledger


text:
#Signature
Complete any delivery service App with this Signature widget.
This widget allows you to save a signature to an attribute.

## Contributing
For more information on contributing to this repository visit [Contributing to a GitHub repository](https://world.mendix.com/display/howto50/Contributing+to+a+GitHub+repository)!

## Features
* Record signature in an attribute
* Customizable size, pencolor and grid
* Reset button to delete signature

## Configuration
Add the widget to a dataview. Connect the data URL property to an unlimited String attribute of the dataview context object.

### Properties
* *Pen color* - HTML color code of the pen.
* *Pen size* - Size of the pen in pixels.
* *Signature timeout* - Amount of milliseconds the widget will wait after the user has stopped writing before saving the signature.
* *Canvast height* - Height of writable area in pixels.
* *Canvas width* - Width of writable area in pixels.
* *Show background grid* - When set to yes, a grid is shown in the background of the writable area.
* *Grid X* - The distance in pixels between gridlines in the horizontal direction.
* *Grid Y* - The distance in pixels between gridlines in the vertical direction.
* *Grid color* - HTML color code of the grid
* *Grid border width* - Width of canvas border in pixels
* *Reset caption* - Caption that is shown on the button with which you can remove an existing signature.
* *Data URL* - Unlimited string attribute that is used to save the signature.

repository: mendix/Signature

gha_language: JavaScript

repo_name: mendix/Signature


text:
# Authorization code support

## 1. STS Token encoding

Obtain an authorization code by using the on-demand authorization function of Alibaba Cloud Security Token Service (STS).

Log on to the OSS browser by using the authorization code.

For details, visit https://help.aliyun.com/document_detail/31935.html

### (1) Create a role

Create a role in accordance with the instructions described in [STS On-demand Access Authorization](https://help.aliyun.com/document_detail/31935.html).

### (2) Generate an authorization code in the OSS browser

- Log on using the Access Key of a subaccount rather than the primary account.

- The subaccount must be assigned the "AliyunSTSAssumeRoleAccess" and "AliyunRAMReadOnlyAccess" permissions and the permission to access the directory to be authorized.

Subaccount authorization (recommended configuration for novice users):

![](../preview/genToken1.png)

Authorization in the OSS browser:

![](../preview/genToken2.png)

![](../preview/genToken3.png)

### (3) Logon using the authorization code:

![](../preview/token-login.png)

### (4) Authorization code format

The authorization code generated by a program must adopt the following format:

```javascript
var opt = {
  id: "",
  secret: "",
  stoken: "",
  privilege: "",
  expiration: "",
  osspath: "",
};

//toString
opt = JSON.stringify(opt);

//base64 encode
Buffer.from(opt).toString("base64");
```

For details, see the following code: [app/main/files/modals/grant-token-modal.js](app/main/files/modals/grant-token-modal.js).

## 2. Sub user AK encoding

Generated by a program must adopt the following format:

```javascript
var opt = {
  id: "",
  secret: "",
  desc: "",
  region: "oss-cn-shenzhen",
  osspath: "oss://your-bucket/test/",
  eptpl: "http://{region}.aliyuncs.com",
};

//toString
opt = JSON.stringify(opt);

//base64 encode
Buffer.from(opt).toString("base64");
```

repository: aliyun/oss-browser

branch_name: refs/heads/develop

gha_license_id: NOASSERTION

repo_name: aliyun/oss-browser


text:
# Administration

Once you have a [deployment](deployment.md) set up, you can follow the steps below to set up your first project.

## Setting up your first project

* [Create an admin account](account.md)
* [Create a project](project.md)
* [Define project metadata](metadata.md)

## Admin tasks

* [Backups and restoring](backups.md)
* [Viewing the kubernetes dashboard](dashboard.md)
* [Viewing stored logs](logs.md)

repository: smnamba/tator

repo_name: smnamba/tator


text:
# Implementation of Kinect Fusion

This repository is about an implementation of [Kinect Fusion](https://ieeexplore.ieee.org/document/6162880) algorithms. Here the image capturing part in real-time is not included. Instead, a sequence of pre-captured images is used as input for the system. After executing the program, the system will estimate each frame's camera pose and predict 3D surface points based on the signed distance value and the ray casting technique. As such, with more and more frames being processed, the predicted 3D points are gradually aggregated in the global coordinate and an indoor environment can then be reconstructed.

## Dependencies for Running Locally (Linux, NVIDIA GPU)

* cmake >= 2.8
  * [click here for installation instructions](https://cmake.org/install/)
* make >= 4.1
  * Linux: make is installed by default on most Linux distros
* OpenCV >= 4.1
  * The OpenCV 4.1.0 source code can be found [here](https://github.com/opencv/opencv/tree/4.1.0)
* gcc/g++ >= 5.4
  * Linux: gcc / g++ is installed by default on most Linux distros
* CUDA >= 11.0
  * Download CUDA [here](https://developer.nvidia.com/cuda-downloads/)
* PCL >= 1.7
  * Download PCL [here](https://pointclouds.org/downloads/)

## Basic Build Instructions

1. Clone this repo: `https://github.com/PoChang007/Kinect_Fusion_SLAM.git`
2. `cd Kinect_Fusion_SLAM`
3. `mkdir build && cd build`
4. Compile: `cmake .. && make -j4`
5. Run it: `./kinfu_imp`

## File Structure

* `src/` contains all `*.cpp` and `*.cu` files
* `data/` contains the RGB-D images of a static background scanning

| Class Name      | Description                               |
|-----------------|-------------------------------------------|
| KinfuPipeline   | Where camera intrinsic parameters and a voxel grid for TSDF are initialized. Parallel processing tasks fo each frame are called here |
| SystemUtility   | For image processings and storages of raw 3D data and predicted 3D points |
| ThreeDViewer    | Visualization of 3D point clouds. Each frame's predicted 3D points will be aligned in the global coordinate |

The `system_interface.cpp` is used to get start Kinect fusion system. The aggregated 3D point clouds are rendered in the 3D viewer. More information can be found in [Usage](#Usage).

### Parallel Processing Tasks

| Cuda file              | Description                               |
|------------------------|-------------------------------------------|
| projective_tsdf        | Each voxel's tsdf is updated based on the voxel's projection onto the current frame's depth |
| voxel_traversal        | Each ray will traverse the voxel grid to check zero crossing regions. If a zero crossing regions is found, the surface points can be predicted |
| raw_vertices           | Each pixel in the depth image is converted to the 3D point |
| sensor_pose_estimation | Find eligible point pairs between the current frame and the previous frame and use ICP to refine the current frame of camera pose |

## Usage

Once the program is started, the 3D point clouds are rendered in 3D viewer. The current processing frame of color and depth images are displayed in the different windows.

In 3D viewer,

* Press `r` to reset camera viewpoint
* Press `e` to end the program

## Other Information

1. In this repo the RGB-D data is captured by Kinect v1. It is workable for other RGB-D sensors as long as the image size, camera's extrinsics and extrinsics between color/depth cameras are known
1. When the current frame's processing is done, its corresponding camera pose is temporarily stored in `cv::Mat Kinfu::KinfuPipeline::extrinsic_matrix` until the processing of the next frame is finished
1. Default settings:
   * The size of voxel grid is 3.6m * 3.6m * 3m
   * The size of each voxel is 0.01m * 0.01m * 0.01m
   * For 3D visualization, point clouds are drawn per 5th frame
1. The system was originally implemented in Matlab. The voxel traversal algorithm for ray uses Matlab index style (start at 1)

## License

The project is released under the [MIT License](LICENSE.md).

branch_name: refs/heads/main


text:
## Steps for manual installation (not using terraform)

- Execute `ssh-add {keypair}.pem` to be able to access your cluster nodes via SSH

- Copy `./hosts.example.yaml` to `./hosts.yaml` and fill in the public IP addresses of your cluster so that Ansible can reach them and additionally set for the variables `bootstrap_ip` and `master_list` the private/internal IP addresses for cluster-internal communication. For example:

```
---
# Example for an ansible inventory file
all:
  children:
    bootstraps:
      hosts:
        # Public IP Address of the Bootstrap Node
        <IP_ADDRESS>:
    masters:
      hosts:
        # Public IP Addresses for the Master Nodes
        <IP_ADDRESS>:
    agents:
      hosts:
        # Public IP Addresses for the Agent Nodes
        <IP_ADDRESS>:
        <IP_ADDRESS>:
    agents_public:
      hosts:
        # Public IP Addresses for the Public Agent Nodes
        <IP_ADDRESS>:
  vars:
    # Choose the IP Detect Script
    # options: eth0, eth1, aws, gce
    ip_detect: eth0

    # (internal/private) IP Address of the Bootstrap Node
    bootstrap_ip: <IP_ADDRESS>

    # (internal/private) IP Addresses for the Master Nodes
    master_list:
      - <IP_ADDRESS>

    # DNS Resolvers
    resolvers:
      - <IP_ADDRESS>
      - <IP_ADDRESS>

    # DNS Search Domain
    dns_search: None

    # Internal Loadbalancer DNS for Masters (only needed for exhibitor: aws_s3)
    exhibitor_address: masterlb.internal
```

The setup variables for DC/OS are defined in the file `group_vars/all`. Copy the example file, by running:

```
cp group_vars/all.example group_vars/all
```

The now created file `group_vars/all` is for configuring DC/OS. You have to fill in the variables that match your preferred configuration. The variables are explained within the file.

To check that all instances are reachable via Ansible, run the following:

```
ansible all -m ping
```

Finally, you can install DC/OS by applying the Absible playbook:

```
ansible-playbook plays/install.yml
```

repository: jrx/terraform-ansible-dcos

repo_name: jrx/terraform-ansible-dcos


text:
# 📃 Script - Front Matter 📮 Add Aliases from Slug

This simple script will loop through a specified directory adding a [front matter](https://gohugo.io/content-management/front-matter/) [aliases](https://gohugo.io/content-management/urls/#aliases) variable from the `slug` variable value to all Markdown files.

```
slug:
    appears as the tail of the output URL. A value specified in front matter will override the segment of the URL based on the filename.

aliases:
    an array of one or more aliases (e.g., old published paths of renamed content) that will be created in the output directory structure . See Aliases for details.
```

> **Note:** This script is meant to be used with a [Hugo](https://gohugo.io) website.

## ✏ Prerequisities

This will install [gray-matter](https://github.com/jonschlinkert/gray-matter) the only dependency required.

```bash
npm install
```

## 🏃 Run

```bash
./add-aliases-from-slug.js ../motty.io/content/blog/archive
```

A temporary `tmp` folder will be created with all our modified Markdown files

## 🤔 Why?

We needed to [migrate from Ghost to Hugo](https://github.com/jbarone/ghostToHugo) and keep our old URLs accesibles so we don't lose positioning for that we needed to create an [aliases](https://gohugo.io/content-management/urls/#aliases) variable in each file so Hugo can handle the redirection.

## 👏 Resources

To build this script we use the smarter yaml front matter parser [gray-matter](https://github.com/jonschlinkert/gray-matter)

- [Ghost to Hugo Migration tool](https://github.com/jbarone/ghostToHugo)
- [Front Matter Hugo Documentation](https://gohugo.io/content-management/front-matter/)

Build with ❤ by 🐘 in the 🌏


text:
## elsa

[![Build Status](https://travis-ci.org/Manishearth/elsa.svg?branch=master)](https://travis-ci.org/Manishearth/elsa)
[![Current Version](https://img.shields.io/crates/v/elsa.svg)](https://crates.io/crates/elsa)
[![License: MIT/Apache-2.0](https://img.shields.io/crates/l/elsa.svg)](#license)

_🎵 Immutability never bothered me anyway 🎶_

This crate provides various "frozen" collections.

These are append-only collections where references to entries can be held on to even across insertions. This is safe because these collections only support storing data that's present behind some indirection -- i.e. `String`, `Vec<T>`, `Box<T>`, etc, and they only yield references to the data behind the allocation (`&str`, `&[T]`, and `&T` respectively)

The typical use case is having a global cache of strings or other data which the rest of the program borrows from.

### Running all examples

```bash
cargo test --examples --features indexmap
```

repository: Manishearth/elsa

gha_language: Rust

repo_name: Manishearth/elsa


text:
# [PackJS v0.1.0] (https://github.com/rajithadotco/packjs)
A simple tool to help manage JavaScript projects.

## Requirements

PHP version 5.3.0 or higher is required to use this tool.

Your project needs to be structured as shown in the diagram below.

The "src" folder contains all the JavaScript sources and the "bin" folder is used for the
output from PackJS.

    <project-name>/-|
                    |-bin/
                    |-src/-|
                    |      |-<package-name>/-|
                    |      |                 |-<package_start_file>.js [optional]
                    |      |                 |-<package_end_file>.js [optional]
                    |      |                 |-MyObject.js
                    |      |                 |-sub_folder/-|
                    |      |                               |-AnotherObject.js
                    |      |                               |-Blabla.js
                    |      |                               |-random.js
                    |      |
                    |      |-.js [optional]
                    |
                    |-<config>.ini

## Usage

Navigate to your project folder and use the following command:

    php packjs.php

## Documentation

For more information please see the documentation located [here] (http://rajitha.co/packjs.html).

## Project

This project doesn't have many files, here is an explanation of all the files:

* "hello" directory contains the example project explained in the documentation page located at [rajitha.co/packjs.html] (http://rajitha.co/packjs.html)
* "packjs.php" is the program itself.
* "LICENSE" contains the description of the license.

## License

This software is available under the BSD (FreeBSD) style license.

repository: rajithacodes/packjs

repo_name: rajithacodes/packjs


text:
# GradientInfill
![alt text](https://static1.squarespace.com/static/5d88f1f13db677155dee50fa/t/5e184edf208b5e01f31462a2/1578651390859/vlcsnap-2020-01-10-11h15m40s688.png?format=2500w)

This a Python script that post-processes existing G-Code to add gradient infill for 3D prints.

Watch my YouTube video about it: https://youtu.be/hq53gsYREHU

# Important Notes

In its current for it only works with G-Code files generated with CURA due to the comments CURA puts into the G-Code files.

It is also important to make sure that the "Walls" are printed before the "Infill" ("Infill before Walls" OFF).
For this script to work, also activate "Relative Extrusion" under "Special Modes".

Further instructions can be found on my website: http://cnckitchen.com/blog/gradient-infill-for-3d-prints

# GradientInfill.py (Cura postprocessor PlugIn script)

**Version : 1.5

GradientInfill.py Posprocessing Script for Cura PlugIn. Save the file in the _C:\Program Files\Ultimaker Cura **X.X**\plugins\PostProcessingPlugin\scripts_ directory.

Extrusion mode in Cura must be set in relative mode. If it's not the case an error message will be raised in Cura.

![Message](https://user-images.githubusercontent.com/11015345/72720216-c1662580-3b79-11ea-9583-60de8240eef2.jpg)

No Gcode will be generated by Cura in this case. Same behaviour if Cura settings are not suitable for Gradient Infill modification :

- Infill pattern type ZigZag , Concentric , Cross and Cross3D not allowed
- In cura the option "Connect Infill Lines" for the other patterns musn't be used.

The wall must be done before the Infill element. So In Cura the Option infill_before_walls must be set to Off

## Postprocessing Options ##
![PostProcessing](https://user-images.githubusercontent.com/11015345/73034404-138e9b80-3e45-11ea-8e84-1fa36a80e5a5.jpg)

- Gradient Distance :  Distance of the gradient (max to min) in mm
- Gradient Discretization : Only applicable for linear infills; number of segments within the gradient(segmentLength=gradientThickness / gradientDiscretization) use sensible values to not overload
- Max flow : Maximum extrusion flow
- Min flow : Minimum extrusion flow
- Short distance flow : Extrusion flow for short distance < 2x Gradient distance
- Gradual speed : Activate also Gradual Speed linked to the gradual flow
- Max over speed : Maximum over speed factor
- Min over speed : Minimum over speed factor
- Extruder Id : Define extruder Id in case of multi extruders
- Test with outer wall : "Test the gradiant with the outer wall segments

A new Flow Value for short distance (Linear move < 2 x Gradient distance) added to the standard GradientInfill script.

Add a gradual speed variation for machine without direct drive extruder.

![82574446_1223039984569029_7656888964539744256_o](https://user-images.githubusercontent.com/11015345/72863160-ec628d80-3ccf-11ea-9891-8583b62866f7.jpg)

Sample part with a Gradient distance set to 8 mm :
![82570108_1223017127904648_3642722292435255296_o](https://user-images.githubusercontent.com/11015345/72863337-8e827580-3cd0-11ea-9681-e1de7e2071c2.jpg)

gha_language: Python


text:
# Talking to Servers: LFE & Clojure

## Clojure Client with LFE Server

### Using OTP

In the ``examples`` directory of the Clojang source code there is a module containing a variation on the classic "ping-pong" server. It's written in LFE, but it could have been done in any BEAM (Erlang VM) language. Here's the code:

```cl
(defmodule ping-pong
  (behaviour gen_server)
  (export
    ;; gen_server implementation
    (start 0)
    (stop 0)
    ;; callback implementation
    (init 1)
    (handle_call 3)
    (handle_info 2)
    (terminate 2)
    (code_change 3)
    ;; server API
    (ping 0)
    (get-ping-count 0)))

;;; config functions

(defun server-name () (MODULE))
(defun callback-module () (MODULE))
(defun initial-state () 0)
(defun genserver-opts () '())
(defun register-name () `#(local ,(server-name)))
(defun unknown-command () #(error "Unknown command."))

;;; gen_server implementation

(defun start ()
  (gen_server:start (register-name)
                    (callback-module)
                    (initial-state)
                    (genserver-opts)))

(defun stop ()
  (gen_server:call (server-name) 'stop))

;;; callback implementation

(defun init (initial-state)
  `#(ok ,initial-state))

(defun handle_call
  (('ping _caller state-data)
    `#(reply pong ,(+ 1 state-data)))
  (('ping-count _caller state-data)
    `#(reply ,state-data ,state-data))
  (('stop _caller state-data)
    `#(stop shutdown ok ,state-data))
  ((_message _caller state-data)
    `#(reply ,(unknown-command) ,state-data)))

(defun handle_info
  ((`#(EXIT ,_pid normal) state-data)
   `#(noreply ,state-data))
  ((`#(EXIT ,pid ,reason) state-data)
   (io:format "Process ~p exited! (Reason: ~p)~n" `(,pid ,reason))
   `#(noreply ,state-data))
  ((_msg state-data)
   `#(noreply ,state-data)))

(defun terminate (_reason _state-data)
  'ok)

(defun code_change (_old-version state _extra)
  `#(ok ,state))

;;; our server API

(defun ping ()
  (gen_server:call (server-name) 'ping))

(defun get-ping-count ()
  (gen_server:call (server-name) 'ping-count))
```

We're going to compile and then run that code from the LFE REPL. Then, from a Clojure REPL, we'll talk to it.

Start the LFE REPL using the ``repl`` make target in the Clojang top-level directory:

```bash
$ make repl
LFE Shell V7.2 (abort with ^G)
(clojang-lfe@mndltl01)>
```

Next, compile the example:

```cl
(clojang-lfe@mndltl01)> (c "examples/ping-pong.lfe")
(#(module ping-pong))
```

Now we can start it:

```cl
(clojang-lfe@mndltl01)> (ping-pong:start)
#(ok <0.45.0>)
```

In a separate terminal window (in the Clojang top-level directory, just like the ``make repl`` command), start up the Clojure REPL:

```bash
$ lein repl
nREPL server started on port 58369 on host <IP_ADDRESS> - nrepl://<IP_ADDRESS>:58369
REPL-y 0.3.7, nREPL 0.2.10
Clojure 1.8.0
clojang.dev=>
```

Now we can create nodes for two ends of the connection, and then open a connection between the two:

```clojure
clojang.dev=> (def self (node/self :client))
#'clojang.dev/self
clojang.dev=> (def other (node/peer "clojang-lfe@mndltl01"))
#'clojang.dev/other
clojang.dev=> (def connx (node/connect self other))
#'clojang.dev/connx
```

With a connection established, we're able to execute Erlang module/function calls on the remote LFE/Erlang node:

```clojure
clojang.dev=> (conn/!rpc connx :ping-pong :ping)
nil
clojang.dev=> (conn/!rpc connx :ping-pong :ping)
nil
clojang.dev=> (conn/!rpc connx :ping-pong :ping)
nil
clojang.dev=> (conn/receive-rpc connx)
:pong
clojang.dev=> (conn/receive-rpc connx)
:pong
clojang.dev=> (conn/receive-rpc connx)
:pong
clojang.dev=> (conn/!rpc connx :ping-pong :get-ping-count)
nil
clojang.dev=> (conn/receive-rpc connx)
3
```

While the emphasis here is remote communications, it goes without saying that local sends are also possible. Since this is a ``gen_server`` implementation, the proper way to do this is by calling the API we defined:

```cl
(clojang-lfe@mndltl01)> (ping-pong:ping)
pong
(clojang-lfe@mndltl01)> (ping-pong:ping)
pong
(clojang-lfe@mndltl01)> (ping-pong:ping)
pong
(clojang-lfe@mndltl01)> (ping-pong:get-ping-count)
6
```

### Quick and Dirty

What we've demonstrated above is the "right way" to start thinking about long-running processes in the Erlang VM: using the infrastructure of OTP to build for reliability. We could have written something similar, but much more simply. It would also have been very fragile.

For instance, we could have done it like this:

```cl
(clojang-lfe@mndltl01)> (defun png-png (count)
                          (receive
                            (`#(ping ,caller)
                              (! caller 'pong) (png-png (+ 1 count)))
                            (`#(get-count ,caller)
                              (! caller count) (png-png count))
                            (`#(stop, caller)
                              (! caller 'stopped) 'stopped)))
png-png
```

Please don't write your LFE OTP apps like this, though :-) You'll slowly end-up reinventing OTP, though a partially-implemented and bug-ridden one ...

Back to this demonstration: all we need now to turn this into a simplistic server is to spawn it:

```cl
(clojang-lfe@mndltl01)> (set png-png-pid (spawn (lambda () (png-png 0))))
<0.71.0>
```

Let's test it out:

```cl
(clojang-lfe@mndltl01)> (! png-png-pid `#(ping ,(self)))
#(ping <0.68.0>)
(clojang-lfe@mndltl01)> (! png-png-pid `#(ping ,(self)))
#(ping <0.68.0>)
(clojang-lfe@mndltl01)> (! png-png-pid `#(ping ,(self)))
#(ping <0.68.0>)
(clojang-lfe@mndltl01)> (c:flush)
Shell got pong
Shell got pong
Shell got pong
ok
```

Since we're using the LFE REPL as the client, we'll need to ``flush`` its inbox to get the messages that our simple little server is sending to it.

Let's make the other call:

```cl
(clojang-lfe@mndltl01)> (! png-png-pid `#(get-count ,(self)))
#(get-count <0.68.0>)
(clojang-lfe@mndltl01)> (c:flush)
Shell got 3
ok
```

We're going to want to call this from Clojure too, so let's register the LFE process with a name:

```cl
(clojang-lfe@mndltl01)> (register 'png-png png-png-pid)
true
```

With that done, let's return to the Clojure REPL and make some calls to our second (simple-don't-deploy-with-this) server:

```clojure
clojang.dev=> (conn/! connx :png-png [:ping (node/get-pid self)])
nil
clojang.dev=> (conn/! connx :png-png [:ping (node/get-pid self)])
nil
clojang.dev=> (conn/! connx :png-png [:ping (node/get-pid self)])
nil
clojang.dev=> (conn/receive connx)
:pong
clojang.dev=> (conn/receive connx)
:pong
clojang.dev=> (conn/receive connx)
:pong
clojang.dev=> (conn/! connx :png-png [:get-count (node/get-pid self)])
nil
clojang.dev=> (conn/receive connx)
6
```

That looks not-so-erily familiar ...

## LFE Client with Clojure Server

### Using XXX (core.async?)

In the case of an LFE server, Erlang/OTP defined the service specification (i.e., ``gen_server``), but there is no analog in Clojure (core, anyway; the [Pulsar](http://docs.paralleluniverse.co/pulsar/#behaviors) library provides an OTP-inspired ``gen-server``). Sticking with the RPC example, there is no OTP-compliant mechanism for making calls on remote nodes in Clojure. This, of course, is no surprise, since the OTP RPC mechanism is very specific to the Erlang VM.

That being said, it's "simply" sturctured message passing, and there's no reason we cannot implement our own RPC server -- we just need to be able to hanle RPC messages. The Clojang library offers just this, and in fact, will automatically parse RPC-type messages sent from an Erlang VM node (in our case, LFE, but the mechanism is dialect-agnostic).

To demonstate this we need to set up a long-running Clojure XXX (analog to Erlang VM "process", dependent upon implementation) and then make requests to it. The Clojure XXX needs to accept OTP messages, parse them, evaluate the specified code, and then send the results back to the LFE node.

We use the same example as above: a simple ping-pong server which accepts RPC calls. Here is the source code:

```clojure
TBD
```

To run the server in the Clojure REPL, slurp it and XXX:

```clojure
TBD
```

Now, from your LFE REPL, make some calls:

```cl
TBD
```

As with the previous example, it's possible to call the ping-pong server from the same node where the server is running:

```clojure
TBD
```

### Quick and Dirty

With the core.match library for Clojure, we are able to get remarkably close to the
little server we wrote in LFE above:

```clojure
(require '[clojure.core.match :refer [match]])

(defn png-png
  []
  (let [init-state 0
        self (node/new :srvr)
        inbox (mbox/new self :pinger)]
    (loop [png-count init-state]
      (match [(mbox/receive inbox)]
        [[:ping caller]]
          (do (mbox/! inbox caller :pong)
              (recur (inc png-count)))
        [[:get-count caller]]
          (do (mbox/! inbox caller png-count)
              (recur png-count))
        [[:stop caller]]
          (do (mbox/close inbox)
              (node/close self)
              :stopped)))))
```

Let's paste this server into the Clojure REPL and then run it:

```clojure
(png-png)
```

Now let's head over to an LFE REPL and talk to the Clojure server:

```cl
(clojang-lfe@mndltl01)> (! #(pinger srvr@mndltl01) `#(ping ,(self)))
#(ping <0.34.0>)
(clojang-lfe@mndltl01)> (! #(pinger srvr@mndltl01) `#(ping ,(self)))
#(ping <0.34.0>)
(clojang-lfe@mndltl01)> (! #(pinger srvr@mndltl01) `#(ping ,(self)))
#(ping <0.34.0>)
(clojang-lfe@mndltl01)> (c:flush)
Shell got pong
Shell got pong
Shell got pong
ok
(clojang-lfe@mndltl01)> (! #(pinger srvr@mndltl01) `#(get-count ,(self)))
#(get-count <0.34.0>)
(clojang-lfe@mndltl01)> (c:flush)
Shell got 3
ok
```

Once we're done, we can ask the server to stop from LFE:

```cl
(clojang-lfe@mndltl01)> (! #(pinger srvr@mndltl01) `#(stop ,(self)))
#(stop <0.34.0>)
```

Back in the Clojure REPL you should now see:

```clojure
:stopped
```

repository: yurrriq/clojang

repo_name: yurrriq/clojang


text:
tabsearch - search your open tabs in Chrome.
====
Hit Ctrl-Y to search all titles, urls and content of all open tabs, select a tab with up/down arrow keys, and hit enter to switch.

What's New?
----
If you're switching to a tab in another window, bring that window to the front.

repository: bobbydigitales/tabsearch

repo_name: bobbydigitales/tabsearch


text:
# CSS Filters

A short guide on some of the options available for flexbox and how to style them correctly.

## Getting Started

Visit the page [here](http://evelynmaire.github.io/flexbox/).

## Built With

* [Prism](http://prismjs.com/) - Styling for code
* [Fontawesome](http://fontawesome.io/) - Icons

## License

This project is licensed under the MIT License.

## Acknowledgments

* [@mauricevancooten](http://github.com/mauricevancooten/) - Web Development tutor

repository: evelynmaire/flexbox

repo_name: evelynmaire/flexbox


text:
# Maya Math Node

[![Maya](https://img.shields.io/badge/Maya-2008+.svg)](https://www.autodesk.com/developmaya)
![Platforms](https://img.shields.io/badge/platform-windows%20%7C%20osx%20%7C%20linux-lightgray.svg)
[![License](http://img.shields.io/:license-mit-blue.svg)](http://opensource.org/licenses/MIT)

## Description

This plug-in can be used in place of the Maya 'Expression' system.
Maya's evaluation of 'Expressions' depends on the contents of the
expression – sometimes you have to force evaluation - whereas, for
a node, the Maya DG will always do it for you when needed. Debugging
a Maya 'Expression' is not easy either (no tools are available), and
requires a knowledge of MEL. Using the MathNode plug-in, you can use
a Python debugger to debug the Node evaluation [see the following
Blog post for details](http://around-the-corner.typepad.com/adn/2012/07/python-debugging-in-maya.html).
In any case, it is always preferable to use self-contained nodes and
connections over expressions whenever possible.

## System Requirements

This plug-in has been tested with Autodesk Maya 2012-18.

This plug-in is a Python based plug-in, so it does not require any
compilation and works on Window 32bit/64bit, Mac OS, and Linux.

## Installation

### Manual Installation

The following steps are for using the plug-in with Autodesk Maya
2012-18. If you are using Maya 2018, please consider the
release number as "2018" in the paths listed below.

  1. If you are using Windows 7 (or Vista), first check if the
     zip file needs to be unblocked. Right-click on the zip file
     and select "Properties". If you see an "Unblock" button, then
     click it.

  2. Extract the plug-in module to any location you'd like. But keep
     the directory structure as is.

  3. Copy the mathNode.mod into the following folder
     ```
     Windows 7
     C:\users\<your login>\Documents\maya\2018[-x64]\modules

     MacOS
     /Users/Shared/Autodesk/maya/2018/modules

     Linux
     /home/<your login>/maya/2018/modules
     ```

  4. Edit the new mathNode.mod file in a text editor and modify the
     path <mypath>, to reflect the location where you copied the files.

  5. Once installed, the "mathNode" plug-in will be available
     in your Maya plug-in manager. Open the plug-in manager, load
     the plug-in, and select the 'Auto load' option. The plug-in manager
     can be found in:
     ```
      ->Window->Settings/Preferences/Plug-in manager
     ```

### Install from the AppStore

Go and Download the plugin installer from the
[AppStore](https://apps.autodesk.com/MAYA/en/Detail/Index?id=212304226072872821&appLang=en&os=Win64)

## Usage

Inside Maya, create a new node by using the MEL command 'createNode'.
I.e.  createNode asdkMathNode;

Then you can create connections from this/to this node as usual.
The node has for now 3 possible input parameters 'a, b, c', one 'expression'
and 1 output parameter 'result'. The 'expression' parameter can contain
any mathematical formula (including constants). For examples below:
  ```
  sin(a)
  a+b
  sin(a*pi/2)
  sin((a+sqrt(b))*3.14/180)-c
  factorial(c)
  sum([10, .1, c])
  ```

The expression has to be written in Python syntax. Python Math functions are
documented here: http://docs.python.org/library/math.html

## Uninstallation

### Manual Uninstall

Simply removing the "mathNode.mod" files from your system folder, and
delete the plug-in module folder will uninstall the plug-in.

### Uninstall from the AppStore

Go and Download the plugin installer from the
[AppStore](https://apps.autodesk.com/MAYA/en/Detail/Index?id=212304226072872821&appLang=en&os=Win64)

## Notes

Instead of writing a very long formula in one node, you can combine
several node to compose a complete formula. This will have a very limited
impact on the execution/evaluation time.

## Limitations

The current implementation accepts both native Python math module functions
and your own function implemented in the Maya embedded Python Editor, but the
Python code for custom functions is not saved within the node/scene.
This UI in the property window is very limited today - the plug-in will be
enhanced in future to support:
  a library of functions,
  the ability to add variables,
  to store python code custom function in file,

## Further Reading

For more information on developing with Maya, please visit the
Maya Developer Center at http://www.autodesk.com/developmaya

## Feedback

Email us at cyrille @ autodesk . com with feedback or requests for enhancements.

## Release History

1.0    Original release                     (August 1, 2012)

--------

## License

This sample is licensed under the terms of the [MIT License](http://opensource.org/licenses/MIT).
Please see the [LICENSE](LICENSE) file for full details.

## Written by

Cyrille Fauvel

Forge Partner Development

http://developer.autodesk.com/

http://around-the-corner.typepad.com

repository: cyrillef/MayaMathNode

repo_name: cyrillef/MayaMathNode


text:
##  Post All Un-Posted G/L Transactions (GLTRANS.P1)

<PageHeader />

**Form Details**
[ Form Details ](GLTRANS-P1-1/README.md)

**Purpose**
The GLTRANS.P1 procedure is used to post all un-posted GLTRANS records. Unposted GLTRANS journal entries may occur in one of two ways. First, the [ GL.CONTROL ](../../../../../../../../../../../rover/AP-OVERVIEW/AP-ENTRY/AP-E/CHECKS-E/AP-CONTROL/GLCHART-E/GLCHART-E-1/GL-CONTROL) may be setup to allow the filing of [ GLTRANS.E ](../../../../../../../../../../../rover/AP-OVERVIEW/AP-ENTRY/ACCT-CONTROL/ACCT-CONTROL-1/ar-e/AR-E-1/CASH-E/recon-e/RECON-E-4/GLTRANS-E) without posting. This allows the editing of all transactions prior to posting. Second, all GLTRANS records created though the [ GLINT.P2 ](GLINT-P2.htm) interface posting process are filed without posting.

**Frequency of Use**
As required.

**Prerequisites**
Setup of the [ GL.CONTROL ](../../../../../../../../../../../rover/AP-OVERVIEW/AP-ENTRY/AP-E/CHECKS-E/AP-CONTROL/GLCHART-E/GLCHART-E-1/GL-CONTROL) record ( [ GL.CONTROL ](../../../../../../../../../../../rover/AP-OVERVIEW/AP-ENTRY/AP-E/CHECKS-E/AP-CONTROL/GLCHART-E/GLCHART-E-1/GL-CONTROL) ) and the establishment of a fiscal year via the [ FY.E ](FY-E/README.md) procedure. All account numbers used must be present in the GLCHART file.

<badge text= "Version 8.10.57" vertical="middle" />

<PageFooter />

repository: zumasys/docs

repo_name: zumasys/docs


text:
---
title: "About The Theme"
menu: "main"
draft: false
---

Indigo is a lightweight theme for [Hugo][hugo] with [IndieWeb][indieweb] features baked in. It's great for longer-form blogging, placing its focus on distraction-free reading and beautiful typefaces.

Read more about the theme [here][intro].

[hugo]: https://gohugo.io
[indieweb]: https://indieweb.org/
[intro]: /post/introducing-indigo

repository: AngeloStavrow/hello-indigo

repo_name: AngeloStavrow/hello-indigo


text:
---
layout: post
title:  "Linux and USB virtual serial devices (CDC ACM)"
date:   2021-04-27 08:18:00 +02:00
categories: Artikel
tweet_url: "https://twitter.com/zekjur/status/1386930540817920005"
---

During my work on [Teensy 4.1](https://www.pjrc.com/store/teensy41.html) support
in [ChibiOS](https://en.wikipedia.org/wiki/ChibiOS/RT) for the QMK keyboard
firmware, I noticed that ChibiOS’s virtual serial device USB demo would
sometimes print garbled output, and that I would never see the ChibiOS shell
prompt.

This article walks you through diagnosing and working around this issue, in the
hope that it helps others who are working with micro controllers and USB virtual
serial devices.

## Background

Serial interfaces are often the easiest option when working with micro
controllers to print text: you only connect `GND` and the micro controller’s
serial `TX` pin to a USB-to-serial converter. The `RX` pin is only needed when
you want to send text to the micro controller as well.

While conceptually simple, the requirement for an extra piece of hardware
(USB-to-serial adapter) is annoying. If your micro controller has a working USB
interface and USB stack, a popular alternative is for the micro controller to
provide a virtual serial device via USB.

This way, you just need one USB cable between your micro controller and
computer, reusing the same connection you already use for programming the
device.

A popular choice within this solution is to provide a device conforming to the
USB Communications Device Class (CDC) standard, specifically its Abstract
Control Model (ACM), which is typically used for modem hardware.

On Linux, these devices show up as e.g. `/dev/ttyACM0`. In case you’re
wondering: `/dev/ttyUSB0` device names are used by more specific drivers
(vendor-specific). The blog post [What is the difference between /dev/ttyUSB and
/dev/ttyACM?](https://rfc1149.net/blog/2013/03/05/what-is-the-difference-between-devttyusbx-and-devttyacmx/)
goes into a lot more detail.

## ModemManager

One unfortunate side-effect of using a modem standard to provide a generic
serial device is that modem-related software might mistake our micro controller
for a modem.

Use the following command to disable ModemManager until the next reboot, which
otherwise might open and probe any new serial devices:

```
% sudo systemctl mask --runtime --now ModemManager
```

## Problem statement

With a regular, non-USB serial interface, you can send data at any time. If
nobody is receiving the data on the other end, the micro controller doesn’t care
and still writes serial data.

When using the ChibiOS shell with a regular serial interface, this means that if
you open the serial interface too late, you will not see the ChibiOS shell
prompt. But, if you have the serial interface already opened when powering on
your device, you will be greeted by ChibiOS’s shell prompt:

```
ChibiOS/RT Shell
ch>
```

With a USB serial, however, the host will not transfer data from the device
until the serial interface is opened. This means that writes to the USB serial
can block, whereas writes to the UART serial will not block but may go ignored
if nobody is listening.

So when I open the USB serial interface, I would expect to see the ChibiOS shell
prompt like above. Instead, I would often not see any prompt at all, and I would
even sometimes see garbled output like this:

```
cch> biOS/RT She
```

## USB analysis with Wireshark

[Wireshark](https://en.wikipedia.org/wiki/Wireshark) allows us to analyze USB
traffic in combination with the `usbmon` Linux kernel module.

Looking through the captured packets, I noticed unexpected packets from the host
(computer) to the device (micro controller), specifically containing the
following bytes:

1. hex `0xa` = ASCII `\n`
1. hex `0xd` = ASCII `\r`

Seeing any packets in this direction is unexpected, because I am only opening
the serial interface **for reading**, and I am not consciously sending
anything. So where do the packets come from?

To verify I am not missing any nuance of the CDC protocol, I added debug
statements to the ChibiOS shell to log any incoming data. The `\n\r` bytes
indeed make it to the ChibiOS shell.

When the shell receives a line break, it prints a new prompt. This seems to be
the reason why I’m seeing garbled data: while the output is transferred to the
host, line breaks are received, causing more data transfers. It’s as if somebody
was hammering the return key really quickly.

## Linux tty echo vs. ChibiOS shell banner

The unexpected `\n\r` bytes turn out to come from the Linux USB CDC ACM driver,
or its interplay with the Linux tty driver, to be specific. The CDC ACM driver
is a kind of tty driver, so it is built atop the Linux tty infrastructure, whose
[standard settings include various `ECHO`
flags](https://elixir.bootlin.com/linux/v5.11.16/source/drivers/tty/tty_io.c#L122).

When echoing is enabled, the ChibiOS shell banner triggers echo characters,
which in turn are interpreted as input to the shell, causing garbled output.

So why is echoing enabled? Wouldn’t a terminal emulator turn off echoing first
thing?

Yes. But, when the CDC ACM driver receives the first data transfer via USB
(already queued), the standard tty settings are still in effect, because the
application did not yet have a chance to set its tty configuration up!

This can be verified by running the following command on a Linux host:

```shell
% stty -F /dev/ttyACM0 115200 -echo -echoe -echok
```

Even though the command’s sole purpose is to configure the tty, its opening of
the device still causes the banner to print, and echoing to happen, and garbled
output is the result.

It turns out this is a somewhat common problem. Hence, the Linux USB CDC ACM
driver [has a quirks
table](https://elixir.bootlin.com/linux/v5.11.16/source/drivers/usb/class/cdc-acm.c#L1708),
in which devices that print a banner select the `DISABLE_ECHO` quirk, which
results in the CDC ACM driver turning off the echoing termios flag early:

```c
static const struct usb_device_id acm_ids[] = {
	/* quirky and broken devices */
	{ USB_DEVICE(0x0424, 0x274e), /* Microchip Technology, Inc. */
	  .driver_info = DISABLE_ECHO, }, /* DISABLE ECHO in termios flag */
// …
```

So, a quick solution to turn off echoing early is to change your USB vendor and
product id (VID/PID) to an ID for which the Linux kernel applies the
`DISABLE_ECHO` quirk, e.g.:

```c
#define USB_DEVICE_VID 0x0424
#define USB_DEVICE_PID 0x274e
```

## Flushing in Screen

With tty echo disabled, I don’t see garbled output anymore, but still wouldn’t
always see the ChibiOS shell prompt!

This issue turned out to be specific to the terminal emulator program I’m
using. For many years, I have been using
[Screen](https://en.wikipedia.org/wiki/GNU_Screen) for serial devices of any
sort.

I was surprised to learn during this investigation that Screen [flushes any
pending
output](https://git.savannah.gnu.org/cgit/screen.git/tree/src/window.c?id=d7bd327fdf799c82f9a359365d461edb755056ea#n971)
when opening the device. This typically isn’t a problem because adapter-backed
serial devices are opened once and then stay open. USB virtual serial devices
however are only opened when used, and disappear when loading new program code
onto your micro controller.

I verified this is the problem by using {{< man
name="cat" section="1" >}} instead, with which I can indeed see the prompt:
```
% cat /dev/ttyACM0

ChibiOS/RT Shell

                ch>
```

After commenting out the flush call in Screen’s sources, I could see the prompt
in Screen as well.

{{< note >}}

**Tip:** During the review phase of this article,
[tio](https://github.com/tio/tio/) was pointed out to me as a terminal program
which automatically reconnects. This won’t help with the problem at hand, but
seems handy nevertheless.

{{< /note >}}

## Line ending conversion

Now that we no longer flush the prompt away, why is the spacing still incorrect,
and where does it go wrong?

```

ChibiOS/RT Shell

                ch>
```

If we use {{< man name="strace" section="1" >}} to see what {{< man
name="screen" section="1" >}} or {{< man name="cat" section="1" >}} read from
the driver, we see:

```
797270 read(7, "\n\nChibiOS/RT Shell\n\nch> ", 4096) = 24
```

We would have expected `"\r\nChibiOS/RT Shell\r\nch> "` instead, meaning all
Carriage Returns (`\r`) have been translated to Newlines (`\n`).

This is again due to the [Linux tty driver’s default termios
settings](https://elixir.bootlin.com/linux/v5.11.16/source/drivers/tty/tty_io.c#L122):
`c_iflag` enables option `ICRNL` by default, which translates `CR` (Carriage
Return) to `NL` (Newline).

Unfortunately, contrary to the `DISABLE_ECHO` quirk, there is no corresponding
quirk in the Linux ACM driver to turn off line ending conversion, so a fix would
need a Linux kernel driver change!

## Device-side workaround: wait until opened

At this point, we have covered a few problems that would need to be fixed:

1. Change USB VID/PID to get the `DISABLE_ECHO` quirk in the driver.
1. Recompile terminal emulator programs to remove flushing, if needed.
1. Modify kernel driver to add quirk to disable Carriage Return (`\r`) conversion.

Time for a quick reality check: this seems too hard and too long a time for all
parts of the stack to be fixed. Is there an easier way, and why don’t others run
into this problem? If only the device didn’t print its banner so early, that
would circumvent all of the problems above, too!

Luckily, the host actually notifies the device when a terminal emulator program
opens the USB serial device by sending a `CDC_SET_CONTROL_LINE_STATE` request. I
verified this behavior on Linux, Windows and macOS.

So, let’s implement a workaround in our device code! We will delay starting the
shell until:

1. The USB serial device was opened (not just configured).
1. An additional delay of 100ms has passed to give the terminal emulator
   application a chance to configure the serial device.

In our `main.c` loop, we wait until USB is active, and until we receive the
first `CDC_SET_CONTROL_LINE_STATE` request because the serial port was opened:

```c
  while (true) {
    if (SDU1.config->usbp->state == USB_ACTIVE) {
      chSemWait(&scls);
      chThdSleepMilliseconds(100);

      thread_t *shelltp = chThdCreateFromHeap(NULL, SHELL_WA_SIZE, "shell", NORMALPRIO + 1, shellThread, (void *)&shell_cfg1);
      chThdWait(shelltp);
    }
  }
```

And in our `usbcfg.c`, when receiving a `CDC_SET_CONTROL_LINE_STATE` request, we
will reset the semaphore to non-blockingly wake up all waiters:

```c
extern semaphore_t scls;

bool requests_hook(USBDriver *usbp) {
  const bool result = sduRequestsHook(usbp);

  if ((usbp->setup[0] & USB_RTYPE_TYPE_MASK) == USB_RTYPE_TYPE_CLASS &&
      usbp->setup[1] == CDC_SET_CONTROL_LINE_STATE) {
    osalSysLockFromISR();
    chSemResetI(&scls, 0);
    osalSysUnlockFromISR();
  }

  return result;
}
```

## Screenshots: Mac and Windows

Aside from Linux, I also verified the workaround works on a Mac (with Screen):

{{< img src="chibios-acm-mac.jpg" alt="USB virtual serial device on macOS" >}}

…and that it works on Windows (with PuTTY):

{{< img src="chibios-acm-windows10.jpg" alt="USB virtual serial device on Windows 10" >}}

repository: stapelberg/hugo

extension: markdown

gha_language: HTML

repo_name: stapelberg/hugo


text:
# What's here?
Here you can find a small collection of [Microbit](https://microbit.org) JavaScript codes. Feel free to use them in any possible way!

## snake.js
It's Snake for the Micorbit ...

## pong-and-more.js
Playing with some buttons, sensors and functions. The code includes the following modes (shake to switch modes):
* Current temperature
* Pong
* Gravity controlled ball
* Display light level
* Compass

## game-of-life.js
I'm not sure whether it is actually working. My actual goal was to create a game field of variable size through which one can scroll. Since this part is working just fine, I've uploaded it anyway ...


text:
# [gulp](http://gulpjs.com)-sort-amd

> Sorts files in stream by dependencies defined according to the AMD/require.js specification. Used in conjunction with [gulp-concat](https://github.com/wearefractal/gulp-concat) to combine files in the correct order, so dependent files execute first when loaded.

This plugin allows you to use your modules without adding the weight of requirejs to your website.  In order to use it though, you **must** name all your modules, or it can't be retrieved from the hash map. It will work with most any AMD/UMD libraries, as long as they set a global object if `define.amd` is `false`.

The greatest benefit of this is the ability to require modules from outside the bundle itself, thereby allowing you to split bundles up per page (or even within a single page app) and still allow modules across bundles to communicate with each other without requirejs.

This assumes you are concatenating all of your scripts into various bundles, as this method prevents dynamic loading of individual modules (which I saw as a plus since it's best to bundle anyway). But because you can access modules in one bundle from another, you can dynamically load that bundle with a single, simple XHR call. This is ideal for single page apps that have large sections of content that you only want to load if the user accesses them, which is exactly the use case I built this for.

## Install

```bash
$ npm install --save-dev gulp-sort-amd
```

## Usage

### Gulpfile

```js
var gulp = require('gulp');
var sortAmd = require('gulp-sort-amd');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');

gulp.task('default', function () {
	return gulp.src('src/**/*.js')
		.pipe(sortAmd())
		.pipe(sourcemaps.init())
        .pipe(concat('scripts.js'))
        .pipe(sourcemaps.write('./'))
		.pipe(gulp.dest('dist'));
});
```

### Source file

Named modules with dependencies as a parameter:
```js
define('a', ['sub/b', '../c'], function(b, c) {
	// hot sauce
});
```

Unnamed modules in the commonJS style:
```js
define(function() {
	var b = require('b');
	var c = require('c');
});
```

And everything else [amdetective](https://github.com/mixu/amdetective) supports.

## License

gulp-sort-amd is MIT licensed. Feel free to use it, contribute or spread the word. Created by [Corey Birnbaum](https://twitter.com/vonWolfehaus). Based off of gulp-deps-order by Petr Nevyhoštěný ([Twitter](https://twitter.com/pnevyk)).

repository: vonWolfehaus/gulp-sort-amd

repo_name: vonWolfehaus/gulp-sort-amd


text:
# Hoverfly

A simple container to run [hoverfly](https://docs.hoverfly.io/en/latest/).

TODO create a template

## Usage

### Running in OpenShift

Build the container and deploy it in openshift:

`$ oc new-app https://github.com/labs-ci-cd/labs-ci-cd --name=hoverfly --context-dir=docker/hoverfly`

Expose the proxy/webserver port

`$ oc expose svc hoverfly --port 8500`

Expose the admin interface, including the rest API

`$ oc expose svc hoverfly --port 8888 --name hoverfly-admin`

### Uploading Simulation Files in OpenShift

`$ curl -X PUT <hoverfly-admin-route>/api/v2/simulation --upload-file <file-name>`

See [the docs](https://docs.hoverfly.io/en/latest/pages/reference/api/api.html) for detail

### Running and Uploading in Docker

Running in standalone docker is not an objective for this container. Look at [this issue](https://github.com/SpectoLabs/hoverfly/issues/675) in hoverfly or just [run the binary locally](https://docs.hoverfly.io/en/latest/pages/introduction/downloadinstallation.html) without a container. It's a Go binary, so it's easy.

### Runtime Environment Variables

- `RUN_AS_WEBSERVER`: if set to any value, the hoverfly will start as a webserver. defaults to running as a proxy

repository: rht-labs/cab-it

gha_language: Groovy

repo_name: rht-labs/cab-it


text:
# `withActions(dispatcher, actions, [prop])`

This is a decorator that can be used to insert ready-to-use actions into your
component.

Actions are supposed to be written as pure functions for composability. However, the
result needs to be dispatched somehow. `withActions` is a decorator that injects an
object containing actions into your component as a prop and wraps them in a
function that injects the result into the [`dispatch`](Dispatcher.md#dispatch)
method.

## Arguments

1. `dispatcher`: This is the dispatcher that you want to dispatch your actions
  on.

1. `actions`: This is your object containing pure functions, that return your
  plain object actions.

1. `prop` (Optional): This is the prop where the wrapped actions are going to be
  passed into your child component. Defaults to: `actions`

## Returns

A function that takes the child component and returns a top-level component
that wraps it.

## Example

### ES6 with Decorator Syntax

```js
// ...
import { withActions } from 'fluorine-lib'
import * as actions from './actions'
import dispatcher from './dispatcher'

@withActions(dispatcher, actions)
export default class YourComponent extends React.Component {
  render() {
    return (
      <button onClick={this.props.actions.doSomething}>
        Do something!
      </button>
    )
  }
}
```

The actions used in this example might look something like this:

```
export function doSomething() {
  return {
    type: 'DO_SOMETHING'
  }
}
```

Note that the import instruction `* as actions` transforms all of the exports
into a single object.

## ES5

```js
// ...
var withActions = require('fluorine-lib').withActions
var actions = require('./actions')
var dispatcher = require('./dispatcher')

var YourComponent = React.createClass({
  render: function() {
    return (
      <button onClick={this.props.actions.doSomething}>
        Do something!
      </button>
    )
  }
})

module.exports = withActions(dispatcher, actions)(YourComponent)
```

With the actions for the ES5 example looking something like this:

```js
module.exports = {
  doSomething: function() {
    return {
      type: 'DO_SOMETHING'
    }
  }
}
```

## A note on Babel

To use decorators in Babel you need to enable them. You can find instructions on
how to enable a decorator plugin here:

http://babeljs.io/docs/plugins/syntax-decorators/

repository: rgbkrk/fluorine

repo_name: rgbkrk/fluorine


text:
---
title: "Previous Versions of bradybellini.com"
date: 2021-09-25T21:14:06-07:00
draft: false
summary: View previous version of my website via the Wayback Machine
---
I tend to change my website when I want to try out something new or want a small project to work on. You can use the Wayback Machine to view old versions of my personal website starting in 2016 when I used to use tumblr. Now it is powered by Hugo using the PaperMod theme.

https://web.archive.org/web/changes/bradybellini.com


text:
# Lastly

Coding test using Last.fm

_Work in progress_

### API

[Get artist info](https://www.last.fm/api/show/artist.getInfo)

[Sample search](https://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Cher&api_key=5abe1e36c731df9fe52f884ce99455ec&format=json)

Unfortunately images are [no more](https://getsatisfaction.com/lastfm/topics/api-announcement-dac8oefw5vrxq) 😞

### TODO

- [ ] Unit and UI tests (for examples see the https://github.com/zfoltin/twittererer repo for now)
- [ ] Introduce dependency injection (again, see an example in the [twitterere](https://github.com/zfoltin/twittererer) repo for now)
- [ ] Tidy up the artist detail screen
- [ ] Create styles for common text styles
- [ ] Move common sizes to dimens.xml (8dp, 16dp, 32dp, 20sp...)
- [ ] Make HTML look HTML in the artist bio text
- [x] Improve the UX by using shared element activity transition for the artist image and name
- [ ] Use Android Architecture Components - ViewModels, Live Data, Navigation...
- [ ] Upgrade to AndroidX and Material Components

repository: zfoltin/lastly

repo_name: zfoltin/lastly


text:
# go mmaths

Just a set of math routines that I wrote to supplement go's math package.

## updates

**since go v1.10**

Function *Round* has been changed to *RoundTo* as the go math package now includes a *Round* functon

repository: maseology/mmaths

repo_name: maseology/mmaths


text:
# Download Github Release

A node module to download Github release assets. It will also uncompress zip
files and skip downloading if a file already exists.

[![Build Status](https://travis-ci.org/terascope/fetch-github-release.svg?branch=master)](https://travis-ci.org/terascope/fetch-github-release)
[![codecov](https://codecov.io/gh/terascope/fetch-github-release/branch/master/graph/badge.svg)](https://codecov.io/gh/terascope/fetch-github-release)
[![Build Status](https://david-dm.org/terascope/fetch-github-release.svg)](https://david-dm.org/terascope/fetch-github-release)

```
$ fetch-github-release -s darwin-x64 electron electron
Downloading<EMAIL_ADDRESS>electron-v1.3.1-darwi... ▇▇▇▇▇---------------------------------------------------- 662.8s
electron-v1.3.1-darwi... ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇--------- 13.4s
electron-v1.3.1-darwi... ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇--- 3.6s
ffmpeg-v1.3.1-darwin-... ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 0.0s
```

## API

### Usage

If you need to download assets from a private repository or you need to avoid rate limits, you can pass an option token for the request. To generate a token go to your Github [settings](https://github.com/settings/tokens) and a token with `public_repo` or `repo` (for private repos) permissions.

```javascript
const downloadRelease = require('fetch-github-release');

const user = 'some user';
const repo = 'some repo';
const token = process.env.GITHUB_TOKEN
const outputdir = 'some output directory';
const leaveZipped = false;
const disableLogging = false;

// Define a function to filter releases.
function filterRelease(release) {
  // Filter out prereleases.
  return release.prerelease === false;
}

// Define a function to filter assets.
function filterAsset(asset) {
  // Select assets that contain the string 'windows'.
  return asset.name.indexOf('windows') >= 0;
}

downloadRelease(user, repo, token, outputdir, filterRelease, filterAsset, leaveZipped, disableLogging)
  .then(function() {
    console.log('All done!');
  })
  .catch(function(err) {
    console.error(err.message);
  });
```

`downloadRelease` returns an array of file paths to all of the files downloaded
if called with `leaveZipped = true`.

repository: CodeCastTeam/fetch-github-release

repo_name: CodeCastTeam/fetch-github-release


text:
# CONTOURS HIERARCHY in OPENCV

## What is heirarchy?
- In case of nested figures, we call outer one as parent and inner one as child.
- This way, contours in an image has some relationship to each other. And we can specify how one contour is connected to each other, like, is it child of some other contour, or is it a parent etc.
- Representation of this relationship is called the Hierarchy.

## Hierarchy Representation in OpenCV
OpenCV represents it as an array of four values :
[Next, Previous, First_Child, Parent]

# Input image is:

![Image](https://i.imgur.com/FKe36pL.png)

# Contour Retrieval Mode

## 1. RETR_LIST
- It simply retrieves all the contours, but doesn't create any parent-child relationship.
- Parents and kids are equal under this rule, and they are just contours. ie they all belongs to same hierarchy level.
- So here, 3rd and 4th term in hierarchy array is always -1.

### Contours Hierarchy is:
```sh
    array([[[ 1, -1, -1, -1],
            [ 2,  0, -1, -1],
            [ 3,  1, -1, -1],
            [ 4,  2, -1, -1],
            [ 5,  3, -1, -1],
            [ 6,  4, -1, -1],
            [ 7,  5, -1, -1],
            [-1,  6, -1, -1]]], dtype=int32)
```
## Output of RETR_LIST:
![img](https://i.imgur.com/ByAvAx1.png)

## 2. RETR_EXTERNAL
- It returns only extreme outer flags.
- All child contours are left behind.

### Contours Hierarchy is:
```sh
    array([[[ 1, -1, -1, -1],
            [ 2,  0, -1, -1],
            [-1,  1, -1, -1]]], dtype=int32)
```
## Output of RETR_EXTERNAL:
![img](https://i.imgur.com/GsOWDzu.png)

## 3. RETR_CCOMP
- This flag retrieves all the contours and arranges them to a 2-level hierarchy. ie external contours of the object (ie its boundary) are placed in hierarchy-1.
- The contours of holes inside object (if any) is placed in hierarchy-2.
- If any object inside it, its contour is placed again in hierarchy-1 only. And its hole in hierarchy-2 and so on.

### Contours Hierarchy is:
```sh
    array([[[ 1, -1, -1, -1],
            [ 2,  0, -1, -1],
            [ 4,  1,  3, -1],
            [-1, -1, -1,  2],
            [ 6,  2,  5, -1],
            [-1, -1, -1,  4],
            [ 7,  4, -1, -1],
            [-1,  6, -1, -1]]], dtype=int32)
```
## Output of RETR_CCOMP:
![img](https://i.imgur.com/ASA9fea.png)

## 4. RETR_TREE
- It retrieves all the contours and creates a full family hierarchy list.

### Contours Hierarchy is:
```sh
    array([[[ 6, -1,  1, -1],
            [-1, -1,  2,  0],
            [-1, -1,  3,  1],
            [-1, -1,  4,  2],
            [ 5, -1, -1,  3],
            [-1,  4, -1,  3],
            [ 7,  0, -1, -1],
            [-1,  6, -1, -1]]], dtype=int32)
```
## Output of RETR_TREE:
![img](https://i.imgur.com/HD1Q5CU.png)

# Author
## [Akhil Bhalerao](https://github.com/iamakkkhil)

gha_language: Jupyter Notebook


text:
# Adafruit IO
---
The Adafruit cloud, Adafruit IO, is a cloud service primarily aimed at the maker market. While Adafruit IO is more limited than the major players in cloud services, it is very easy to use and there's a free option making this a great way to test IoT proofs of concept and prototypes.

We'll need create a few things for our code. We'll need an Adafruit Certificate, a dashboardID, a username, a password key, and a feed to subscribe to.

First add an Adafruit Certificate to our resources and then add it to line of code below.

![Adafruit IO Add Certificate](images/adaIO-add-cert.jpg)

```cs
var caCertSource = Resources.GetBytes(Resources.BinaryResources.DigiCertGlobalRootG2);
```
Next, we'll create a 'Dashboard', from the Dashboards page. Click on 'Create a New Dashboard' found inside the 'Actions' dropdown.

![Adafruit create Dashboard](images/adaIO-create-dashboard.jpg)

Create a meaningful name for our Dashboard. This will be the 'dashboardID' inside our code sample.

![Adafruit name Dashboard](images/adaIO-name-dashboard.jpg)

Click on our newly created 'Dashboard'

![Adafruit select Dashboard](images/adaIO-select-dashboard.jpg)

This opens the Dashboard canvas for our project. This is where we will add blocks to control our IoT device. Click on '+' to create a new block.

![Adafruit create Block](images/adaIO-create-block.jpg)

Let's add our first block to the canvas. There are many kinds of blocks you can add, for this we'll first add a 'Toggle' block. Click on the 'Toggle' block.

![Adafruit select Toggle](images/adaIO-select-toggle.jpg)

We need to create a 'feed' name to attach to our newly created block. Enter a name for the feed and click 'Create'. In our example we'll call this block's feed 'ToggleSwitch'

![Adafruit name feed](images/adaIO-name-feed.jpg)

Check the box of the newly created feed and click 'Next Step'

![Adafruit name feed](images/adaIO-next-step.jpg)

Here we can set the Text we want to use that appears on the button and the value the button will send when used. Let's change the Button value to 1 for on and 0 for off. Then click 'Create block'

![Adafruit block settings](images/adaIO-block-settings.jpg)

The new Toogle we created now appears in the Dashboard canvas, the blocks can be placed anywhere we like on the Dashboard. But let's add another block first.

![Adafruit create another Blcok](images/adaIO-add-newblock.jpg)

Let's add a 'Gauge' block to our canvas next.

![Adafruit create another Blcok](images/adaIO-add-gauge.jpg)

Like we did the ToggleSwitch feed, we need to create a feed for the Gauge. We'll just call the feed 'Gauge', click on the 'Create', select the 'Gauge' and click 'Next step'

![Adafruit name gauge feed](images/adaIO-name-gaugefeed.jpg)

There are several setting we can adjust but for this tutorial we'll just us the default and click on 'Create block'

![Adafruit name gauge feed](images/adaIO-create-gaugeblock.jpg)

We can see that the gauge has been added to our Dashboard Canvas. The final element we need for our code is an 'Adafruit IO Key'. Click on it located in the top menu.

![Adafruit select key](images/adaIO-select-key.jpg)

Copy the generated key...

![Adafruit generate key](images/adaIO-generate-key.jpg)

...and paste in our code as shown in the example below.

```cs
var key = "aio_XXJy54zT7H0X89PMZhUwlsfA7";
```
We now have all the elements we need to complete the code in our sample. Here are the values we created and need to add.

```cs
var dashboardId = "SITCore";
var username = "Your Username";
var key = "aio_XXJy54zT7H0X89PMZhUwlsfA7";
var feed = "your username/feeds/ToggleSwitch";
```
Deploy your program to your SITCore IoT device, once launched the gauge on our Dashboard will start at 50 and increment by 5 every 2 seconds. Clicking on the 'Toggle Switch' will send the value to our device, which can be seen in Visual Studio's output window.

![Adafruit running dashboard](images/adaIO-complete-dashboard.jpg)

![Adafruit running dashboard](images/adaIO-message-vs.jpg)

---

## Using MQTT

```cs
var caCertSource = Resources.GetBytes(Resources.BinaryResources.DigiCertGlobalRootG2);
X509Certificate CaCert = new X509Certificate(caCertSource);

var mqttHost = "io.adafruit.com";
var mqttPort = 8883; //Default SSL port is 8883, default insecure port is 1883.
var dashboardId = "Your Dashboard";
var username = "Your Username";
var key = "Your Adafruit IO Key";
var feed = "Feed you wish to subscribe to";

try {
    var clientSetting = new MqttClientSetting {
        BrokerName = mqttHost,
        BrokerPort = mqttPort,
        ClientCertificate = null,
        CaCertificate = CaCert,
        SslProtocol = System.Security.Authentication.SslProtocols.Tls12,
    };

    var client = new Mqtt(clientSetting);

    var connectSetting = new MqttConnectionSetting {
        ClientId = dashboardId,
        UserName = username,
        Password = key
    };

    // Connect to host
    var returnCode = client.Connect(connectSetting);

    if(returnCode == ConnectReturnCode.ConnectionAccepted)
        Debug.WriteLine("Connected to Adafruit IO");

    var packetId = 1;

    // Subscribe to a feed
    client.Subscribe(new string[] {feed}, new QoSLevel[] { QoSLevel.ExactlyOnce },
        (ushort)packetId++);

    // Publish to a feed
    client.PublishReceivedChanged += Client_PublishReceivedChanged;
    var dx = 5;
    var x = 50;
    while (true) {
        x += dx;
        if (x >= 100 || x <= 0)
            dx *= -1;
            // Publish a topic
            client.Publish("your username/feeds/gauge", Encoding.UTF8.GetBytes(" " + x),
            QoSLevel.MostOnce, false, (ushort)packetId); //Sets gauge
            Thread.Sleep(2000);
    }
}

catch (Exception e) {

}
Thread.Sleep(Timeout.Infinite);
}

private static void Client_PublishReceivedChanged(object sender, string topic, byte[] data, bool duplicate, QoSLevel qosLevel, bool retain) {
    if (data[0] == '1') { //Toggle is set to '1'
        Debug.WriteLine("ToggleSwitch set to 1");
    }
    if (data[0] == '0') {  //Toggle is set to '0'
        Debug.WriteLine("ToggleSwitch set to 0");
    }
}

```

## Using HTML

Your IoT device can communicate with Adafruit IO using simple HTTP GET and POST commands. However, to respond to input on your Adafruit IO dashboard you must repeatedly execute HTTP GET requests to poll the input. If you would rather use event driven input from Adafruit IO, MQTT is a better choice than HTML.

The following code uses an HTTP POST request to send a value to an Adafruit IO feed named "Gauge" which is represented by a gauge on an Adafruit IO dashboard. It uses a secure connection, so you must have the Adafruit certificate loaded as a [resource](resources.md). There must be a working Internet connection for this code to work.

```cs
var url = "http://io.adafruit.com/api/feeds/temperature/data.json";

var postData = "{\"value\":\"20\"}"; //Sending a value of 20.

var byteArray = System.Text.Encoding.UTF8.GetBytes(postData);

var cert = Resource.GetBytes(Resource.BinaryResources.DigiCertGlobalRootG2);

certx509 = new X509Certificate[] { new X509Certificate(cert) };

int read = 0, total = 0;
byte[] result = new byte[512];

try {
    using (var postRequest = HttpWebRequest.Create(url) as HttpWebRequest) {
        postRequest.KeepAlive = false;
        postRequest.HttpsAuthentCerts = certx509;
        postRequest.ReadWriteTimeout = 2000;
        postRequest.Headers.Add("x-aio-key: your_adafruit_io_key_goes_here");
        postRequest.ContentType = "application/json";
        postRequest.Method = "POST";
        postRequest.ContentLength = byteArray.Length;

        System.IO.Stream dataStream = postRequest.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        using (var res = postRequest.GetResponse() as HttpWebResponse) {
            using (var stream = res.GetResponseStream()) {
                do {
                    read = stream.Read(result, 0, result.Length);
                    total += read;

                    System.Diagnostics.Debug.WriteLine("read : " + read);
                    System.Diagnostics.Debug.WriteLine("total : " + total);

                    String page = "";

                    page = new String(System.Text.Encoding.UTF8.GetChars
                        (result, 0, read));

                    System.Diagnostics.Debug.WriteLine("Response : " + page);
                }

                while (read != 0);
            }
        }
    }
}
catch {

}
```

You can use an HTTP GET request to read the status of an Adafruit IO feed. The following code reads that status of a toggle block called "Digital." You will need the rename the toggle's `Button On Text` to "1" and the `Button Off Text` to "0" on the Adafruit IO dashboard. There must be a working Internet connection for this code to work.

```cs
url = "https://io.adafruit.com/api/v2/adafruit_io_username/
    feeds/toggleswitch/data?include=value&limit=1";

var cert = Resource.GetBytes(Resource.BinaryResources.DigiCertGlobalRootG2);

certx509 = new X509Certificate[] { new X509Certificate(cert) };

using (var getRequest = HttpWebRequest.Create(url) as HttpWebRequest) {
    getRequest.KeepAlive = false;
    getRequest.HttpsAuthentCerts = certx509;
    getRequest.ReadWriteTimeout = 2000;
    getRequest.Headers.Add("x-aio-key: your_adafruit_io_key_goes_here");
    getRequest.Method = "GET";

    using (var response = getRequest.GetResponse() as HttpWebResponse){
        using (var stream = response.GetResponseStream()) {
            do {
                read = stream.Read(result, 0, result.Length);
                total += read;

                System.Diagnostics.Debug.WriteLine("read : " + read);
                System.Diagnostics.Debug.WriteLine("total : " + total);

                String page = "";

                page = new String(System.Text.Encoding.UTF8.GetChars
                    (result, 0, read));

                System.Diagnostics.Debug.WriteLine("Response : " + page);
            }
            while (read != 0);
        }
    }
}
```

repository: ITSPaul/Documentation

repo_name: ITSPaul/Documentation


text:
Laravel Deployment
==========================

Overview
--------

While using git makes it easy to pull any revised code into a new environment, there are some manual steps that need to be done to facilitate this.  These steps could be automated, but they're simple enough.

Steps
-----

1. `git stash` - stash any *local changes* like composer updates that aren't stored in the repository
2. `git pull` - pull the fresh data from the upstream repository
3. If necessary, stop services, such as MySQL, Apache, Supervisor, etc. Composer is evidently a memory hog. It will become apparent if it is necessary if the `composer update` fails with an out of memory error
4. `composer update` - this is only necessary if any new composer dependencies were added to `composer.json`
5. Restart any services you stopped previously.
6. `php artisan migrate` - Run any new migrations. Again, only necessary if there were any new migrations in this deployment.
7. Check permissions.  Everything should be read-write by www-data group and `apps/storage/*` should be owned by www-data:www-data.  From your project root, run
	`chown -R :www-data * `
	`chown -R wwww-data:www-data /apps/storage`

Additional Steps for a fresh clone from a repository
==============================================

1. Configure your `app/config/<environment>` directory with any environment specific configuration settings, for instance the debug flag or to use a local sqlite databse.
2. Create a .env.<environment>.php file in the project root for any configuration settings set by PHP super-global variables. You can find these by `grep ENV app/config/*.php`
3. Configure your environment in the Detect The Application Environment section of `bootstrap.start.php`
4. Run any migrations using `php artisan migrate` If you are using a MySQL database, you must create the database first. Sqlite will automagically create the database file.

repository: beauraines/mtf

repo_name: beauraines/mtf


text:
---
title: Wish List
date: '2005-06-09 13:29:12'
tags:
- camera
- canon
- eos-20d
- general
- new-zealand
- photography
- roadtrips
- sigma-lenses
- skiing
- wishlist
---

Well, I'm getting my camera "wishlist" together atm... and it goes something like this:

Canon EOS 20D

Sigma 80-400mm f/4.5-5.6 EX OS APO

Sigma 24-70mm F2.8 EX DG MACRO

and on top of that a ski trip to NZ...

license: Unlicense

gha_language: CoffeeScript

gha_license_id: Unlicense


text:
# gitlab-ci-android
This Docker image contains the Android SDK and most common packages necessary for building Android apps in a CI tool like GitLab CI. Make sure your CI environment's caching works as expected, this greatly improves the build time, especially if you use multiple build jobs.

A `.gitlab-ci.yml` with caching of your project's dependencies would look like this:

```
image: dyangalih/gitlab-ci-android:latest

stages:
- check
- build
- deploy

before_script:
  - export GRADLE_USER_HOME=/cache/.gradle

cache:
  key: ${CI_PROJECT_ID}
  paths:
  - .gradle/

#job untuk checking
check:
  stage: check
  only:
        - develop
  script:
      - ./gradlew assembleDebug

#job untuk build
build:
  stage: build
  only:
      - develop
  script:
    - ./gradlew --stacktrace clean assembleRelease crashlyticsUploadDistributionQaRelease
  artifacts:
    paths:
    - app/build/outputs/apk

#job untuk deploy
deploy:
  stage: deploy
  only:
      - master
  script:
    - ./gradlew --stacktrace clean publishApkPlayRelease
  artifacts:
    paths:
    - app/build/outputs/apk
```

repository: DyanGalih/gitlab-ci-android

repo_name: DyanGalih/gitlab-ci-android


text:
# Connecting EL with T using DBT \(part 2/2\)

## Overview

This tutorial will describe how to integrate SQL based transformations with Airbyte syncs using specialized transformation tool: DBT.

This tutorial is the second part of the previous tutorial [Connecting EL with T using SQL](connecting-el-with-t-using-sql.md).

## Run Transformations with DBT

The tool in charge of transformation behind the scenes is actually called [DBT](https://blog.getdbt.com/what--exactly--is-dbt-/) \(Data Build Tool\).

Before generating the SQL files as we've seen previously, Airbyte is setting up internally a Docker image where DBT is installed, and a DBT project is created as described in their [documentation](https://docs.getdbt.com/docs/building-a-dbt-project/projects). It is run afterward, thanks to [DBT CLI](https://docs.getdbt.com/dbt-cli/cli-overview).

In the future, we will work on improving this DBT integration further... For example, it would probably be easier to customize and import your own DBT project within the Airbyte pipeline or connect with the [DBT Cloud](https://docs.getdbt.com/docs/dbt-cloud/cloud-overview).

However, for now, let's see how to interact with the DBT tool.

Since the whole DBT project is properly configured, it is possible to invoke the CLI from within the docker image to trigger transformation processing:

```bash
#!/usr/bin/env bash
docker run --rm -i -v airbyte_workspace:/data -w /data/$NORMALIZE_WORKSPACE/normalize --network host --entrypoint /usr/local/bin/dbt airbyte/normalization debug --profiles-dir=. --project-dir=.
docker run --rm -i -v airbyte_workspace:/data -w /data/$NORMALIZE_WORKSPACE/normalize --network host --entrypoint /usr/local/bin/dbt airbyte/normalization run --profiles-dir=. --project-dir=.
```

Example Output:

```text
Running with dbt=0.18.1
dbt version: 0.18.1
python version: 3.7.9
python path: /usr/local/bin/python
os info: Linux-4.19.121-linuxkit-x86_64-with-debian-10.6
Using profiles.yml file at ./profiles.yml
Using dbt_project.yml file at /data/5/0/normalize/dbt_project.yml

Configuration:
  profiles.yml file [OK found and valid]
  dbt_project.yml file [OK found and valid]

Required dependencies:
 - git [OK found]

Connection:
  host: localhost
  port: 3000
  user: postgres
  database: postgres
  schema: quarantine
  search_path: None
  keepalives_idle: 0
  sslmode: None
  Connection test: OK connection ok

Running with dbt=0.18.1
Found 1 model, 0 tests, 0 snapshots, 0 analyses, 302 macros, 0 operations, 0 seed files, 1 source

14:37:10 | Concurrency: 32 threads (target='prod')
14:37:10 |
14:37:10 | 1 of 1 START table model quarantine.covid_epidemiology....................................................... [RUN]
14:37:11 | 1 of 1 OK created table model quarantine.covid_epidemiology.................................................. [SELECT 17911 in 0.33s]
14:37:11 |
14:37:11 | Finished running 1 table model in 0.50s.

Completed successfully

Done. PASS=1 WARN=0 ERROR=0 SKIP=0 TOTAL=1
```

As seen in the tutorial on [exploring workspace folder](exploring-workspace-folder.md), it is possible to browse the `normalize` folder and examine further logs if an error occurs.

In particular, we can also take a look at the DBT models generated by Airbyte and export them to the local host filesystem:

```bash
#!/usr/bin/env bash

TUTORIAL_DIR="$(pwd)/tutorial/"
rm -rf $TUTORIAL_DIR/normalization-files
mkdir -p $TUTORIAL_DIR/normalization-files

docker cp airbyte-server:/tmp/workspace/$NORMALIZE_WORKSPACE/normalize/ $TUTORIAL_DIR/normalization-files

NORMALIZE_DIR=$TUTORIAL_DIR/normalization-files/normalize
cd $NORMALIZE_DIR
cat $NORMALIZE_DIR/models/generated/*.sql
```

Example Output:

```text
with
covid_epidemiology_node as (
  select
    _airbyte_emitted_at,
    {{ dbt_utils.current_timestamp_in_utc()  }} as _airbyte_normalized_at,
    cast({{ json_extract_scalar('_airbyte_data', ['date'])  }} as {{ dbt_utils.type_string()  }}) as date,
    cast({{ json_extract_scalar('_airbyte_data', ['new_recovered'])  }} as {{ dbt_utils.type_float()  }}) as new_recovered,
    cast({{ json_extract_scalar('_airbyte_data', ['new_tested'])  }} as {{ dbt_utils.type_float()  }}) as new_tested,
    cast({{ json_extract_scalar('_airbyte_data', ['total_deceased'])  }} as {{ dbt_utils.type_float()  }}) as total_deceased,
    cast({{ json_extract_scalar('_airbyte_data', ['new_deceased'])  }} as {{ dbt_utils.type_float()  }}) as new_deceased,
    cast({{ json_extract_scalar('_airbyte_data', ['new_confirmed'])  }} as {{ dbt_utils.type_float()  }}) as new_confirmed,
    cast({{ json_extract_scalar('_airbyte_data', ['total_confirmed'])  }} as {{ dbt_utils.type_float()  }}) as total_confirmed,
    cast({{ json_extract_scalar('_airbyte_data', ['total_tested'])  }} as {{ dbt_utils.type_float()  }}) as total_tested,
    cast({{ json_extract_scalar('_airbyte_data', ['total_recovered'])  }} as {{ dbt_utils.type_float()  }}) as total_recovered,
    cast({{ json_extract_scalar('_airbyte_data', ['key'])  }} as {{ dbt_utils.type_string()  }}) as key
  from {{ source('quarantine', 'covid_epidemiology_raw')  }}
),
covid_epidemiology_with_id as (
  select
    *,
    {{ dbt_utils.surrogate_key([
        'date',
        'new_recovered',
        'new_tested',
        'total_deceased',
        'new_deceased',
        'new_confirmed',
        'total_confirmed',
        'total_tested',
        'total_recovered',
        'key'
    ])  }} as _airbyte_covid_epidemiology_hashid
    from covid_epidemiology_node
)
select * from covid_epidemiology_with_id
```

If you have [DBT installed](https://docs.getdbt.com/dbt-cli/installation/) on your machine, you can then view, edit, customize and run the dbt models in your project if you want to bypass the normalization steps generated by Airbyte!

```bash
#!/usr/bin/env bash

dbt deps --profiles-dir=$NORMALIZE_DIR --project-dir=$NORMALIZE_DIR
dbt run --profiles-dir=$NORMALIZE_DIR --project-dir=$NORMALIZE_DIR --full-refresh
```

Example Output:

```text
Running with dbt=0.18.1
Installing<EMAIL_ADDRESS>  Installed from revision 0.6.2

Running with dbt=0.18.1
Found 1 model, 0 tests, 0 snapshots, 0 analyses, 302 macros, 0 operations, 0 seed files, 1 source

15:37:54 | Concurrency: 32 threads (target='prod')
15:37:54 |
15:37:55 | 1 of 1 START table model quarantine.covid_epidemiology....................................................... [RUN]
15:37:55 | 1 of 1 OK created table model quarantine.covid_epidemiology.................................................. [SELECT 17911 in 0.30s]
15:37:55 |
15:37:55 | Finished running 1 table model in 0.51s.

Completed successfully

Done. PASS=1 WARN=0 ERROR=0 SKIP=0 TOTAL=1
```

## Going further

For the moment, it is not possible to make changes to the generated DBT models and commit them back so Airbyte can use it in its next sync of a certain source/destination combination. But, we'll work on such integration in the near future!

Our DBT models are currently composed of only one model per final table to replicate, we would probably refine this and grow the transformation steps further, adding UI elements to configure what should be included or not in the normalization step.

However, if you have ideas on what to do with DBT from this point on, we would be glad to hear your feedbacks and ideas. Thank you!

repository: MinjaMiladinovic/airbyte

gha_language: Java

repo_name: MinjaMiladinovic/airbyte


text:
# Dokku [![Build Status](https://circleci.com/gh/progrium/dokku/tree/master.svg?style=svg&circle-token=eec5b442dda53a4d229911dd97d4214853acc262 "Build Status")](https://circleci.com/gh/progrium/dokku/tree/master) [![Ubuntu Package](https://img.shields.io/badge/package-ubuntu-brightgreen.svg?style=flat-square "Ubuntu Package")](https://packagecloud.io/dokku/dokku)

Docker powered mini-Heroku. The smallest PaaS implementation you've ever seen. Sponsored by our friends at [Deis](http://deis.io/).

## Requirements

- A fresh VM running Ubuntu `14.04 x64`

## Installing

To install the latest stable release, you can run the following command as a user that has access to `sudo`:

    wget -qO- https://raw.github.com/progrium/dokku/v0.3.16/bootstrap.sh | sudo DOKKU_TAG=v0.3.16 bash

### Upgrading

[View the docs for upgrading](http://progrium.viewdocs.io/dokku/upgrading) from an older version of Dokku.

## Documentation

Full documentation - including advanced installation docs - are available online at [docs](http://progrium.viewdocs.io/dokku/index)

## Support

You can use [Github Issues](https://github.com/progrium/dokku/issues), check [Troubleshooting](http://progrium.viewdocs.io/dokku/troubleshooting) in the documentation, or join us on [freenode in #dokku](https://webchat.freenode.net/?channels=%23dokku)

## Sponsors

Dokku is currently sponsored by the enterprise grade, multi-host PaaS project [Deis](http://deis.io/).

## License

MIT

repository: broadly/dokku

gha_language: Shell

repo_name: broadly/dokku