text:
## Graceful Shutdown and Cleanup

The code in Listing 20-20 is responding to requests asynchronously through the
use of a thread pool, as we intended. We get some warnings about the `workers`,
`id`, and `thread` fields that we’re not using in a direct way that reminds us
we’re not cleaning up anything. When we use the less elegant ctrl-c method to halt the main thread, all other
threads are stopped immediately as well, even if they’re in the middle of
serving a request.

Now we’ll implement the `Drop` trait to call `join` on each of the threads in
the pool so they can finish the requests they’re working on before closing.
Then we’ll implement a way to tell the threads they should stop accepting new
requests and shut down. To see this code in action, we’ll modify our server to
accept only two requests before gracefully shutting down its thread pool.

### Implementing the `Drop` Trait on `ThreadPool`

Let’s start with implementing `Drop` on our thread pool. When the pool is
dropped, our threads should all join to make sure they finish their work.
Listing 20-22 shows a first attempt at a `Drop` implementation; this code won’t
quite work yet.

Filename: src/lib.rs

```rust,ignore,does_not_compile
{{#rustdoc_include ../listings/ch20-web-server/listing-20-22/src/lib.rs:here}}
```

Listing 20-22: Joining each thread when the thread pool
goes out of scope

First, we loop through each of the thread pool `workers`. We use `&mut` for
this because `self` is a mutable reference, and we also need to be able to
mutate `worker`. For each worker, we print a message saying that this
particular worker is shutting down, and then we call `join` on that worker’s
thread. If the call to `join` fails, we use `unwrap` to make Rust panic and go
into an ungraceful shutdown.

Here is the error we get when we compile this code:

```console
{{#include ../listings/ch20-web-server/listing-20-22/output.txt}}
```

The error tells us we can’t call `join` because we only have a mutable borrow
of each `worker` and `join` takes ownership of its argument. To solve this
issue, we need to move the thread out of the `Worker` instance that owns
`thread` so `join` can consume the thread. We did this in Listing 17-15: if
`Worker` holds an `Option<thread::JoinHandle<()>>` instead, we can call the
`take` method on the `Option` to move the value out of the `Some` variant and
leave a `None` variant in its place. In other words, a `Worker` that is running
will have a `Some` variant in `thread`, and when we want to clean up a
`Worker`, we’ll replace `Some` with `None` so the `Worker` doesn’t have a
thread to run.

So we know we want to update the definition of `Worker` like this:

Filename: src/lib.rs

```rust,ignore,does_not_compile
{{#rustdoc_include ../listings/ch20-web-server/no-listing-04-update-worker-definition/src/lib.rs:here}}
```

Now let’s lean on the compiler to find the other places that need to change.
Checking this code, we get two errors:

```console
{{#include ../listings/ch20-web-server/no-listing-04-update-worker-definition/output.txt}}
```

Let’s address the second error, which points to the code at the end of
`Worker::new`; we need to wrap the `thread` value in `Some` when we create a
new `Worker`. Make the following changes to fix this error:

Filename: src/lib.rs

```rust,ignore
{{#rustdoc_include ../listings/ch20-web-server/no-listing-05-fix-worker-new/src/lib.rs:here}}
```

The first error is in our `Drop` implementation. We mentioned earlier that we
intended to call `take` on the `Option` value to move `thread` out of `worker`.
The following changes will do so:

Filename: src/lib.rs

```rust,ignore
{{#rustdoc_include ../listings/ch20-web-server/no-listing-06-fix-threadpool-drop/src/lib.rs:here}}
```

As discussed in Chapter 17, the `take` method on `Option` takes the `Some`
variant out and leaves `None` in its place. We’re using `if let` to destructure
the `Some` and get the thread; then we call `join` on the thread. If a worker’s
thread is already `None`, we know that worker has already had its thread
cleaned up, so nothing happens in that case.

### Signaling to the Threads to Stop Listening for Jobs

With all the changes we’ve made, our code compiles without any warnings. But
the bad news is this code doesn’t function the way we want it to yet. The key
is the logic in the closures run by the threads of the `Worker` instances: at
the moment, we call `join`, but that won’t shut down the threads because they
`loop` forever looking for jobs. If we try to drop our `ThreadPool` with our
current implementation of `drop`, the main thread will block forever waiting
for the first thread to finish.

To fix this problem, we’ll modify the threads so they listen for either a `Job`
to run or a signal that they should stop listening and exit the infinite loop.
Instead of `Job` instances, our channel will send one of these two enum
variants.

Filename: src/lib.rs

```rust,noplayground
{{#rustdoc_include ../listings/ch20-web-server/no-listing-07-define-message-enum/src/lib.rs:here}}
```

This `Message` enum will either be a `NewJob` variant that holds the `Job` the
thread should run, or it will be a `Terminate` variant that will cause the
thread to exit its loop and stop.

We need to adjust the channel to use values of type `Message` rather than type
`Job`, as shown in Listing 20-23.

Filename: src/lib.rs

```rust,ignore
{{#rustdoc_include ../listings/ch20-web-server/listing-20-23/src/lib.rs:here}}
```

Listing 20-23: Sending and receiving `Message` values and
exiting the loop if a `Worker` receives `Message::Terminate`

To incorporate the `Message` enum, we need to change `Job` to `Message` in two
places: the definition of `ThreadPool` and the signature of `Worker::new`. The
`execute` method of `ThreadPool` needs to send jobs wrapped in the
`Message::NewJob` variant. Then, in `Worker::new` where a `Message` is received
from the channel, the job will be processed if the `NewJob` variant is
received, and the thread will break out of the loop if the `Terminate` variant
is received.

With these changes, the code will compile and continue to function in the same
way as it did after Listing 20-20. But we’ll get a warning because we aren’t
creating any messages of the `Terminate` variety. Let’s fix this warning by
changing our `Drop` implementation to look like Listing 20-24.

Filename: src/lib.rs

```rust,ignore
{{#rustdoc_include ../listings/ch20-web-server/listing-20-24/src/lib.rs:here}}
```

Listing 20-24: Sending `Message::Terminate` to the
workers before calling `join` on each worker thread

We’re now iterating over the workers twice: once to send one `Terminate`
message for each worker and once to call `join` on each worker’s thread. If we
tried to send a message and `join` immediately in the same loop, we couldn’t
guarantee that the worker in the current iteration would be the one to get the
message from the channel.

To better understand why we need two separate loops, imagine a scenario with
two workers. If we used a single loop to iterate through each worker, on the
first iteration a terminate message would be sent down the channel and `join`
called on the first worker’s thread. If that first worker was busy processing a
request at that moment, the second worker would pick up the terminate message
from the channel and shut down. We would be left waiting on the first worker to
shut down, but it never would because the second thread picked up the terminate
message. Deadlock!

To prevent this scenario, we first put all of our `Terminate` messages on the
channel in one loop; then we join on all the threads in another loop. Each
worker will stop receiving requests on the channel once it gets a terminate
message. So, we can be sure that if we send the same number of terminate
messages as there are workers, each worker will receive a terminate message
before `join` is called on its thread.

To see this code in action, let’s modify `main` to accept only two requests
before gracefully shutting down the server, as shown in Listing 20-25.

Filename: src/bin/main.rs

```rust,ignore
{{#rustdoc_include ../listings/ch20-web-server/listing-20-25/src/bin/main.rs:here}}
```

Listing 20-25: Shut down the server after serving two
requests by exiting the loop

You wouldn’t want a real-world web server to shut down after serving only two
requests. This code just demonstrates that the graceful shutdown and cleanup is
in working order.

The `take` method is defined in the `Iterator` trait and limits the iteration
to the first two items at most. The `ThreadPool` will go out of scope at the
end of `main`, and the `drop` implementation will run.

Start the server with `cargo run`, and make three requests. The third request
should error, and in your terminal you should see output similar to this:

```console
$ cargo run
   Compiling hello v0.1.0 (file:///projects/hello)
    Finished dev [unoptimized + debuginfo] target(s) in 1.0s
     Running `target/debug/main`
Worker 0 got a job; executing.
Worker 3 got a job; executing.
Shutting down.
Sending terminate message to all workers.
Shutting down all workers.
Shutting down worker 0
Worker 1 was told to terminate.
Worker 2 was told to terminate.
Worker 0 was told to terminate.
Worker 3 was told to terminate.
Shutting down worker 1
Shutting down worker 2
Shutting down worker 3
```

You might see a different ordering of workers and messages printed. We can see
how this code works from the messages: workers 0 and 3 got the first two
requests, and then on the third request, the server stopped accepting
connections. When the `ThreadPool` goes out of scope at the end of `main`, its
`Drop` implementation kicks in, and the pool tells all workers to terminate.
The workers each print a message when they see the terminate message, and then
the thread pool calls `join` to shut down each worker thread.

Notice one interesting aspect of this particular execution: the `ThreadPool`
sent the terminate messages down the channel, and before any worker received
the messages, we tried to join worker 0. Worker 0 had not yet received the
terminate message, so the main thread blocked waiting for worker 0 to finish.
In the meantime, each of the workers received the termination messages. When
worker 0 finished, the main thread waited for the rest of the workers to
finish. At that point, they had all received the termination message and were
able to shut down.

Congrats! We’ve now completed our project; we have a basic web server that uses
a thread pool to respond asynchronously. We’re able to perform a graceful
shutdown of the server, which cleans up all the threads in the pool.

Here’s the full code for reference:

Filename: src/bin/main.rs

```rust,ignore
{{#rustdoc_include ../listings/ch20-web-server/no-listing-08-final-code/src/bin/main.rs}}
```

Filename: src/lib.rs

```rust,noplayground
{{#rustdoc_include ../listings/ch20-web-server/no-listing-08-final-code/src/lib.rs}}
```

We could do more here! If you want to continue enhancing this project, here are
some ideas:

* Add more documentation to `ThreadPool` and its public methods.
* Add tests of the library’s functionality.
* Change calls to `unwrap` to more robust error handling.
* Use `ThreadPool` to perform some task other than serving web requests.
* Find a thread pool crate on [crates.io](https://crates.io/) and implement a
  similar web server using the crate instead. Then compare its API and
  robustness to the thread pool we implemented.

## Summary

Well done! You’ve made it to the end of the book! We want to thank you for
joining us on this tour of Rust. You’re now ready to implement your own Rust
projects and help with other peoples’ projects. Keep in mind that there is a
welcoming community of other Rustaceans who would love to help you with any
challenges you encounter on your Rust journey.

repository: rust-lang-cn/book-cn

gha_language: Rust

repo_name: rust-lang-cn/book-cn


text:
Hot Chai (tea) with Java coffee (ch.vorburger.hotea)
====

__*Please also check out the follow-up projects [ch.vorburger.osgi.gradle](https://github.com/vorburger/ch.vorburger.osgi.gradle) and [ch.vorburger.minecraft.osgi](https://github.com/vorburger/ch.vorburger.minecraft.osgi).*__

The Minecraft specific part is in the [minecraft/ module](ch.vorburger.hotea.minecraft). What follows here is a general library (not Minecraft related, but the Minecraft module uses this).

Hotea is a "kept it simple and stupid" (KISS) Java Mod-ules/Plug-In mini framework with HOT Class reloading to "support dynamic script like source code" (through isolated ClassLoader/s).  This may be of interest and useful to you to build things ranging from e.g. plugins for game engines to perhaps some sort of runtime changeable coded out "business rule" stuff.

Watch this https://www.youtube.com/watch?v=oMhY075hx9k and this https://www.youtube.com/watch?v=mibW8MhenGc vidoe, or see e.g. the [HotSwingExampleMain](ch.vorburger.hotea/src/test/java/ch/vorburger/hotea/examples/swing/HotSwingExampleMain.java) or [the Tests](ch.vorburger.hotea/src/test/java/ch/vorburger/hotea/tests/), for illustrations regarding what this is really all about.

Caveat emptor: This is intended for and best works with simple plugin-like scenarios, where the classpath of each such plugin does not overlap nor need to share instances among different plugins. In more interesting use cases, by experience, Very Weired Things (VWT) may happen if you don't fully understand what you are actually doing when several class loaders are involved in Java. You have been warned.

Use of Java 8 is recommended to avoid PermGen memory issues due to Class reloading.

Features: (what it does do)
* Load Java byte code for additional *.classes from directory/-ies and/or JARs, through a child ClassLoader
* Hot reload such extensions/modules/plugins/bundles whenever any files in the watched classpath directory are updated
* Notify your code whenever it hot reloaded, so that you can do what you need to do in your code (say cleanly shut down previous instances of your classes, and re-instantiate objects using your new class definitions)
* _TODO Build *.class files from *.java sources files, and auto. rebuild on any changes (ch.vorburger.hotea.compilewatchedfiles)_
* No need to follow a particular "Plugin API" at all (of Hotea, there is none) - you can hot (re)load any class implementing any of your own "API" interface

Non-Features, what it does *NOT* do, not today and not planned:
* Hot-reload classes on your (already loaded) "main" primary classpath - no JVM Agent
* Dependencies between modules/plugins/bundles (perhaps you want to look at OSGi?)
* Versioning of modules/plugins/bundles (perhaps you want to look at OSGi?)
* Repositories, remote provisioning, etc.
* Remote API export etc.

Hotea is thus somewhat similar yet quite different from:

Class A: Approaches which hot-reload classes on your (already loaded) "main" primary classpath typically through a custom JVM Agent (with more or less limitations):

* http://hotswapagent.org
* http://dcevm.github.io
* https://github.com/spring-projects/spring-loaded
* http://zeroturnaround.com/software/jrebel/
* https://code.google.com/p/jreloader/
* Standard JVM Hot Deploy in Debug mode

Class B: Other extensions/modules/plugins/bundles
* OSGi (eclipse.org/rt: eclipse.org/equinox, eclipse.org/virgo, eclipse.org/gemini; felix.apache.org & karaf.apache.org; bndtools.org BND Tools; Spring Dynamic Modulees DM)
* [JBoss Modules](https://github.com/jboss-modules/jboss-modules) (and [Doc](https://docs.jboss.org/author/display/MODULES/Home))
* [NucleusPowered/QuickStartModuleLoader](https://github.com/NucleusPowered/QuickStartModuleLoader)
* http://jpf.sourceforge.net
* https://code.google.com/p/jspf/ : No hot unload
* https://code.google.com/p/impala/

Class C: Approaches between A/B
* https://github.com/jmarranz/relproxy/ : Seems to be intended to (re)load one class, only, e.g. for a single Web View

Class D: Other related stuff
* http://commons.apache.org/proper/commons-jci
* http://docs.codehaus.org/display/JANINO/Home

Class E: Related articles
* http://tutorials.jenkov.com/java-reflection/dynamic-class-loading-reloading.html
* http://www.javaworld.com/article/2071777/design-patterns/add-dynamic-java-code-to-your-application.html
* https://blogs.oracle.com/sundararajan/entry/dynamic_source_code_in_java
* http://stackoverflow.com/questions/26291254/dynamically-recompile-and-reload-a-class

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# Matrix rain
Matrix Rain in React for you website.

### Development build
To build it locally, run

```
npm i
npm start
```

then open `http://localhost:3000/` in the browser.

###  Production build

```
npm i
npm run build
npm run serve
```

license: ISC

repository: shweta-codeprism/matrix-rain

repo_name: shweta-codeprism/matrix-rain


text:
# Tapis Security Kernel Database Schema Support

## Version 1.0.0

### New Features
1. Security Kernel database schema definition and Flyway-based migration utilities.

repository: tapis-project/tapis-java

branch_name: refs/heads/dev

gha_language: Java

repo_name: tapis-project/tapis-java


text:
# TutorialScrollingView

This is the tutorial code for my blog post on creating scrollable views using Xcode Storyboards.  You can read the blog post that goes with this code here:

https://robkerr.com/configuring-uiscrollview-in-a-storyboard-d579706b2591

license: MIT

repository: robkerr/TutorialScrollingView

repo_name: robkerr/TutorialScrollingView


text:
Adafruit Unified BNO055 Driver (AHRS/Orientation)  [![Build Status](https://github.com/adafruit/Adafruit_BNO055/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_BNO055/actions)[![Documentation](https://github.com/adafruit/ci-arduino/blob/master/assets/doxygen_badge.svg)](http://adafruit.github.io/Adafruit_BNO055/html/index.html)
================

This driver is for the Adafruit BNO055 Breakout, and is based on Adafruit's Unified Sensor Library (Adafruit_Sensor).

Tested and works great with the Adafruit Si4713 Breakout Board.
To work with the Arduino Zero, the BNO055's ADR pin must be high.
* http://www.adafruit.com/products/2472

## What is the Adafruit Unified Sensor Library? ##

The Adafruit Unified Sensor Library ([Adafruit_Sensor](https://github.com/adafruit/Adafruit_Sensor)) provides a common interface and data type for any supported sensor.  It defines some basic information about the sensor (sensor limits, etc.), and returns standard SI units of a specific type and scale for each supported sensor type.

It provides a simple abstraction layer between your application and the actual sensor HW, allowing you to drop in any comparable sensor with only one or two lines of code to change in your project (essentially the constructor since the functions to read sensor data and get information about the sensor are defined in the base Adafruit_Sensor class).

This is important and useful for two reasons:

1.) You can use the data right away because it's already converted to SI units that you understand and can compare, rather than meaningless values like 0..1023.

2.) Because SI units are standardised in the sensor library, you can also do quick sanity checks when working with new sensors, or drop in any comparable sensor if you need better sensitivity or if a lower cost unit becomes available, etc.

Light sensors will always report units in lux, gyroscopes will always report units in rad/s, etc. ... freeing you up to focus on the data, rather than digging through the datasheet to understand what the sensor's raw numbers really mean.

Adafruit invests time and resources providing this open source code.  Please support Adafruit and open-source hardware by purchasing products from Adafruit!

Kevin (KTOWN) Townsend Adafruit Industries.
MIT license, check license.txt for more information
All text above must be included in any redistribution

To install, use the Arduino Library Manager and search for "Adafruit BNO055" and install the library.

gha_license_id: MIT


text:
---
title: Update DOM Elements Outside Vue
date: "2019-08-02"
template: "post"
draft: false
slug: "/posts/update-dom-elements-outside-vue/"
category: "Vue"
tags:
  - "Vue"
  - "Javascript"
description: "Update content that lives outside Vue from within Vue. Working on a legacy PHP application that's, getting converted to an SPA using Vue, I encountered a need to interact with some sections of the application that reside outside of Vue."
---

### Challenge

Update content that lives outside Vue from within Vue.

### Scenario

Working on a legacy PHP application that's, getting converted to an SPA using Vue, I encountered a need to interact with some sections of the application that reside outside of Vue. In particular the page heading and icons are set by the PHP controllers. With a couple sections converted over to Vue, we're able to route requests between the new Vueified sections using Vue Router. This works great but leaves the page heading set to the previous section.

Eventually this section will likely be converted to Vue as well but for now that's out of scope. A quick fix would be to just not use router links, but I don't want to give up the benefits of routing between these sections using Vue Router.

### Existing Options

Doing some DOM manipulation using some vanilla Javascript (getElementById) was the first option that came to mind but I wanted to see what some others have done in similar situations.

#### Portal-Vue

I found a package called Portal-Vue and gave it a shot. I came across this package from a post on [alligator.io](<https://alligator.io/vuejs/portal-vue/>).

I couldn't find my particular use-case (manipulate DOM outside Vue) in the Portal-Vue documentation but the article on alligator.io covered this.

1. Install portal-vue
   ```npm install portal-vue --save```

2. Enable plugin

   ```
   import PortalVue from 'portal-vue';
   Vue.use(PortalVue);
   ```

3. Create new Vue component

   ```
   <template>
     <div>
       <portal target-el="#target-element-id">
         <p>Contents for target element here</p>
       </portal>
     </div>
   </template>
   ```

4. Add component to the page

   ```
   <NewPortalComponent />
   ```

   This works fine, but after doing all this and thinking about what's actually happening, I can just interact with the DOM myself and avoid installing another package and adding it as a global Vue plugin.

### Solution

To keep this lightweight I decided to create a component specifically for my use-case.

#### Renderless Vue Component

Renderless as this doesn't need to render anything where the component is added. Unlike portal-vue, I'll just set the HTML for the target element directly in the script so the component won't need a template.

##### Requirements

- Find an element on the page and update the inner HTML
- HTML will be different on each page so content will need to be dynamic

##### Steps

1. Wrap target element in div with id

   ```html
   <div id="page-heading">
     <h1><i class="original-icon"> Original Page Heading</h1>
   </div>
   ```

2. Create renderless component and get target element

   ```vue
   <script>
     mounted() {
         let target = document.getElementById('page-heading');
     }
     render() {
         return null;
     }
   </script>
   ```

3. Set new content for element in mounted:

   ```javascript
   if (target) {
     target.innerHTML = '<h1><i class="new-icon"> New Header</h1>';
   }
   ```

4. Add new content as props to make this dynamic

   ```javascript
   props: {
     icon: {
       type: String,
       required: true
     },
     heading: {
       type: String,
       required: true
     }
   },
   ```

5. Update new content to use props

   ```javascript
   mounted() {
     let target = document.getElementById('page-heading');
     if (target) {
       target.innerHTML = `<h1><i class="{this.icon}"> {this.heading}</h1>`;
     }
   }
   ```

##### Finished component

```vue
/** ../components/UpdateHeading.vue */
<script>
  props: {
    icon: {
      type: String,
      required: true
    },
    heading: {
      type: String,
      required: true
    }
  },
  mounted() {
      let target = document.getElementById('page-heading');
      if (target) {
        target.innerHTML = `<h1><i class="{this.icon}"> {this.heading}</h1>`;
      }
  }
  render() {
      return null;
  }
</script>
```

#### Usage

To use the component: add the component to the page and pass in the desired icon and heading. When the component is mounted it will update the contents of the target element with your props.

```vue
<UpdateHeading
  icon="new-icon"
  heading="New Page Heading"
/>
```

#### Next Steps

The final component got refactored a bit more by moving the updating of innerHTML into a method that is called in mounted and then adding some watchers on the props which also call the new method (not needed for the use-case in the app but setting it up this way allowed the component to be interactive in Storybook using knobs).

This was a specific use-case for the application I was working on, but hopefully this gives some insight into a couple different approaches to tackling DOM manipulation outside of Vue from within Vue.

repository: alexmckinnon/alexmckinnon-website

gha_language: JavaScript

repo_name: alexmckinnon/alexmckinnon-website


text:
[![build status](https://github.com/asottile/dead/actions/workflows/main.yml/badge.svg)](https://github.com/asottile/dead/actions/workflows/main.yml)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/asottile/dead/main.svg)](https://results.pre-commit.ci/latest/github/asottile/dead/main)

dead
====

dead simple python dead code detection

## installation

```bash
pip install dead
```

## cli

Consult the help for the latest usage:

```console
$ dead --help
usage: dead [-h] [--files FILES] [--exclude EXCLUDE] [--tests TESTS]

optional arguments:
  -h, --help         show this help message and exit
  --files FILES      regex for file inclusion, default: ''
  --exclude EXCLUDE  regex for file exclusion, default '^$'
  --tests TESTS      regex to mark files as tests, default
                     '(^|/)(tests?|testing)/'
```

run the `dead` utility from the root of a git repository.

## as a pre-commit hook

See [pre-commit](https://github.com/pre-commit/pre-commit) for instructions

Sample `.pre-commit-config.yaml`:

```yaml
-   repo: https://github.com/asottile/dead
    rev: v1.5.2
    hooks:
    -   id: dead
```

### how it works

1. find all files in a repository using `git ls-files` and filtering:
    - only include files matched by the `--files` regex
    - exclude files matched by the `--exclude` regex
    - only include files identified as `python` by
      [`identify`](https://github.com/chriskuehl/identify)
    - classify test files by the `--tests` regex
1. ast parse each file
    - search for definitions and references
1. report things which do not have references

### false positives

I wrote this in ~15 minutes on an airplane, it's far from perfect but often
finds things.  Here's a few things it's not good at:

- functions which implement an interface are often marked as unused
- metaclass magic is often marked as unused (enums, model classes, etc.)

### suppressing `dead`

The `# dead: disable` comment will tell `dead` to ignore
any line which has reportedly dead code.

### is this project dead?

_maybe._

repository: asottile/dead

branch_name: refs/heads/main

gha_language: Python

repo_name: asottile/dead


text:
# Python and the LYNX API

*A simple Python implementation for requesting streaming Market Data from Trader Workstation or the LYNX Gateway*

## Requirements:

> - [API Software](https://api.lynx.academy/API_versions) Installed
>- TWS Running
> - Socket Connection enabled and configured: *Configure->API->Settings* *(Port - 7496 & Enable ActiveX and Socket Clients)*
> - Python 3.6 or higher
> - Set-up your environment to work with the API as described [here](/Python/SETUP.md)
>

At the bottom you will find the full example to request Market Data using the LYNX API, or download the .py file directly [here](/Python/request_market_data/request_market_data.py).

## Initial Setup

**EWrapper and EClient:**

```python
# Copyright (C) 2021 LYNX B.V. All rights reserved.

# Import ibapi deps
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import *

import threading
from datetime import datetime
from time import sleep

class App(EWrapper, EClient):
    def __init__(self, ipaddress, portid, clientid):
        EClient.__init__(self, self)
        self.data = [] #initialize variable to store data in

        self.connect(ipaddress, portid, clientid)
        app_thread = threading.Thread(target=self.run)  # run the socket in a thread
        app_thread.start()

```

The two most import source code files in the pythonclient folder are EClient and EWrapper. The EWrapper is necessary to receive and handle the information coming from TWS and the ECLient is used to send outgoing request/messages to TWS. In order to redirect the output from the EWrapper to a specific place a function from it needs to be overwritten in the script.

In a newly created App class, both the EClient and the EWrapper class are passed through into it and a thread is added.

*Note: consult the EWrapper/EClient source files if you are not sure which functions to use.*

---

## Receiving Real-Time, Streaming, Quotes from the LYNX API:

In order to start receiving data we need to perform five actions:

1. Initialize the App class and create a connection
2. Define the contract to request
3. Call the actual request
4. Overwrite the correct function from the EWrapper class
5. Disconnect the connection

**The App class:**

```python
# Init the TestApp(Wrapper, Client)
app = App("localhost", 7496, clientid = 0)
print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
                                              app.twsConnectionTime()))
```

**The contract definition:**

```python
# Define the contract
contract = Contract()
contract.symbol = "EUR"
contract.secType = "CASH"
contract.currency = "USD"
contract.exchange = "IDEALPRO"
```

**The Request**:

```python
# Here we are requesting tickdata for the EUR.USD Contract.
app.reqTickByTickData(4001, contract, "MidPoint", 0, False)
```

**Returning the Request:**

```python
# Here we print the Midpoint, Request ID and Time using a function from the EWrapper class
def tickByTickMidPoint(self, reqId: int, time: int, midPoint: float):
        print("Midpoint. ReqId:", reqId,
              "Time:", datetime.datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"),
              "MidPoint:", midPoint)
```

**Diconnect**
```python
# The connection can be disconnected after the data has been received
app.disconnect()
```
---

### The entire code:

```python
# Copyright (C) 2021 LYNX B.V. All rights reserved.

# Import ibapi deps
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import *

import threading
from datetime import datetime
from time import sleep

class App(EWrapper, EClient):
    def __init__(self, ipaddress, portid, clientid):
        EClient.__init__(self, self)

        self.connect(ipaddress, portid, clientid)
        app_thread = threading.Thread(target=self.run)  # run the socket in a thread
        app_thread.start()

    def tickByTickMidPoint(self, reqId: int, time: int, midPoint: float):
        """returns tick-by-tick data for tickType = "MidPoint" """

        print("Midpoint. ReqId:", reqId,
              "Time:", datetime.fromtimestamp(time).strftime("%Y%m%d %H:%M:%S"),
              "MidPoint:", midPoint)

def main():
    # Init the App(Wrapper, Client)
    app = App("localhost", 7497, clientid=0)
    print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
                                                  app.twsConnectionTime()))

    # Define the contract
    contract = Contract()
    contract.symbol = "EUR"
    contract.secType = "CASH"
    contract.currency = "USD"
    contract.exchange = "IDEALPRO"

    # Here we are requesting tickdata for the EUR.USD Contract.
    app.reqTickByTickData(4001, contract, "MidPoint", 0, False)

    MAX_WAITED_SECONDS = 5
    print("Getting tick data from the server... can take %d second to complete" % MAX_WAITED_SECONDS)

    sleep(MAX_WAITED_SECONDS)

    # The connection can be disconnected after the data has been received
    app.disconnect()

if __name__ == "__main__":
    main()

```

## More information:

**Running the program:**

> After installing the necessary files you should be able to run *request_market_data.py* from you IDE or from your terminal using:

```bash
python3 request_market_data.py
```

![](images/run_from_terminal2.png)

> After which the following response indicates a successful connection:

![](images/output_from_console.png)

> After which a stream of data should start generating:

![](images/output_from_console2.png)

---

### More resources:

Take a further look at our online API Documentation to discover all of the possibilities using LYNX' API.

- [LYNX Basic Contract Definitions](https://api.lynx.academy/BasicContracts)
- [LYNX Requesting Market Data](https://api.lynx.academy/TopMarketData)
- [LYNX Available TickTypes](https://api.lynx.academy/TickTypes)

repository: lynxbroker/API-examples

repo_name: lynxbroker/API-examples


text:
---
layout: post
title:  "Letsencrypt is awesome!"
date:   2015-12-27 16:00:00
categories: misc
tags: ssl,openssl,certificates
---

I was about to shop for an SSL cert for a domain I own, and decided to do another "free SSL" Google search.

To my pleasant surprise, I stumbled upon this project "[letsencrypt](https://letsencrypt.org/)" which is sponsored by quite a lot of enterprise companies (Mozilla, Facebook to name a few).

In a nutshell, this is an CLI tool which makes life easier when you wish to configure your webserver for SSL, and also provide you with a free CA SSL cert for a domain you own. Pretty neat!

I didn't test this "quick-and-easy" setup with webservers, though. From what I see, it works via a webserver plugin.

Instead, I opted for the ```letsencrypt certonly --manual``` command. This command will require you to spin up a temporary Python webserver on a host that is verifiable by resolving the domain name. I'd say this is a small price to pay for a free SSL cert! Once that is done, you end up with your certs (and some of them bundled separately for convenience) in ```/etc/letsencrypt/live/$domain/``` .

This piece of software has my strong recommendation. You should check out their [documentation](https://letsencrypt.readthedocs.org/en/latest/using.html) which is compact and comprehensive. Have fun securing your stuff!

P.S.

While you are at it, you might want to check out [Raymii's blog post](https://raymii.org/s/tutorials/Strong_SSL_Security_On_nginx.html) on tightening your SSL settings on Nginx.

extension: markdown

gha_language: HTML


text:
### debian-hyperkube-base

Serves as the base image for `k8s.gcr.io/hyperkube-${ARCH}`
images.

This image is compiled for multiple architectures.

#### How to release

If you're editing the Dockerfile or some other thing, please bump the `TAG` in the Makefile.

```console
# Build and  push images for all the architectures
$ make all-push
# ---> staging-k8s.gcr.io/debian-hyperkube-base-amd64:TAG
# ---> staging-k8s.gcr.io/debian-hyperkube-base-arm:TAG
# ---> staging-k8s.gcr.io/debian-hyperkube-base-arm64:TAG
# ---> staging-k8s.gcr.io/debian-hyperkube-base-ppc64le:TAG
# ---> staging-k8s.gcr.io/debian-hyperkube-base-s390x:TAG
```

If you don't want to push the images, run `make all-build` instead

[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/build/debian-hyperkube-base/README.md?pixel)]()

repository: intuit/foremast

repo_name: intuit/foremast


text:
---
title: Installation
type: guide
category: Slim base
order: 1
github: https://github.com/awurth/Slim
---

### Create the project using Composer
``` bash
$ composer create-project awurth/slim-base [project-name]
```

### Setup environment variables

Copy `.env.dist` to a `.env` file and change the values to your needs. This file is ignored by Git so all developers working on the project can have their own configuration.

## Download client-side libraries
``` bash
$ npm install
```
This will install Gulp dependencies, and Semantic UI in `public/assets/lib/semantic/`.

### Gulp
This skeleton uses Gulp to manage assets. The CSS and Javascript files are located in `assets/`, so you have to use Gulp after creating your project to generate the minified files in `public/`, which will be ignored by Git.

### Install Gulp
You can install Gulp globally on your system with the following command if you haven't done it yet
``` bash
$ npm install -g gulp-cli
```

### Generate assets
If you just want to generate the default CSS and JS that comes with this skeleton, run the following command
``` bash
$ gulp build
```

If you want to run a watcher and begin coding, just run
``` bash
$ gulp
```

### Setup cache files permissions
The skeleton uses a cache system for Twig templates and the Monolog library for logging, so you have to make sure that PHP has write permissions on the `var/cache/` and `var/log/` directories.

### Update your database schema
First, create a database with the name you set in the `.env` file. Then you can create the tables by running this command:
``` bash
$ php bin/console db
```

If you're using [Oh My Zsh](https://github.com/robbyrussell/oh-my-zsh), you can install the symfony2 plugin, which provides an alias and autocompletion:
``` bash
# Without Symfony2 plugin
$ php bin/console db

# With Symfony2 plugin
$ sf db
```


text:
---
layout: default
---

# 1997-04-21 - Re: SSL weakness affecting links from pa

## Header Data

From: John Deters<EMAIL_ADDRESS>To: Adam Shostack<EMAIL_ADDRESS>Message Hash: 31e60486d0fde4b40a115585e03103fb835e8171d4b212abd0206c29eba575f9

Message ID: \<<IP_ADDRESS>.19970421133153.02551970@labg30\>

Reply To<EMAIL_ADDRESS>UTC Datetime: 1997-04-21 18:32:06 UTC

Raw Date: Mon, 21 Apr 1997 11:32:06 -0700 (PDT)

## Raw message

```
{% raw  %}From: John Deters<EMAIL_ADDRESS>Date: Mon, 21 Apr 1997 11:32:06 -0700 (PDT)
To: Adam Shostack<EMAIL_ADDRESS>Subject: Re: SSL weakness affecting links from pa
In-Reply-To<EMAIL_ADDRESS>Message-ID: <<IP_ADDRESS>.19970421133153.02551970@labg30>
MIME-Version: 1.0
Content-Type: text/plain

At 03:32 PM 4/20/97 -0500, Adam Shostack wrote:
>	Thats true, but can they avoid it?  I'm considering writing a
>database pollution bot, which runs around, claiming to be Mozilla or
>IE, and randomly following a link once per minute.  Why?  Database
>pollution.  If there are a few thousand of these randomly collecing
>links and creating arbitrary (or perhaps biased) viewing habbits in
>the databases of the advertisers, then their individual data becomes
>worth less.  They'll need to actively solicit peoples permission to
>collect data before doing so, to avoid people polluting their
>databases.
>
>	Similarly, putting a randomly generated email address in those
>sign up fields produces pollution in the data used by spammers, which
>costs them (and no one else) money.

You are forgetting to separate the marketers from the businesses being
marketed here.  While they're occasionally one and the same (see Cantor &
Siegel), in today's world, the marketing is being handled by a third party
(doubleclick).

These marketers get paid by hit-count ratings:  if they deliver the message
to 1,000 browsers, they get some amount, say $15.00.  If they deliver it to
100,000 browsers, they get $1500.00.  They're not paid by the number of
respondents, referred sales, or even valid e-mail addresses snarfed.  So,
you'd only be artifically inflating the cost of the marketers to the
advertisers.

Here, your hope is that the advertisers notice a diminishing ROI for
marketing costs, but that's a big hope.  The numbers for a small site might
look something like this:

January -  20,000 hits, 50 sales
February - 22,000 hits, 60 sales
March    - 25,000 hits, 70 sales
April    - 50,000 hits, 90 sales  <-- pollutionbot strikes 20,000 times

So, you've watered it down a bit.  To make the pollutionbot truly
effective, you'd have to hit a site by at least 10x the general population
strikes:

May      - 440,000 hits, 100 respondents <- pollutionbot strikes 400,000 times

In the meantime, they're billing the business:
Month        Hits   Sales  Billing    Cost/sale  Pollutionbot hits/inflation
January  -  20,000   50     $300        $6.00            0     $0
February -  22,000   60     $330        $5.50            0     $0
March    -  25,000   70     $375        $5.36            0     $0
April    -  50,000   90     $750        $8.33       20,000   $300
May      - 440,000  100    $6600       $66.00      400,000  $6000

Hopefully, the advertisers will pull out at this point.  It's easy to see
that something "bad" is happening, and that they're not getting the bang
for the buck that they need.  However, with some megasites (where they
reportedly get 2,000,000+ hits per day) subscribing to doubleclick.com,
it's doubtful you could make a noticable dent unless you started your
attack from a T3 connected backbone site.

The marketers will also try to keep this sham up by saying to the
businesses, "It's the Internet, who the hell knows?  Keep going another
month, it'll get better.  In the meantime, just pay your bills."

Even if you were successful at flooding doubleclick, many of their
advertisers are Big:  IBM, Micro$oft, HP, etc.  They don't even care about
direct responses, they're just after name recognition.

Ultimately, it'll reduce the ability of Mom & Pop (or Cantor & Siegel) to
advertise on the same playing field as Micro$oft.  Doubleclick won't go
broke; neither will Micro$oft.  The only good hope you may have is of
breaking a "mom & pop" version of doubleclick, and keeping the world less
polluted.  But, doubleclick will still be around and be able to move in and
fill the void.  What have you gained then?

John
--
J. Deters "Don't think of Windows programs as spaghetti code.  Think
          of them as 'Long sticky pasta objects in OLE sauce'."
+--------------------------------------------------------------------+
| NET<EMAIL_ADDRESS>(work<EMAIL_ADDRESS>(home) |
| PSTN:  1<PHONE_NUMBER> (work)          1<PHONE_NUMBER> (home)        |
| ICBM:  44^58'36"N by 93^16'27"W Elev. ~=290m (work)                |
| For my public key, send mail with the exact subject line of:       |
| Subject: get pgp key                                               |
+--------------------------------------------------------------------+

{% endraw %}
```

## Thread

+ Return to [April 1997](/archive/1997/04)

+ Return to "[Adam Shostack <adam@homeport.org>](/authors/adam_shostack_adam_at_homeport_org_)"
+ Return to "[Bill Stewart <stewarts@ix.netcom.com>](/authors/bill_stewart_stewarts_at_ix_netcom_com_)"
+ Return to<EMAIL_ADDRESS>(Dr.Dimitri Vulis KOTM)](/authors/dlv_at_bwalk_dm_com_dr_dimitri_vulis_kotm_)"
+ Return to "[Eric Murray <ericm@lne.com>](/authors/eric_murray_ericm_at_lne_com_)"
+ Return to "[Jeremiah A Blatz <jer+@andrew.cmu.edu>](/authors/jeremiah_a_blatz_jer_at_andrew_cmu_edu_)"
+ Return to "[John Deters <jad@dsddhc.com>](/authors/john_deters_jad_at_dsddhc_com_)"
+ Return to "["Phillip M. Hallam-Baker" <hallam@ai.mit.edu>](/authors/phillip_m_hallambaker_hallam_at_ai_mit_edu_)"
+ Return to "[Rachel Willmer <rachel@intertrader.com>](/authors/rachel_willmer_rachel_at_intertrader_com_)"
+ Return to "[Steve <steve@edmweb.com>](/authors/steve_steve_at_edmweb_com_)"

+ 1997-04-18 (Fri, 18 Apr 1997 14:00:14 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/fc22f771efb14cf0329884f00864c0b07b5cb4b1d4f3275e3abd05a219e29c4c) - _"Phillip M. Hallam-Baker"<EMAIL_ADDRESS>  + 1997-04-19 (Fri, 18 Apr 1997 18:00:12 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/0615645d98993f0c6cd3c6de93997ad4750375de65d2e6d2ace5799926df1e25) -<EMAIL_ADDRESS>(Dr.Dimitri Vulis KOTM)_
  + 1997-04-19 (Fri, 18 Apr 1997 23:12:09 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/6c4626e8060ed18bffb8707a3c6b0a9b350527d01e0232d74d64c5c65fd68960) - _Bill Stewart<EMAIL_ADDRESS>    + 1997-04-19 (Sat, 19 Apr 1997 07:38:49 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/1edb47e356e9bf9ec325a9177b3306b03c33a66e30a6b3c9cbfe8ef55019625c) - _Adam Shostack<EMAIL_ADDRESS>      + 1997-04-19 (Sat, 19 Apr 1997 13:39:24 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/5046a951df5b23de5b8c477e9c81daf8251d10bd597228b7fce8de01f886934b) - _Steve<EMAIL_ADDRESS>        + 1997-04-20 (Sun, 20 Apr 1997 13:35:33 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/c5faf59009a42deebdf77f088a60c15472a217883a3e4a3187374df57ed21735) - _Adam Shostack<EMAIL_ADDRESS>          + 1997-04-21 (Sun, 20 Apr 1997 19:23:01 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/5b4c4a4f72fb122eeb4efa26551d517b84943a705a33f9b826a76e4040e1e34f) - _Eric Murray<EMAIL_ADDRESS>            + 1997-04-21 (Sun, 20 Apr 1997 19:35:40 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/420a1a7cae73f2b46ebeaf42cabf3a9e3c1b263e1828a49a2a8ceb0270192e55) - _Adam Shostack<EMAIL_ADDRESS>            + 1997-04-21 (Sun, 20 Apr 1997 20:13:21 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/c92f7d3d02d604d4c3edc4513cc9a9e935da3f6d5bbb3de963581998324cb7e3) - _Jeremiah A Blatz<EMAIL_ADDRESS>        + 1997-04-21 (Mon, 21 Apr 1997 11:32:06 -0700 (PDT)) - Re: SSL weakness affecting links from pa - _John Deters<EMAIL_ADDRESS>    + 1997-04-20 (Sun, 20 Apr 1997 12:34:43 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/d7a910088324e201d7418d48aff6628224971f62600aa9c0f352019200953289) - _Rachel Willmer<EMAIL_ADDRESS>      + 1997-04-20 (Sun, 20 Apr 1997 13:26:22 -0700 (PDT)) - [Re: SSL weakness affecting links from pa](/archive/1997/04/af75c4531c842f9c1c1931d13e5a3abab5b278ff9101446da09e186139c05250) - _Adam Shostack<EMAIL_ADDRESS>


text:
# Using Matplotlib to Visualise Data

Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+.

## Getting Started

- [x] Importing And Using Matplotlib
- [x] Anatomy Of A Matplotlib Figure
- [x] Scatter Plot And Bar Plot
- [x] Histograms And Subplots
- [x] Plotting From Pandas DataFrames
- [ ] Customizing Your Plots
- [ ] Saving And Sharing Your Plots
- [ ] Assignment: Matplotlib Practice

## Prerequisites

Jupyter Notebook

```
pip install matplotlib
```

## Documentation

* [http://matplotlib.org) - Library

## Authors

* Dulaj Kavinda

## License

This project is licensed under the MIT License

repository: dulajkavinda/matplotlib-ML

repo_name: dulajkavinda/matplotlib-ML


text:
# jison-lex

[![Join the chat at https://gitter.im/jison-parsers-lexers/Lobby](https://badges.gitter.im/jison-parsers-lexers/Lobby.svg)](https://gitter.im/jison-parsers-lexers/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Build Status](https://travis-ci.org/GerHobbelt/jison-lex.svg?branch=master)](https://travis-ci.org/GerHobbelt/jison-lex)
[![NPM version](https://badge.fury.io/js/%40gerhobbelt%2Fjison-lex.svg)](http://badge.fury.io/js/%40gerhobbelt%2Fjison-lex)
[![Dependency Status](https://img.shields.io/david/GerHobbelt/jison-lex.svg)](https://david-dm.org/GerHobbelt/jison-lex)
[![npm](https://img.shields.io/npm/dm/@gerhobbelt/jison-lex.svg?maxAge=2592000)]()

A lexical analyzer generator used by [jison](http://jison.org). It takes a lexical grammar definition (either in JSON or Bison's lexical grammar format) and outputs a JavaScript lexer.

## install

    npm install @gerhobbelt/jison-lex

or the entire bundle via

    npm install jison-gho

Then the `jison-lex` library is located in the subdirectory `packages/jison-lex/` of the `jison-gho` monorepo, i.e. `.../node_modules/jison-gho/packages/jison-lex/`.

Alternatively, the entire `jison-lex` API is also available via the `jison` API itself as can be seen from this internal `jison` code snippet:

```
import Lexer from '../packages/jison-lex';
import ebnfParser from '../packages/ebnf-parser';
import lexParser from '../packages/lex-parser';
import grammarPrinter from './util/grammar-printer.js';
import helpers from '../packages/helpers-lib';
var rmCommonWS = helpers.rmCommonWS;
var camelCase  = helpers.camelCase;
var code_exec  = helpers.exec;
import XRegExp from '@gerhobbelt/xregexp';
import recast from 'recast';
import astUtils from 'ast-util';
import json5 from '@gerhobbelt/json5';

// Also export other APIs: the JISON module should act as a 'facade' for the others,
// so applications using the JISON compiler itself can rely on it providing everything
// in a guaranteed compatible version as it allows userland code to use the precise
// same APIs as JISON will be using itself:
Jison.Lexer = Lexer;
Jison.ebnfParser = ebnfParser;
Jison.lexParser = lexParser;
Jison.codeExec = code_exec;
Jison.XRegExp = XRegExp;
Jison.recast = recast;
Jison.astUtils = astUtils;
Jison.JSON5 = json5;
Jison.prettyPrint = grammarPrinter;
Jison.rmCommonWS = rmCommonWS;
Jison.mkStdOptions = mkStdOptions;
Jison.camelCase = camelCase;
Jison.autodetectAndConvertToJSONformat = autodetectAndConvertToJSONformat;
...
Jison.Parser = Parser;

export default Jison;
```

hence you can get at it this way, for example:

```
import jisonAPI from 'jison-gho';
// get a reference to the full `jison-lex` API:
const jisonLexAPI = jisonAPI.Lexer;
```

## build

Follow the install & build directions of the monorepo.

You can also only build this particular subpackage by `cd`-ing into this directory
and then invoking the local make:

    cd packages/jison-lex
    make

This will generate the rollup/babel-postprocessed ES6 and ES5
compatible libraries and CLI in the local `dist/` directory.

>
> ### Note about ES6/rollup usage vs. ES5
>
> All `dist/` library files are 'self-contained': they include all 'local imports'
> from within this jison monorepo in order to deliver a choice of source files
> for your perusal where you only need to worry about importing **external dependencies**
> (such as `recast`).
>
> As such, these `dist/` files **should** be easier to minify and/or use in older
> (ES5) environments.
>
> #### rollup
>
> Iff you use `rollup` or similar tools in an ES6/ES2015/ES2017 setting, then the
> [`package.json::module`](https://github.com/rollup/rollup/wiki/pkg.module) has
> already been set up for you to use the *original sources* instead!
>

## usage

```
Usage: jison-lex [file] [options]

file     file containing a lexical grammar

Options:
   -o FILE, --outfile FILE       Filename and base module name of the generated parser
   -t TYPE, --module-type TYPE   The type of module to generate (commonjs, js)
   --version                     print version and exit
```

## programmatic usage

```
var JisonLex = require('@gerhobbelt/jison-lex');

var grammar = {
  rules: [
    ["x", "return 'X';" ],
    ["y", "return 'Y';" ],
    ["$", "return 'EOF';" ]
  ]
};

// or load from a file
// var grammar = fs.readFileSync('mylexer.l', 'utf8');

// generate source
var lexerSource = JisonLex.generate(grammar);

// or create a parser in memory
var lexer = new JisonLex(grammar);
lexer.setInput('xyxxy');
lexer.lex();
// => 'X'
lexer.lex();
// => 'Y'
```

## license

MIT

## related repositories

- [jison / jison-gho](https://github.com/GerHobbelt/jison) @ [NPM](https://www.npmjs.com/package/jison-gho)
- [jison-lex](https://github.com/GerHobbelt/jison/master/packages/jison-lex) @ [NPM](https://www.npmjs.com/package/@gerhobbelt/jison-lex)
- [lex-parser](https://github.com/GerHobbelt/jison/master/packages/lex-parser) @ [NPM](https://www.npmjs.com/package/@gerhobbelt/lex-parser)
- [ebnf-parser](https://github.com/GerHobbelt/jison/master/packages/ebnf-parser) @ [NPM](https://www.npmjs.com/package/@gerhobbelt/ebnf-parser)
- [jison2json](https://github.com/GerHobbelt/jison/master/packages/jison2json) @ [NPM](https://www.npmjs.com/package/@gerhobbelt/jison2json)
- [json2jison](https://github.com/GerHobbelt/jison/master/packages/json2jison) @ [NPM](https://www.npmjs.com/package/@gerhobbelt/json2jison)
- [jison-helpers-lib](https://github.com/GerHobbelt/jison/master/packages/helpers-lib) @ [NPM](https://www.npmjs.com/package/jison-helpers-lib)
- ### secondary source repositories
  + [jison-lex](https://github.com/GerHobbelt/jison-lex)
  + [lex-parser](https://github.com/GerHobbelt/lex-parser)
  + [ebnf-parser](https://github.com/GerHobbelt/ebnf-parser)
  + [jison2json](https://github.com/GerHobbelt/jison2json)
  + [json2jison](https://github.com/GerHobbelt/json2jison)
  + [jison-helpers-lib](https://github.com/GerHobbelt/jison-helpers-lib)

repository: GerHobbelt/jison

repo_name: GerHobbelt/jison


text:
# Apolpi

[![Docker Repository on Quay](https://quay.io/repository/galaxy-genome-annotation/apolpi/status "Docker Repository on Quay")](https://quay.io/repository/galaxy-genome-annotation/apolpi) ![Lint](https://github.com/galaxy-genome-annotation/apolpi/workflows/Lint/badge.svg)

This is a tiny Flask application reimplementing a specific API function (organism listing) of [Apollo](https://github.com/GMOD/apollo), to make it run way faster.

See https://github.com/GMOD/Apollo/issues/2626 for more details on why we implemented it.

## Running with docker-compose

A typical docker-compose.yml to run this app looks like that:

```
version: '3.7'
  services:

    apolpi:
    	image: quay.io/galaxy-genome-annotation/apolpi
            environment:
                SQLALCHEMY_DATABASE_URI: "postgresql://username:password@localhost:5432/apollo"
```

## Configuring Nginx proxy

You need to configure your reverse proxy (Nginx for example) to redirect the traffic for this specific API endpoint, like this:

```
location /apollo/organism/findAllOrganisms {
   proxy_pass http://<IP_ADDRESS>:80/organism/findAllOrganisms;
}
```

The rest of the API traffic need to be proxied to the normal Apollo application as usual.

## Required env variables

* SQLALCHEMY_DATABASE_URI *Connection Uri to the postgres database of Apollo*

repository: galaxy-genome-annotation/apolpi

repo_name: galaxy-genome-annotation/apolpi


text:
TIL if I put password confirmation thing, I need to seed my users with password: "blahblah", password_confirmation: "blahblah" as well

activerecord defaults at UTC time it kept effing up my 'sort by today' page.
## changes timezone to local, instead of UTC
ActiveRecord::Base.default_timezone = :local
fixed the timezone issue.

BMR Formula (Imperial)
Women: BMR = 655 + (4.35 x weight in pounds) + (4.7 x height in inches) - (4.7 x age in years)

Men: BMR = 66 + (6.23 x weight in pounds) + (12.7 x height in inches) - (6.8 x age in years)

     ## calculates basal metabolic rate using the Harris-Benedict equation
     def calculate_user_bmr(user)
       if user.gender == "male"
         bmr = 66 + (user.weight * 6.23) + (12.7 * user.height) - (6.8 * user.age)
       elsif user.gender == "female"
         bmr = 655 + (user.weight * 4.35) + (4.7 * user.height ) - (4.7 * user.age)
       end
       return bmr.to_i
     end

    ## calculates basal metabolic rate using the Mifflin St. Jeor equation
    def self.calculate_user_bmr(user)
        if user.gender == "male"
        bmr = (10 * (user.weight * 0.4535934)) + (6.25 * (user.height * 2.54)) - (5 * user.age) + 5
        elsif user.gender == "female"
        bmr = (10 * (user.weight * 0.4535934)) + (6.25 * (user.height * 2.54)) - (5 * user.age) - 161
        end
        return bmr.to_i
    end

To determine your total daily calorie needs, multiply your BMR by the appropriate activity factor, as follows:

If you are sedentary (little or no exercise) : Calorie-Calculation = BMR x 1.2
If you are lightly active (light exercise/sports 1-3 days/week) : Calorie-Calculation = BMR x 1.375
If you are moderatetely active (moderate exercise/sports 3-5 days/week) : Calorie-Calculation = BMR x 1.55
If you are very active (hard exercise/sports 6-7 days a week) : Calorie-Calculation = BMR x 1.725
If you are extra active (very hard exercise/sports & physical job or 2x training) : Calorie-Calculation = BMR x 1.9

## KNOWLEDGE REQUIREMENTS

- MVC
	- What is MVC?
		Model View Controller

	- Why do we use it?
		It creates a separation of concerns where groups of files have specific jobs. Models is where data is manipulated, views is the front-end where users will see, controllers are the middleman.

	- Does everything we need fit inside MVC?
		We still got our config, environment files, gemfiles, etc

	- How does this affect our file structure?
		Keeps our code very organized, each file will have a different responsibility. Seperated presentation.

- CRUD
	- What is CRUD?
		Create (SQL: INSERT, HTTP: POST)
    Read (SQL: SELECT, HTTP: GET)
    Update (SQL: UPDATE, HTTP: PATCH)
    Delete (SQL: DELETE, HTML: DELETE)

REST
- What is REST?
	Representational State Transfer. It’s an architectural style that web applications using HTTP should follow. Looking something up should use GET requests, creating stuff uses POST requests, updating things uses PATCH/PUT, and deleting stuff uses DELETE requests.

- Why do we use it?
	It makes things simple af. It provides mapping between HTTP verbs like get, post, delete, patch, to controller CRUD actions. Whenever our web app receives an HTTP request, it matches that request to the right controller action. Boom.

- CRUD actions are different actions that occur on the same resource. If we want to view item 6, we make a GET request to /item/6, but if we want to update it, it's gonna be a PUT/PATCH request to the same /item/6 route.

Environment Variables

- What are they?
	It’s kind of like a hash with a key/value pair (KEY=VALUE) that we use to share configurations between programs, like making our app start in test/development/production mode. Can also tell our OS where to look for binary files, or telling Ruby where to look for gems. We use `env` in the terminal to see a list.

Sessions/Cookies

- What are cookies?
	It's a hash of data that gets stored in the browser to store data. It gets sent back to the server at every request to let the server remember you.

- What are sessions?
	It’s similar to a cookie but more on the server-side usage for temporarily saving data while the user browses.

- How did we use them?
	We did that set SESSION_SECRET = ENV['SESSION_SECRET'] thing

- 12 Factor Apps?
	It stores config in environment variables. Which allows easy change between deploys (production, development, staging, etc) without changing any code.

Sinatra Basics

	- How to enable sessions?
		Within our ApplicationController class, in the configure do block, “enable :sessions”

	- How to set up a database?
		In our env file, `ActiveRecord::Base.establish_connection` block, `:database => “db/#{ENV[‘SINATRA_ENV’].sqlite”`.

    ```ruby
    configure :development do
    set :database, 'sqlite3:db/database.db'
    end
    ```

	- How to ensure all our gems are being used?
		Gemfile?

	- What gem enables database password encryption?
		Bcrypt

	- Why do we encrypt our passwords in the database?
		So bad people can’t guess and steal??

	- What are helpers and why do we use them?
		Helpful methods placed in a helpers do block in our application controller, and we use them so we don’t have to throw a bunch of logic in a view which makes it messy af. Instead we can abstract it into a helper method.

	- How do we make helpers?
		In ApplicationController class, we set up a helpers do end block

	- How to create migrations?
		rake db:create_migration NAME=create_whatever

	- How to set up has_many and belongs_to relationship vs a has_many to has_many in sql/activerecord
		class Dog belongs to class Owner, class Owner has many dogs

	class Assembly has_many_and_belongs_to_many :parts
  class Part has_and_belongs_to_many :assemblies

  We can also do a many_to_many using has_many :through to make the association indirectly, through a join model.

- How to rescue an error in Ruby?
    We wrap our code that raises the error in a  `begin`/`rescue` block.
    ```ruby
    begin
      #code we are trying to run and may break on us
    rescue
      puts "this will fuck up"
    end
    ```

- Difference between authentication and authorization?
    authentication authenticates the current user, checks if they're logged in and if they are the current user, else we can kick or redirect them to login

    authorization checks if they are authorized for action, like authorizing a user for editing something.

- Walk through the logical progession process of a user asking for an HTML form to data being changed in the database (include user input validation and authentication/authorization)
    User clicks on a link, or types in an HTML, that triggers a get request, then when they input whatever in the form, and submit, that triggers a post request. The post request then says wassap to the controller, it goes in has params and has to get through authentication or authorization, then the input validation will get triggered whenever a `.save` or `.update` method is called.

- What is Rack?
    A gem - a Ruby Webserver Interface, that helps us create a web server at its simplest form. The building block of rails. Has a config rackup file.

- What is Rake used for? How to make a Rake task?
    A task runner used in Ruby. We use it for stuff like - making backups of our db, running our tests, gathering and reporting stats. It helps the Ruby servers and frameworks work together
    rake -t to see a list

    to make a rake task, we need a rakefile, we can do something like:
    ```ruby
        task :console do
        Pry.start
        end

        rake console
    ```

- How to use a .gitignore correctly?
    `touch .gitignore` then write the name of the files you want git to ignore when you add/push

- What methods do ActiveRecord give you? How do we access associations? Show in rake console.
    It gives us a bunch of methods like .create, .find, .new, .save, .update, .destroy_all, etc.
    ```
    u = User.find_by_id(1)
    u.update(name: "Woogie Boogie")
    u.delete
    ```

    We can do something like:
    ```ruby
    dude = Owner.create(name: "Human")
    woof = Dog.new(name: "Bark")
    woof.owner = dude
    woof.save
    ```
    This is of course after our associations are set up in the classes and tables

- What Http methods are idempotent?
    Idempotent methods are HTTP methods that can be called many times without different outcomes. (`a = 4` yes, `a++` no)

    GET, DELETE are idempotent, POST, PATCH are not.


text:
# TutoPop
### Lead by bubble!

___

## Requirements
* JQuery

___

## What is it?

TutoPop is a jQuery-based tool for creating simple popup tutorials showing your users the interface of your website or web app!

___

## How does it work?

It's simple! All you have to do is pass in a few key points of data voila! Instant tutorials!

The method takes up to 5 arguments

``` js
tutoPop(array[, array, int, callback, callback]);
```

Then there are (currently) 2 initiation type methods to call on tutoPop

``` js
// timeline
// calling the "timeline" method will initiate tutoPop for procedural operations
tutoPop(...).timeline()
// oneTime
// calling the "oneTIme" method will initiate tutoPop to display all tutorial popups at once.
tutoPop(...).oneTime([options])
```

The initiation methods accept an object with the following options
``` js
// This is an object of our initiation method options
// fadeIn: the time, in seconds, that it'll take for the dialog box to fade in
// highlight: indicates whether or not to include a highlight on the page
// color: a CSS color value (hex code or RGB), the color of the area surrounding the highlighted area
// opacity: the opacity of the highlight box (color opacity is effected)

{
  fadeIn: number
  highlight: boolean,
  opacity: number,
  color: string
}
```
**NOTE: the "highlight" option is not available to the "oneTime()" initiation method. Ergo, neither are "opacity" and "color"**
___

Here how it works:

First, you'll want to create an array of all of your tutorial prompts

``` js
// This is an array of our tutorial prompts.
// It's an array of objects that take 9 parameters:

// dialogX: this is the x coordinate for the tutorial dialog box. 50% is the default
// dialogY: this is the y coordinate for the tutorial dialog box. 50% is the default
// highlightX: this is the x coordinate for the tutorial highlight box
// highlightY: this is the y coordinate for the tutorial highlight box
// highlightRadius: this is the border radius for the highlight area
// highlightWidth: this is the width of the optional highlight area
// highlightHeight: this is the height of the optional highlight area
// msg: this is the actual text for the tutorial dialog box. "???" is the default text
// side: this is the side that arrow will appear: top(default), right, bottom, left
// offset: this is of the arrow. If it had a face, negatives would be its left, posititves its right. Influence is a percentage based on dialog box width or height. 0% is the default value
// maxWidth: this is the maximum width of the dialog box

var tutorials = [
  {
    dialogX: number,
    dialogY: number,
    highlightX: number,
    highlightY: number,
    highlightRadius: number,
    highlightWidth: number,
    highlightHeight: number,
    msg: string,
    side: string,
    offset: number,
    maxWidth: number
  },
  ...
];
```

Next, we call the tutoPop method to initiate the tutorial popups

``` js
tutoPop(tutorials).[initiationTypeMethod]([options]);
```

And that's it! Seriously, that's all that's required.

Of course there's more that you can so with TutoPop, so let's explore what those other optional arguments let us do.

___

``` js
tutoPop(tutorials[, color, index, nextButtonCallback, closeButtonCallback]);
```

### Color: array

The second argument accepts an array. Passing in any hex code(s) (or CSS rgb(a) value(s)) will let you change the color of both the text and the background.

``` js
["<color for background>", "<color for text>"]
```
Pass an empty string or null to ignore that index of the array.

### Index: number

The third argument accepts an integer. This indicates the place in the tutorials array in which to begin the tutorial.

Pass an empty string or null and it will default to 0;

### Callback(s): function

The third and fourth arguments accept a function. This allows you to trigger certain events for the clicking of the "Next" and "X" buttons.

Pass an empty string or null and it will ignore it;

Below you'll find an example of a callback function using this feature

``` js
// This is our callback for when the user clicks the next button of the current tutorial dialog box (optional)

// "arr" is the original array that gets passed back to this function
// "ind" is the current index that gets passed back to this function
// "nextFunc/closeFunc" are the original callbacks that get passed back to this function

var nextCB = function(arr, ind, nextFunc, closeFunc) {
  if(ind >= arr.length-1) {
    if(confirm("Would you like to rerun the tutorial?")) {
      tutoPop(arr, null, null, nextFunc, closeFunc).timeline();
    }
  }
};

// This is our callback for when the user clicks the close button of the current tutorial dialog box (optional)

// ditto

var closeCB = function(arr, ind, nextFunc, closeFunc) {
  if(confirm("Would you like to rerun the tutorial?")) {
    tutoPop(arr, null, null, nextFunc, closeFunc).timeline();
  }
};
```
**NOTE: if you use the "oneTime" initiation method "arr" with actually be a single tutorial from the popup**

That's just a small example of what you can use the callback feature of TutoPop for.  And tell me about it :)

Here's a [Codepen](http://codepen.io/piecedigital/pen/vNdaJm) example of TutoPop in use.

___

#  Thanks for viewing! :)
##  Star this repo if you liked it
###  Checkout my links below

[Twitter](http://twitter.com/PieceDigital) | [Github](piecedigital.github.io) | [LinkedIn](linkedin.com/in/pdstudios)

repository: piecedigital/TutoPop

repo_name: piecedigital/TutoPop


text:
# Cerebral Custom Resource Definitions

Cerebral is comprised of various [Custom Resource Definitions (CRDs)](https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions):

* [AutoscalingGroup](#autoscalinggroup)
* [AutoscalingPolicy](#autoscalingpolicy)
* [AutoscalingEngine](#autoscalingengine)
* [MetricsBackend](#metricsbackend)

The relationships between them are as follows:
* `AutoscalingGroup` references __one__ `AutoscalingEngine` and __one or more__ `AutoscalingPolicies`.
* `AutoscalingPolicy` references __one__ `MetricsBackend`.
* `AutoscalingEngine` describes how to communicate with __one__ autoscaling provider.
* `MetricsBackend` describes how to communicate with  __one__ metrics source.

All CRDs can be deployed using the `examples/common` directory:

```
kubectl apply -f examples/common
```

### AutoscalingGroup

An `AutoscalingGroup` is defined as a group of nodes that exists within the Kubernetes cluster, and has the ability to be scaled independently of other nodes in the cluster.

The manifest for an AutoscalingGroup is available within the [prerequisite manifests][examples-prereqs].

#### Example

Examples are available in the [examples directory][examples-autoscaling-groups].

#### Fields

| Path | Required | Type | Description |
|------|----------|------|-------------|
| `spec.nodeSelector` | true | object | Set of key / value label pairs which are logically ANDed together, and are responsible for selecting the nodes that comprise the `AutoscalingGroup` |
| `spec.policies` | true | string | List of `AutoscalingPolicy` names applied to the `AutoscalingGroup` |
| `spec.cooldownPeriod` | true | number | Number of seconds to disable scaling events after a scaling action takes place |
| `spec.suspended` | true | boolean | Flag indicating whether scaling actions are allowed to take place |
| `spec.minNodes` | true | number | Minimum number of nodes in the group |
| `spec.maxNodes` | true | number | Maximum number of nodes in the group |
| `spec.engine` | true | string | Associated `AutoscalingEngine` used to change capacity of the `AutoscalingGroup` |
| `spec.scalingStrategy.scaleUp` | false | string | String representation of the `ScalingStrategy` to use when triggering a scale up operation. Default value provided by the associated `AutoscalingEngine`. |
| `spec.scalingStrategy.scaleDown` | false | string | String representation of the `ScalingStrategy` to use when triggering a scale down operation. Default value provided by the associated `AutoscalingEngine`. |
| `status.lastUpdateTime` | false | string | Timestamp representing the last time the `AutoscalingGroup` triggered a scale event |

#### Notes

**Important**: The set of nodes selected by each `nodeSelector` must be disjoint from the sets of nodes selected by all other selectors for other `AutoscalingGroups`.
Otherwise, a single node would belong to multiple `AutoscalingGroups`.

### AutoscalingPolicy

An `AutoscalingPolicy` is defined as a list of thresholds, responsible for triggering one or more `AutoscalingGroups` to scale either up or down based on the returned metric value from the `MetricsBackend`.

The manifest for an AutoscalingPolicy is available within the [prerequisite manifests][examples-prereqs].

#### Example

Examples are available in the [examples directory][examples-autoscaling-policies].
See also [documentation for specific metrics backends][docs-metrics-backends].

#### Fields

| Path | Required | Type | Description |
|------|----------|------|-------------|
| `spec.metricsBackend` | true | string | `MetricsBackend` name associated with the `AutoscalingPolicy` |
| `spec.metric` | true | string | String representation of the target metric to monitor. Available values are provided by the given `MetricsBackend`. |
| `spec.metricConfiguration` | false | object | Arbitrary configuration object used to configure the metric polling. See [metrics configuration](#metrics-configuration). |
| `spec.policy.scaleUp` | false | object | Policy object containing parameters used when scaling an `AutoscalingGroup` up |
| `spec.policy.scaleUp.threshold` | true | number | Numerical representation of the threshold at which when the comparison evaluates to true, the associated `AutoscalingGroups` should scale up
| `spec.policy.scaleUp.comparisonOperator` | true | string | The comparison operator to use when comparing the `MetricsBackend` metric value to the `threshold` value. Allowed values are `>`, `<`, `>=`, `<=`, `==`, `!=` |
| `spec.policy.scaleUp.adjustmentType` | true | string | Method by which to add capacity to the `AutoscalingGroup`. Absolute represents an exact number of nodes, whereas percent represents a percentage (rounded up to the nearest whole number) of nodes in the pool. |
| `spec.policy.scaleUp.adjustmentValue` | true | number | Numerical representation of the number of nodes to scale the `AutoscalingGroup` up by determined by the `adjustmentType` |
| `spec.policy.scaleDown` | false | object | Policy object containing parameters used when scaling an `AutoscalingGroup` down |
| `spec.policy.scaleDown.threshold` | true | number | Numerical representation of the threshold at which when thhe comparison evaluates to true, the associated `AutoscalingGroups` should scale down
| `spec.policy.scaleDown.comparisonOperator` | true | string | The comparison operator to use when comparing the `MetricsBackend` metric value to the `threshold` value. Allowed values are `>`, `<`, `>=`, `<=`, `==`, `!=` |
| `spec.policy.scaleDown.adjustmentType` | true | string | Method by which to add capacity to the `AutoscalingGroup`. Absolute represents an exact number of nodes, whereas percent represents a percentage (rounded up to the nearest whole number) of nodes in the pool. |
| `spec.policy.scaleDown.adjustmentValue` | true | number | Numerical representation of the number of nodes to scale the `AutoscalingGroup` down by determined by the `adjustmentType` |
| `spec.pollInterval` | true | number | Number of seconds between polling the associated `MetricsBackend` |
| `spec.samplePeriod` | true | number | Number of seconds the `AutoscalingPolicy` must alert the threshold before the policy triggers a scale up or scale down action |

#### Notes

The `AutoscalingPolicy` can be thought of as a mathematical comparison defined as: `returnedMetricValue` `spec.policy{scaleUp,scaleDown}.comparisonOperator` `spec.policy{scaleUp,scaleDown}.threshold`.

If the comparison evaluates to `true`, the `AutoscalingPolicy` is said to "alert".
A scale request is generated only if the threshold is breached for at least the `samplePeriod`.

* The `AutoscalingPolicy` is not required to implement both a `scaleUp` and `scaleDown` policy definition.
* Since `AutoscalingGroup`s are often homogeneous, a `scalingStrategy` is often only used in conjunction with a `scaleDown` policy.
* If the group were heterogeneous, the `scaleUp` policy could in theory pick a node and add capacity of the same instance type.

### AutoscalingEngine

An `AutoscalingEngine` is defined as the system responsible for adding or removing capacity to the Kubernetes cluster.

The manifest for an AutoscalingEngine is available within the [prerequisite manifests][examples-prereqs].

#### Example

Example AutoscalingEngine manifests are available [in the examples directory][examples-autoscaling-engines].

#### Fields

| Path | Required | Type | Description |
|------|----------|------|-------------|
| `spec.type` | true | string | Type of engine |
| `spec.configuration` | true | object | Type-dependent configuration information for the engine |

### MetricsBackend

A `MetricsBackend` is defined as a source from which the cluster autoscaler will poll for metrics, returning a raw metric value to compare against the thresholds defined in the `AutoscalingPolicies` in order to make scaling decisions.
See the relevant `AutoscalingPolicy` fields [here](#autoscaling-policy-fields).

The manifest for a MetricsBackend is available within the [prerequisite manifests][examples-prereqs].

#### Example

Example MetricsBackend manifests are available [in the examples directory][examples-metrics-backends].

#### Fields

| Path | Required | Type | Description |
|------|----------|------|-------------|
| `spec.type` | true | string | Type of metrics backend |
| `spec.configuration` | true | object | Type-dependent configuration information for the metrics backend, i.e. information required to communicate with it |

##### Metric Configuration

The `MetricsBackend` is required to expose a list of well-defined metrics which the user can leverage in an `AutoscalingPolicy`.
Each metric may expose a different set of configurable parameters.
For Prometheus this looks like:

###### `cpu_percent_utilization`

Monitor the average CPU across an `AutoscalingGroup`.
Configuration is as follows:

| Key | Required | Type | Description |
|-----|----------|------|-------------|
| `aggregation` | false | string | Aggregation function to apply the metric (default `avg`) |
| `range` | false | string | Historical range over which to aggregate the metric (default `1m`) |
| `cpuMetricName` | false | string | Name of the CPU metric to fetch from Prometheus (default `node_cpu`) |

Note that [#48](https://github.com/containership/cerebral/issues/48) should remove the need to have a `cpuMetricName` configuration key.

###### `memory_percent_utilization`

Monitor the average memory across an `AutoscalingGroup`.
Configuration is as follows:

| Key | Required | Type | Description |
|-----|----------|------|-------------|
| `aggregation` | false | string | Aggregation function to apply the metric (default `avg`) |
| `range` | false | string | Historical range over which to aggregate the metric (default `1m`) |

###### `custom`

Monitor a custom metric across an `AutoscalingGroup`.
Configuration is as follows:

| Key | Required | Type | Description |
|-----|----------|------|-------------|
| `queryTemplate` | true | string | String template used to build the query |

[examples-prereqs]: ../examples/common/00-prereqs.yaml
[examples-autoscaling-engines]: ../examples/engines
[examples-autoscaling-groups]: ../examples/autoscaling_groups
[examples-autoscaling-policies]: ../examples/autoscaling_policies
[examples-metrics-backends]: ../examples/metrics_backends
[docs-metrics-backends]: ../docs/metrics_backends

repository: nicholascapo/cerebral

repo_name: nicholascapo/cerebral


text:
# Waveterm Interactive Viewer

Normally we write expect_tests which can output waveforms in ASCII
when testing Hardcaml, but we can also use the interactive viewer tool
to view waveforms that run for many cycles or
have a lot of signals. This is a very useful debugging tool
when initially designing a hardcaml circuit.

## Buliding a simulation application

The [`hardcaml_waveterm_interactive`](https://github.com/janestreet/hardcaml_waveterm/tree/master/interactive)
library can be used to build an
application which includes a hardware circuit that can be simulated
and the results viewed with the interactive viewer.

A waveform is created in the normal way by wrapping a simulator with
`Hardcaml_waveterm.create` and then running a testbench.

The following function is used to display the waveform.

```ocaml skip
# Hardcaml_waveterm_interactive.run waves
```

## Using the waveform viewer

* `q` quits
* `left/right` or `ctrl+mouse-wheel` scroll waveform horizontally
* `up/down` or `mouse-wheel` scroll waveform vertically
* `-/=` decrease/increase waveform scale

Left clicking on the waveform will position a cursor and show the
value of all signals in the values window.

All windows also have scroll bars that can be clicked on.

## Interactive waveforms from expect tests

Waveform-based expect tests are very information limited. We often
either run very small simulations, show a small portion of a larger
simulation, or zoom far out to capture general behaviour. Often we can
see the behaviour of control signals but not the detailed values on
data buses.

To help with this, the `Hardcaml_waveterm` library can optionally
serialize a waveform to disk. It provides an `expect` function which is
very similar to `Hardcaml_waveterm.Waveform.print`

```ocaml skip
Hardcaml_waveterm.Waveform.expect ~serialize_to:"filename" waves
```

This provides an optional argument called `serialize_to` which
specifies the filename to which the waveform will be saved. The suffix
`.hardcamlwaveform` will be added.

By default, waveforms are not saved. To do so execute the tests with
the following environment variable set.

```
EXPECT_TEST_WAVEFORM=1 ./inline_tests_runner
```

Which will output a file in the same directory called
`filename.hardcamlwaveform`.

To view the waveform, a tool called `waveform_viewer` is provided with
`hardcaml_waveterm` in the `bin` directory.

```
waveform_viewer.exe show filename.hardcamlwaveform
```

repository: janestreet/hardcaml

gha_language: OCaml

repo_name: janestreet/hardcaml


text:
JSON Editor Angular directive
=============================

A directive that wraps [jdorn's json-editor](https://github.com/jdorn/json-editor).

JSON Editor takes a JSON Schema and uses it to generate an HTML form.

For further information about supported schema properties and usage, check out the original [json-editor](https://github.com/jdorn/json-editor).

Requirements
----------------

The module doesn't include the original json-editor code, but it is included in it's bower dependencies.

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

Install via bower

    bower install angular-json-editor --save

Then include the directive and json-editor in your html (you can also use the minified versions)

```html
<script src="bower_components/json-editor/dist/jsoneditor.js"></script>
<script src="bower_components/angular-json-editor/dist/angular-json-editor.js"></script>
```

Usage
-----

The directive supports both synchronous and asynchronous values, all values can be either a scope object, or a promise returned from $q, $http, $timeout, $resource etc.
Please check out `demo/index.html` and `demo/app.js` for an example usage of both scenarios.

### Validation
The directive exposes an `isValid` property on the scope, which can be used to enable/disable show/hide buttons using `ng-disabled/ng-enabled` or `ng-hide/ng-show`.
```html
<button type="button" ng-disabled="!isValid">Button 1</button>
```

### Events
The directive allows you to pass a callback function through the `on-change` attribute that will be called whenever a change event is fired on the editor.
```html
    <json-editor schema="mySchema" startval="myStartVal" buttons-controller="SyncButtonsController" on-change="onChange()">
```

### Configuration and Plugins
Configuring the JSONEditor object for plugins and styling is possible by injecting the JSONEditorProvider to your config function and calling the configure method.
The object you pass to configure will be merged with the JSONEditor object.

```javascript
    angular.module('demoApp', ['angular-json-editor']).config(function (JSONEditorProvider) {
        JSONEditorProvider.configure({
            plugins: {
                sceditor: {
                    style: 'sce/development/jquery.sceditor.default.css'
                }
            },
            defaults: {
                options: {
                    iconlib: 'bootstrap3',
                    theme: 'bootstrap3',
                    ajax: true
                }
            }
        });
    });

```

Building
---------

Clone the project, install bower and npm dependencies by running

    bower install && npm install

If you dont have grunt-cli installed globally run `npm install -g grunt-cli`

Then run `grunt` and look in the `dist` folder.

The MIT License (MIT)
------

Copyright (c) 2015 Rodik Hanukaev

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

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

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

repository: HULFT-Inc/angular-json-editor

repo_name: HULFT-Inc/angular-json-editor


text:
# Using UTPP with real world projects #
Following is how I have been using UTTP in my own projects. It may not be the
best solution but it has worked for me.

## Assumptions ##
+ All the devlopment is in a folder `\development`
+ The project that needs to use UTPP is called COOL_PROJ and its path is
`\development\cool_proj`
+ Include files for COOL_PROJ are under `\development\cool_proj\include`
+ Library files used by COOL_PROJ are under `\development\cool_proj\lib`
+ UTPP repo has been downloaded in folder `\development\utpp`

## Steps ##

1. Create a symlink named `utpp` in `\development\cool_proj\include` pointing to
`\development\utpp\include\utpp`:
```
  mklink /d \development\cool_proj\include\utpp \development\utpp\include\utpp
```

2. Create a symlink named `lib` <b>in `\development\utpp`</b> pointing to `\development\cool_proj\lib`
```
  mklink /d \development\utpp\lib \development\cool_proj\lib
```
  Note that the two symlinks are pointing in opposite directions: the first one
  goes from cool_proj to utpp while the second one goes from utpp to cool_proj

3. Build the UTPP project. This should produce utpp.lib file in `\development\utpp\lib`
folder. Because of the second symlink, uttp.lib will show up in `\development\cool_proj\lib`.

4. In your test files place an include directive for UTPP stuff:
```
  #include <utpp/utpp.h>
```
  Because of the first symlink, `\development\cool_proj\include` contains a folder
  named `utpp` and the compiler can find the include file.

5. Build your test program. `utpp.h` file contains a #pragma directive that specifies
the `utpp.lib` and the linker will be able locate `utpp.lib` file in `\development\cool_proj\lib`

## Different Configurations ##
UTPP libarary can be built in debug or release configurations for 32 or 64 bits.
To accommodate that, the output library is produced in `lib\win32\debug` or `lib\x64\debug`
or `lib\win32\release` or `lib\x64\release`. If you follow the same convention for
COOL_PROJ everything should work automatically.

## FAQ ##
1. Does this work with git?

  Yes it does. Git tries not to touch folders and files that
  are not under source control. The way the symlinks are setup should take care of that.

2. What if I have more than one project that uses UTPP? How can I setup my symlinks?

  I find it easiest to have a single include folder with subfolders for each project
  (something like \development\include\cool_proj, \develompent\include\even_cooler, etc.)
  and **one common** lib folder. Follow the steps above and all should work smoothly.


text:
---
published: false
title: Feedback Loops
menus:
  - Workflow Management
tags:
  - workflow management
---

The most important part of the workflow process are feedback loops, and how they affect
the speed and quality of value delivery.

The ultimate goal is to deliver quality software to our customers. Instead of speculating
how an end-user might consume your teams' product, feedback loops improve your existing
workflow so that you may meet your customer's needs rapidly and with less waste.

---

### Examples of Critical Feedback Loops

Feedback loops are as follows:
You produce something, measure information on that production, and use that information to improve.

- How well does the team understand the requirements?

  Teams need to work with leadership to flush out requirements. How well those requirements
  are understood, can be shown by how often developers are requesting additional information, or how often
  the team is committing code.

- How fast can the team detect defects?

  Defects are weaknesses in the system. The systematic approach of detecting
  where defects are occurring, and how far downstream they are, directly affects
  a team's Mean Time to Detect.

- How effective are our tests?

  [Testing](../testing-process/index.html) is one of the most effective feedback loops a team can have in place.
  Automated tests for example, provide feedback about your system in seconds.

- How well does what we're producing, match the users actual needs?

  Understanding if we're meeting the needs of the consumer is critical feedback.

  How fast can we determine that the customer is using the feature, and is happy with it?
  The longer the duration between the time we've started work, to the time we find out
  information, the more expensive it is.

---

#### Tips

- Use value stream mapping to uncover feedback loops, not just bottlenecks between specific steps.
- Focus on feedback loops that involve human communication, not just system alerts.
- Not all feedback loops are positive. Amplify feedback loops that promote positive change.

---

#### Value

As a development team, we want to identify and shorten our feedback loops, so that we
can analyze and optimize our workflow processes.

repository: bdfinst/engineering

repo_name: bdfinst/engineering


text:
---
title: Tips About Learning How to Program
author: Yamo Gebrewold
date: 2020-11-11
featuredImage: ../images/tips-about-learning-how-to-program.jpeg
---

It can be quite confusing as a beginner wanting to learn programming. The Web is packed with information, but knowing where to start and how to progress when learning programming can be a challenge.
The two big questions that arose in my head were:

1. What should I learn?
2. Where should I learn it?

In this article, I will try to discuss these two questions.

## What Should You Learn?

This one is hard especially as a beginner most likely won’t even know the different niches in software development and the various paths that one can take.

Like most questions, the answer would probably be: “it depends” on what your goal is. If your goal is to get a job as a programmer, then you would have to look at the job posts in your area to find out which area of software development has the greatest job demand. A personal recommendation would be to look into web development (frontend, backend or both) considering the great amount of jobs that are available in that area.

If your goal is to build your own app or do some programming tasks on your own instead of hiring someone to do them for you, then it would depend on what kind of tasks you need to get done.

## Where Should You Study?

This is a question where lots of people will give you different answers. In general, there are usually three routes, but I want to focus on the third one:

1. College.
2. Coding boot camps.
3. Self-teaching.

I want to focus on the third route because it’s the one that many people would probably start off with. And to be honest, most developers will probably combine college with self-teaching, or a coding boot camp with self-teaching. You will have to study on your own if you want to sharpen your skills and keep them up-to-date.

### Different Ways of Self-Teaching

Let’s start off by defining what self-teaching is. I would define it as using resources online to teach yourself programming. The big downside to this approach is that you have to build your own curriculum, which is quite hard when you don’t have any clue about what to start with. Here is where pursuing a college degree or attending a boot camp can be helpful because the curriculum is already prepared for you.

I remember myself scrolling through online forums and watching a bunch of YouTube videos by different people talking about which programming languages to begin with and why one language is more preferable than other languages. My first lines of code were actually in Python — mainly because of the online hype around that particular language — even though I don’t do any work in Python today.

As I mentioned before, the most important thing is to know your goal, and then explore which technologies you will need to learn in order to achieve that goal.

### Free Content vs Paid Content

There is an enormous amount of free content available on the Web today. Free learning resources which give you a great introduction to programming and can even teach you a lot about more advanced concepts too. I have consumed free content heavily — mostly on YouTube — and they help out a lot. On the other hand, I have also bought courses on Udemy for example and followed through the content there too. And in my opinion, I find that paid content tends to be more structured and in-depth than free content. So, free content is good for getting acquainted with the basics of a particular technology, but learning about the more advanced topics is probably hard through pure free content. A $10 course on Udemy can help you tremendously in your career, so it might be worth to look into paid content.

To give you a hint about some of the great YouTube channels for learning how to program, I would recommend the following three: TraversyMedia, WebDevSimplified and Academind.

## Interactive Coding Platforms vs Video Tutorials

With interactive coding platforms I mean platforms like FreeCodeCamp.org, Codecademy and so on. These are good because they explain the different concepts in a clear way and you also get to solve problems as you go, which forces you to apply the knowledge that you have just gained. I used to learn from both FreeCodeCamp and Codecademy in the beginning, and I think they are really suitable for some people, but I personally shifted to video tutorials for several reasons:

1. I felt that those platforms weren’t simulating a real development environment. Coding in a small editor inside of the browser is rarely how you would do regular programming tasks at work. I got many tips and tricks from instructors through their screen recordings of their environments and it gave me a better perspective of how real environments would look like.
2. I understood the concepts and managed to solve the exercises, but I didn’t grasp the whole picture and see how things were related. It was first when I followed YouTube and Udemy instructors who went through projects from scratch that I understood how different parts were connected.

In short, I would say that a combination of both is ideal. But if you only have time to focus on one platform, I would suggest sticking with video tutorials — just to get your feet wet with programming, and then building your own projects along with a lot of research and reading technical documentations about the technology stack in question.


text:
# Twitch for VLC #
* * *

Twitch for VLC is a playlist plugin for VLC that parses Twitch streams' and past broadcasts' URLs.

Someone just had to do it.

## Installation instructions ##

To install the plugin, [download twitch.lua](https://bitbucket.org/Nabile/twitch-for-vlc/raw/master/twitch.lua) and place it into `%VLC install dir%\lua\playlist`.

## Usage ##

* Open a VLC instance.
* Paste or drag and drop a Twitch stream or past broadcast URL.

## Credits ##

Thanks to Johannes Bader for providing a quick explanation on how to get Twitch video URLs (http://www.johannesbader.ch/2014/01/find-video-url-of-twitch-tv-live-streams-or-past-broadcasts/).

Thanks to Fons Leenaars for documenting the new HLS format used by past broadcasts (https://github.com/fonsleenaars/twitch-hls-vods).

repository: Nabile-Rahmani/twitch-for-vlc

repo_name: Nabile-Rahmani/twitch-for-vlc