text:
# Titan graph databse docker image

Titan is an opensource free scalable graph database optimized for storing and querying graphs containing hundreds of billions of vertices and edges distributed across a multi-machine cluster. Titan is a transactional database that can support thousands of concurrent users executing complex graph traversals in real time

This docker image instantiaties a Titan graph database that is capable of integrating with an ElasticSearch container (Indexing) and a Cassandra container (Storage).

The concepts used here can be extended to support any other storage or indexing backend, for that you would need to modify the run.sh file to suit your needs. The titan docker image builds the full version of titan, hence support to the storage / indexing engine is mearly configuration and modifications of configuration to suit the needs.

The default distribution of Titan runs on a single node, with this docker image, it is possible to hook onto the mostly used storage and indexing dependencies of titan (Cassandra and ElasticSearch respectively).

Thanks to Docker. It is possible to realize a separation of concerns at the same time co-locate the backend and titan-server as suggested by the authors of the database.

Note: the use of Docker is not endorsed by the authors of the database, but they suggested to have the storage node and titan-server communicate over localhost. In this docker scenario, I don't think there is any additional cost we have to look at!!

## Titan

Using this project, you can build titan from any specific tag / branch as per your wish. Supported directly by the configuration in the Dockerfile:
```
# search for the following entries and modify them as necessary.
ENV TITAN_VERSION="0.9.0-SNAPSHOT"
ENV TITAN_BRANCH="titan09"
```
You may even buid a specific container using a specific commit from titan code branch. For this you would need to update the the RUN command where the git checkout is performed.

If you want to build the titan from your fork, because you have done some changes to the open source code in your forke? no worries, just change the git repository path in the container where it is obtaining the package from and you are done.

You can find more details about titan at its [page](http://thinkaurelius.github.io/titan/) or the [live forum](https://groups.google.com/forum/#!forum/aureliusgraphs).

Note: If you wish to build titan from a older version/ branch/ tag, please make sure that you have the correct version of the JDK in the Dockerfile. If you are modern enough to use Docker, I wouldn't expect you to build a older version of titan though. Ofcourse, it is your business and your decision :)

## Tinkerpop and Gremlin

[TinkerPop3](http://tinkerpop.incubator.apache.org/) provides graph computing capabilities for both graph databases (OLTP) and graph analytic systems (OLAP) under the Apache2 license.

This project enables you to customize the version of Tinkerpop3 you want to depend upon. The current implementation always fetches the latest branch from the master and builds it.

In case you need a specific tag/ branch, please feel free to modify the Dockerfile using the titan portion of the git checkouts as example. If you don't even want to deal with building Tinkerpop3 and wish to directly titan, please change the flag to value other than YES.
```
ENV CUSTOMIZE_TINKERPOP="YES"
```

## Running

The minimum system requirements for this stack is 1 GB with 2 cores.

Run the required external dependencies, in our case : [Cassandra](https://github.com/docker-library/cassandra) and [ElasticSearch](https://github.com/docker-library/elasticsearch). Following are the snippets to run theese nodes, but I would encourage you to go to the respective github projects to get the latest and relevant instructions

```
# I am using the 2.0 version of cassandra and 1.5 version of elasticsearch.
# At the moment these are the versions supported by titan-0.9.0-M2.
# If the versions change, please feel free to use the correct versions
docker run --name cas1 -d cassandra:2.0
docker run -d --name elas1 elasticsearch:1.5
docker run -d -P --name mytitan --link elas1:elasticsearch --link cas1:cassandra <YOUR TITAN IMAGE>
```
If you wish to run Cassandra / Elasticsearch as clusters of their own, please refer to the documentation from the above mentioned project. For simplicity, I am omitting that topic here.

When running in docker containers, I would encourage you to mount the data directories in your host filesystem. This you can do as follows:
```
docker run -d --name cas1 -v /mnt/Share/titandb/cassdata:/var/lib/cassandra/data cassandra:2.0
docker run -d --name elas1 -v /mnt/Share/titandb/es_index_data:/usr/share/elasticsearch/data elasticsearch:1.5
```

Following is a visual depiction of how the whole thing would look like:
![docker_topology](https://cloud.githubusercontent.com/assets/9419954/9651888/b36eb066-5233-11e5-8e59-fbf3b811d378.jpg)

One more thing to note is, when you are using the docker containers as above with mounted file system, you should be aware of the facts mentioned in the [stackoverflow thread](http://stackoverflow.com/questions/16549833/cassandra-commit-and-recovery-on-a-single-node). I've spent good 2 days hitting around the bush to figure this out. [Details](https://groups.google.com/forum/#!topic/aureliusgraphs/VhLrgs4EsKo) of the issue I've faced.

### Run on Linux with docker-compose

    docker-compose up

To test that the server is running (with websockets) run this:

    bin/test

if You see this - everything is good:
```
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
WebSocket-Origin: http://localhost:8182
WebSocket-Location: ws://localhost/gremlin
```

To access the gremlin console:

    bin/gremlin

### Ports

8182: Websocket port (incase you are using the Websocket(default) version in the run.sh file)
8182: HTTP port for REST API (incase you are using the HTTP / JSON version in the run.sh file)

8184: JMX Port (You won't need to use this, probably)

To test out the REST API (over Boot2docker):

```
curl "http://docker.local:8182?gremlin=100-1"
curl "http://docker.local:8182?gremlin=g.addV('Name','Eric')"
curl "http://docker.local:8182?gremlin=g.V()"
```
For Websocket testing, you would need to have a proper application / gremlin-console. At the time of this writing, the gremlin-console coming with titan-0.9.0-M2 has some issues for remote connection. Hence I've tested using a simple Scala application connecting through gremlin-driver.

## Dependencies

I've tested this container with the following containers:

	- docker-library/cassandra: This is the Cassandra Storage backend for Titan
	- docker-library/elasticsearch: This is the ElasticSearch Indexing backend for Titan. It provides search capabilities for Titan graph datasets.

## Hurdles faced and how did I overcome
1. When using using the docker containers with mounted file system, you should be aware of the facts mentioned in the [stackoverflow thread](http://stackoverflow.com/questions/16549833/cassandra-commit-and-recovery-on-a-single-node). I've spent good 2 days hitting around the bush to figure this out. [Details](https://groups.google.com/forum/#!topic/aureliusgraphs/VhLrgs4EsKo) of the issue I've faced.
2. Not being able to connect to the titan-server through gremlin-driver. This has been addressed by the suggestion from stephen at the [Tinkerpop3-815](https://issues.apache.org/jira/browse/TINKERPOP3-815)

repository: lirender/docker-titan

repo_name: lirender/docker-titan


text:
# About

---

Running a self-published blog on a platform that does not have a blogroll component? You can run this web app to administer your links, then import them to your weblog as an HTML snippet. Or, if you are feeling fancy, import them as JSON then present them in whichever way you'd like.

**IMPORTANT** - this is a toy/learning project. I'm using it as I prepare for my AZ-204 exam.

## Platform

ASP.NET Core 6 using SQLite, LiteDB, Azure Tables, or MySQL for data storage.

Host it on Windows, Linux, in the cloud or in a Docker container.

## License

MIT. Do what you want with this and do not sue me if it does not work.

## Installation

### Docker
Review the Dockerfile and customize it as necessary. Then deploy to your favorite cloud provider. For my blog, I am using Azure with a Linux host.

### VPS / Azure App Service

Publish the project `Blogroll.Web`, which contains the web app. I strongly suggest putting the Kestrel behind a proxy such as `nginx`. Then, you'd want to obtain an SSL certificate, and configure your web server accordingly. By default, the app does not require or care about SSL but you do.

### Azure Functions

Deploy the project `Blogroll.Api` as a function app in Azure.

## Configuration

There are three environment variables you want to set:

- `Auth_Admin__Password` to be set with a password you'll use to manage your links (no username)
- `Data_Data__Engine` to be set with `sqlite`, `litedb`, `azuretables`, or `mysql` (case-insensitive)
- `Data_Data__Storage` - when using `sqlite` or `litedb`, set this with the relative or absolute path to an existing folder where the app will store the database file.

## Administration

Head over to the URL of your deployed app and log in using the pre-configured password (hopefully, over SSL).

For each link you want to add, the only truly mandatory field is the "Blog address". Enter a name if you want to customize it. If not, the app will try to obtain the name from the website's RSS feed.

Likewise, the "Feed url" field is optional. The app will perform auto-discovery if not entered.

You can change the ordering of the links within your blogroll by dragging and dropping the links.

## Integration

There's a simple anonymous API that serves your links as text, HTML, or JSON.

Assuming your deployed instance runs at `https://blogroll.example.com`, it's API server runs at `https://blogroll.example.com/api/v1`.

There are two endpoints:

- `/api/v1/links` for links that include a snippet  from the link's RSS feed's latest entry
- `/api/v1/links/simple` for links that do not include said snippet

By default, the endpoint will return HTML. You can explicitly request the content type by either specifying it in the request header, or by affixing `.json`, `.txt`, or `.html` to the URL, e.g. `https://blogroll.example.com/api/v1/links/simple.json` for JSON output.

### Example of integration

Edit your blog's template and place the following HTML snippet where you want your blogroll to appear:
```
<aside class="blogroll-host" id="blogroll-host" style="display:none">
  <h3>Blogroll</h3>
  <div id="blogroll-contents">
  </div>
</aside>
```

Then, add this at the bottom of your template:

```javascript
<script>
(function(){
  var request = new XMLHttpRequest();
  request.open('GET', 'https://blogroll.example.com/api/v1/links.html', true);
  request.onload = function () {
    if (request.status >= 200 && request.status < 400) {
      // Success!
      var home = document.getElementById("blogroll-contents");
      if (home != null) {
        home.innerHTML = request.responseText;
      }
      document.getElementById("blogroll-host").style.display="block";
    } else {
      // We reached our target server, but it returned an error
      console.log("Could not fetch the links");
    }
  };

  request.onerror = function (err) {
    // There was a connection error of some sort
    console.log(err);
  };

  request.send();
})();
</script>
```

(replacing `https://blogroll.example.com/api/v1/links.html` with the URL containing your instance's domain name).

For this to work, set up your web server such that it sends the right CORS headers like this:
`Access-Control-Allow-Origin: https://amazing.site` where `https://amazing.site` will be the URL where your blog is published.

You will notice it takes a second or two for your blogroll to appear. I will address caching and performance topics later. In the meantime, if you want top performance today, save the generated HTML and simply put it straight in your template, bypassing the XHR request altogether.

license: MIT

repository: teekay/Blogroll

branch_name: refs/heads/main

extension: md

gha_language: C#

gha_license_id: MIT

license_type: permissive

repo_name: teekay/Blogroll


text:
---
slug: storing-laravel-users-on-disk-in-flat-files
title: 'Storing Laravel Users on Disk in Flat-Files'
excerpt: 'Let me demonstrate how simple it is to get a flat-file `User` model going in your Laravel application.'
published_at: 2021-03-28T11:00:00+00:00
---
**I'm tired of generic SQL databases.** I've become infactuated with flat-file systems where content and data is stored on disk and persisted between environments, whether that be an SQLite database that powers my application or plain Markdown files.

That is one of the main reasons why I built [Orbit](https://github.com/ryangjchandler/orbit) - a flat-file "database" driver for Laravel's Eloquent ORM.

The main idea is that all of your content and data is stored inside of a "content" file but can still be used through a normal Eloquent `Model`, just like it would with a MySQL or Postgres database.

## The `User` model

To start using Orbit, you'll need to install the Composer package in your Laravel application.

```bash
composer require ryangjchandler/orbit
```

Orbit operates and bootstraps a model via the `Orbit\Concerns\Orbital` trait. This can be added to your `Model` class like this:

```php
use Orbit\Concerns\Orbital;

class User extends Model
{
    use Orbital;
}
```

This is all you need to do for the model to be "usable", but for it to function like a normal `User`, there are a couple of extra steps.

## The `schema` method

Just like a model that's hooked up to a MySQL database, you should define a `schema`. This is what Orbit will use to determine what content is available in your flat-files and what should be accessible from the model.

It's essentially an "up" migration, written as part of your model's definition:

```php
class User extends Model
{
    use Orbital;

    public static function schema(Blueprint $table)
    {

    }
}
```

Laravel provides a `users` table migration as standard, so we can take that existing migration and copy it into the `schema` method:

```php
class User extends Model
{
    use Orbital;

    public static function schema(Blueprint $table)
    {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
    }
}
```

> Orbit will automatically add the `created_at` and `updated_at` columns to this schema if your `Model` class needs timestamps.

And that's all there is to it. **Really!**

If you were to open up a `tinker` session and type `User::create([...])`, you would see a new `content/users` directory in your application, as well as a new `1.md` file.

## Customising the primary key

One thing that I like to do with these flat-file models is use a more descriptive "key" as the primary key. In the case of the `User` model, that's most likely going to be the `email` since it's always going to be unique.

To do this in Orbit, all you need to do is change the `$primaryKey` or overwrite the `getKeyName` method.

```php
class User extends Model
{
    use Orbital;

    protected $primaryKey = 'email';

    public static function schema(Blueprint $table)
    {
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
    }
}
```

Now, when you create a new `User`, the file name will be the same as the `email` making it really easy to see which users already exist.

> Changing the primary key of a model will affect the foreign and local columns for your relationships. For example, if you use `email` column as your `User` model's primary key, Laravel will guess that the foreign column name is `user_email` on the related model when using `belongsTo` relation. You can change this by specifying the column names when you define the relationship.

## Sign off

If you're interested in Orbit and want to find out more, check out the [GitHub repository](https://github.com/ryangjchandler/orbit).

Thanks for reading this post!


text:
---
number: 296
title: Spooky Web Dev Stories — Part 2
date:<PHONE_NUMBER>713
url: https://traffic.libsyn.com/syntax/Syntax296.mp3
---

In this episode of Syntax, Scott and Wes are back for another episode of spooky web dev stories — listener-submitted stories about web dev gone wrong.

## LogRocket - Sponsor
LogRocket lets you replay what users do on your site, helping you reproduce bugs and fix issues faster. It's an exception tracker, a session re-player and a performance monitor. Get 14 days free at [logrocket.com/syntax](https://logrocket.com/syntax).

## Netlify - Sponsor
Netlify is the best way to deploy and host a front-end website. All the features developers need right out of the box: Global CDN, Continuous Deployment, one click HTTPS and more. Hit up [netlify.com/syntax](https://netlify.com/syntax) for more info.

## Show Notes

03:28 - Jack Rhysider Story

06:28 - Dirty Dicks JSON

08:23 - CMS Disaster

10:58 - Oh No Hotel

11:19 - FTP

12:19 - Push Notification Hell

13:16 - DVD Nightmare

15:15 - Bad Words Again

16:23 - Mo Money

17:01 - Bass Ackwards

18:17 - Taxi Coding

19:36 - Bad Env

21:30 - Login As

21:50 - Email Subscribers Plugin

22:33 - 1 in 300 Chance of the C-Word

24:24 - Production Target

26:12 - A Happy SEO Ending

28:26 - Just Oof

29:48 - I've Fallen and I Can't Get Up

30:54 - Crypto

32:34 - rm -rf

33:42 - Never Deploy on Fridays

35:31 - Million Dollar Scramble

36:22 - Deleting Production

37:11 - 500,000 Concurrent Problems

39:14 - Deleting a Government Website

40:36 - You Ruined the Surprise!

45:23 - Mr. D Hole

46:48 - One Expensive Race Condition

48:43 - Yikes

51:11 - Always Be Closing

51:44 - Adidas - All Day I Delete A Site

## Links
* [@JackRhysider](https://twitter.com/JackRhysider)
* [Darknet Diaries Podcast](https://darknetdiaries.com/)
* [ExpressionEngine](https://expressionengine.com/)
* [#ghosts](https://twitter.com/search?q=%23ghosts)
* [chefkoch.de](http://chefkoch.de/)
* [Sendgrid](https://sendgrid.com/)
* [Magento](https://magento.com/)
* [Evite](https://www.evite.com/)

## ××× SIIIIICK ××× PIIIICKS ×××
* Scott: [Fastify](https://www.fastify.io/)
* Wes:
  * [🇨🇦 Mr Chefer Meat Thermometer](https://amzn.to/3kgQLt6)
  * [🇺🇸 Mr Chefer Meat Thermometer](https://amzn.to/3j9NURD)

## Shameless Plugs
* Scott: [Level Up Pro](https://www.leveluptutorials.com/pro) - Sign up for the year and save 25%!
* Wes: [All Courses](https://wesbos.com/courses/) - Use the coupon code 'Syntax' for $10 off!

## Tweet us your tasty treats!
* [Scott's Instagram](https://www.instagram.com/stolinski/)
* [LevelUpTutorials Instagram](https://www.instagram.com/LevelUpTutorials/)
* [Wes' Instagram](https://www.instagram.com/wesbos/)
* [Wes' Twitter](https://twitter.com/wesbos)
* [Wes' Facebook](https://www.facebook.com/wesbos.developer)
* [Scott's Twitter](https://twitter.com/stolinski)
* Make sure to include [@SyntaxFM](https://twitter.com/SyntaxFM) in your tweets

repository: barrymcgee/Syntax

path: /shows/296 - spooky.md

branch_name: refs/heads/master

filename: 296 - spooky.md

gha_language: JavaScript

repo_name: barrymcgee/Syntax


text:
For bugs or installation issues, please provide the following information.
The more information you provide, the more likely people will be able to help you.

## Environment info
Operating System:

Compiler:

Package used (Python/R/Scala/Julia):

MXNet version:

Or if installed from source:

MXNet commit hash (`git rev-parse HEAD`):

If you are using python package, please provide

Python version and distribution:

If you are using R package, please provide

R `sessionInfo()`:

## Error Message:
Please paste the full error message, including stack trace.

## Minimum reproducible example
if you are using your own code, please provide a short script that reproduces the error.

## Steps to reproduce
or if you are running standard examples, please provide the commands you have run that lead to the error.

1.
2.
3.

## What have you tried to solve it?

1.
2.
3.

repository: huangzehao/incubator-mxnet-bk

gha_language: Python

repo_name: huangzehao/incubator-mxnet-bk


text:
---
metaTitle: "Microsoft SQL Server - Sequences"
description: "Create Sequence, Use Sequence in Table, Insert Into Table with Sequence, Delete From & Insert New"
---

# Sequences

## Create Sequence

```sql
CREATE SEQUENCE [dbo].[CustomersSeq]
AS INT
START WITH 10001
INCREMENT BY 1
MINVALUE -1;

```

## Use Sequence in Table

```sql
CREATE TABLE [dbo].[Customers]
(
    CustomerID INT DEFAULT (NEXT VALUE FOR [dbo].[CustomersSeq]) NOT NULL,
    CustomerName VARCHAR(100),
);

```

## Insert Into Table with Sequence

```sql
INSERT INTO [dbo].[Customers]
       ([CustomerName])
 VALUES
       ('Jerry'),
       ('Gorge')

SELECT * FROM [dbo].[Customers]

```

**Results**

|CustomerID|CustomerName
|---|---|---|---
|10001|Jerry
|10002|Gorge

## Delete From & Insert New

```sql
DELETE FROM [dbo].[Customers]
WHERE CustomerName = 'Gorge';

INSERT INTO [dbo].[Customers]
       ([CustomerName])
 VALUES ('George')

SELECT * FROM [dbo].[Customers]

```

**Results**

|CustomerID|CustomerName
|---|---|---|---
|10001|Jerry
|10003|George

repository: haifenghuang/generate

repo_name: haifenghuang/generate


text:
title: git --set-commit-id
slug: git-set-commit-id
date: 2010-12-14 14:04:51+00:00

People often complain that git's commit ids are too hard to remember and that they prefer the sequential ones generated by inferior version control systems.

Stock git doesn't have an option to pick the commit id for a commit; this seems like a grave omission.  I've prepared a patch which offers git commit --set-commit-id.

For example, everyone knows that the base commit in a repository should have a low number:

$ git init
Initialized empty Git repository in ./.git/
$ git add -A
$ git commit --set-commit-id 0000000 -a -m "Base."
Searching:  46% (12593/26843), done.
[master (root-commit) 0000000] Base.
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 myfile

If you've already messed up your repository, a handy fixing script is provided:

$ git lg
* fe5e2ee - (HEAD, master) work, work, work, it's all I do
* a2c1ec8 - work, work, work
* e580e5e - work, work
* a6ad5ee - work
* 0000000 - base
$ sequentialise.sh 0000000 6
Stopped at a6ad5ee... work
Searching: 39% (10468/26843), done.
[detached HEAD 0000010] work
 1 files changed, 1 insertions(+), 0 deletions(-)
Stopped at e580e5e... work, work
Searching:  174% (46706/26843)
[...]
$ git lg
* 0000040 - (HEAD, master) work, work, work, it's all I do
* 0000030 - work, work, work
* 0000020 - work, work
* 0000010 - work
* 0000000 - base

Much more usable!  This example repository is available for inspection.  gitweb doesn't show the commit ids on the log screen, but you can mouse-over and see them in the URLs.

Needless to say, this takes "a while".  sequentialise.sh defaults to 5 digits, i.e. enough for a million commits, and is reasonably fast on modern hardware.  6 digits is rather less tolerable.

repository: FauxFaux/blog

repo_name: FauxFaux/blog


text:
The "userservice" package
========================

This package provides components you can use to implement user authentication. This is not an "out-of-the-box" package.
In order to use this package, you will have to develop some components on your side. This package will provide utility functions
to log a user, to know whether a user is logged or not, .... This package does not provide any way to store or retrieve users from your database. This is up to you.

The package contains these classes and interfaces:

- A UserService class: this is the main class. It can be used to login a user, to logout the user, to know whether a user is logged or not, etc...
- A UserServiceInterface interface: most libraries relying on the "userservice" will rely on this interface. If the default
  UserService class does not meet your requirements, you can develop your own "userservice" instance that will implement the UserServiceInterface
  interface.
- The UserService class will require a Data Access Object to access your database. The DAO is not part of this package,
  therefore, you will have to provide it. Your DAO will need to extend the UserDaoInterface interface.
- Finally, objects returned by your UserDao class will implement the UserInterface interface.

The one thing you must remember when using the "userservice" package is this: You provide the "userservice" package with a DAO that will help
it to access your database, and the userservice will help you manage your users login/logout in return.

> Installation of UserService : [installation](usersserviceInstallation.md)

gha_language: PHP


text:
# Title
No Test Environments

## Relationships
[CertiK Whitepaper](https://certik.foundation/whitepaper)

## Description
There are no test environments provided in the project's repository.

## Remediation
N/A

## References
* [CertiK.io](https://certik.io)

repository: cybercrimeshield/SWC-registry

repo_name: cybercrimeshield/SWC-registry


text:
---
name      : New Feature or Enhancement
about     : Request for a New Feature or Enhancement
title     :
labels    : enhancement
assignees : ''

---
## Overview
[NOTE]: # ( Give a BRIEF summary of your the new feature or enhancement )
[NOTE]: # ( Please create one issue per feature/enhancement )

## Details
[NOTE]: # ( Describe the feature in simple points, or in a paragraph )
1.
2.
3.

## Outcome/Advantage
[NOTE]: # ( Tell us what you expect to happen )

## Context
[NOTE]: # ( Give us any additional information you may have. )

repository: ZenithClown/API-Logger

repo_name: ZenithClown/API-Logger


text:
# What is git?

Git is a revision control system.  It provides us with a way to track the full
lifecycle of a text-based document (primarily Ruby code files) one change at a time.

## How do you track revisions to a text file?

Say you have a twenty line text file and someone wants to make a copy edit to a single word
in line three.  They can make that change on their machine and then "commit" the change via git
with an informative message like 'corrected spelling of banana'.  That commit can then be shared with
the rest of the team (often by being reshared through GitHub) so that everyone else can apply that
change and see the updated file on their machines.

The interesting thing about how Git works is that you don't have to send a full copy of the file
along with each change, you just send the change itself and Git stitches it together to show the difference.

I'll need to update this with a lot more information some day.

### What does that look like?
Let's use wikipedia as an accessible example.  Say there's a wikipedia page out there with 500 lines and you decide to add one more line to it.  How does wikipedia track the addition of that one line?  How can editors review the edit history of the document?  Here's a picture of the actual wikipedia version comparison screen.  It's fairly git-like:
![wikipedia diff](http://i.imgur.com/VDM6fFL.png)

## What's a pull request?
TBD

repository: railsdog/tech-training

gha_language: Ruby

repo_name: railsdog/tech-training


text:
# opensource-and-cloud-deployment

Open Source powers most of the internet, through  the existence of linux, python, angular and bootstrap to name a few.

With some Open Source projects having in excess of 70,000 contributors, it is necessary for there to be methods and standards in order for these projects to succeed.

We will be looking at how we can best manage and deploy the great tools we have at our disposal in order to achieve better collaboration, less technical conflicts and ultimately a more inclusive project.

This talk will also look at one of the biggest drivers in Open Source: it’s Community, and how best to be part of this Community both from a contributor and maintainer perspective.

![Screenshot](https://user-images.githubusercontent.com/624760/58321740-e6ea3600-7e16-11e9-9a7a-d175bf2624a9.png)

## Notes

* Open source
    * What is it
    * Its not just about code
    * Why contribute to open source
    * Contributor tips
    * What are the benefits to a project maintainer
    * Maintainer tips
* Cloud
    * Setup pipeline and deploy hello world first
    * Feature branching (gitflow)
    * Commit strategy + Changelog generation
    * Merging strategies
    * Automation - automated testing (cypress), extra tools like static code analysis / mutation testing
    * CI (run all automation)
    * CD (each feature/epic branch gets it own environment, protect main branches (GitHub code owner file), delete feature/epic environments after PR is closed)
    * Serverless / Firebase much easier (cost model is very effective), AWS / GCP more infrastructure as code is required


text:
Instead of having to give up on handling all of our renders on the front-end, if using React, we have access to a wonderful tool called React Router. I’ll go into some of the details pertaining to React Router Web, though their documentation is quite helpful and covers three areas—core, web, native.
[https://reactrouter.com](https://reactrouter.com)

To use React Router you will need to start with installing it through `npm install react-router` or `yarn add react-router`, depending on what you have chosen to use. Once installed, you will want to use the syntax `import {...} from “react-router-dom”` in the App component and other components that you need access to its tools; filling in the bracketed space with whichever named parameter you are interested in using.

There are five key tools in React Router (without getting into those that use React Hooks):
* Router
* Route
* Switch
* Redirect
* Link

# Router

One of the initial and key components to client-side routing with React Router is the router itself. There is a low-level router simply called `Router`, but they generally recommend using one of the high-level routers. There are five such routers—`BrowserRouter`, `HashRouter`, `MemoryRouter`, `NativeRouter`, `StaticRouter`—each with their own use case. The most commonly used router is BrowserRouter. On importing one of these routers, the common syntax is to rename them as Router (`import { BrowserRouter as Router } from “react-router-dom”`).

BrowserRouter will, as the documentation describes, “keep your UI in sync with the URl”. Meaning that as a user clicks on links on types paths in the address bar, the router will use the history to determine what is the current path and from there it interacts with the route to determine what to render.

# Route

Route is the heart of this client-side routing. Through this you can dictate what components should be rendered for the user based on which Route paths match the URL. It should be kept in mind though that route paths are inclusively matching. As such, when navigating to **“/login”** the root path **“/”** would also match and render.

In order to avoid this, one can use `exact path` to avoid unintended rendering. As an example:
```
<Router>
	<div>
		<Route exact path=“/”>
			<HomeComponent />
		</Route>
		<Route path=“/login”>
			<LoginComponent />
		</Route>
	<div>
</Router>
```

# Switch

When working with a collection of routes the Switch can be quite useful. The Switch changes the behaviour of Routes from inclusive rendering to exclusive rendering. Meaning that the first Route in the Switch that matches the URL will render the associated components instead of all Routes that match the URL rendering their components. As such, one should always be mindful of listing paths that accept slugs after defined paths.

# Redirect

The Redirect is a very useful tool when needing to decide what component to render after a Route has been matched. This can be particularly useful when trying to manage page access to components that require a user to be logged in or have other various permissions. The core syntax is `<Redirect to=“/some/page”>`, but is often used in conjunction with a ternary operator. Based on the truthiness of some variable, such as isLoggedIn or isAdministrator, you can determine whether to render a component or redirect the user to a different URL. The example provided in the React Router documentation is:
```
<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>
```

# Link

The Link allows you to provide hyperlinks to other routes in your application without triggering a full page load. It instead allows you to wrap text or html with the link and have the URL of the user’s browser change triggering a check for matching Route paths and rendering specific components as necessary.

As a small aside, if you are using a `Nav.Link` object from React Bootstrap, you will want to include `as={Link}` as an attribute of Nav.Link. For example, `<Nav.Link as={Link} to="/">Home</Nav.Link>`.

# Future plans

React Router as it currently is will continue to be available to all, but there are notable plans in the future for this wonderful bit of code. It is outlined on this page:
[https://reacttraining.com/blog/reach-react-router-future/](https://reacttraining.com/blog/reach-react-router-future/)

The general gist of it is that React Router will be merging with its lightweight sibling Reach Router going forward, and they plan to be leveraging the more recent technology of React Hooks in their new API.

Hope this was a helpful overview and let me know in the comments below of any other helpful insights to React Router.

extension: markdown


text:
ADVimba
===========
An
[EPICS](http://www.aps.anl.gov/epics)
[areaDetector](https://cars.uchicago.edu/software/epics/areaDetector.html)
driver for cameras from
[Allied Vision](http://www.alliedvision.com) using their Vimba SDK.
These include GigE and USB-3 cameras.

Allied Vision purchased Prosilica, and this driver is a replacement for the ADProsilica driver
that is based on the PvAPI SDK, and which is now obsolete.

ADVimba is based on [ADGenICam](https://areadetector.github.io/master/ADGenICam/ADGenICam.html),
which handles many of the details of mapping GenICam features to EPICS records.

Additional information:
* [Documentation](https://areadetector.github.io/master/ADVimba/ADVimba.html).
* [Release notes and links to source and binary releases](RELEASE.md).

repository: ISISComputingGroup/EPICS-areaDetector

gha_language: C

gha_license_id: NOASSERTION

repo_name: ISISComputingGroup/EPICS-areaDetector


text:
# Component: Light

* This component defines a light as a well encapsulated object.
* A light device is defined by:
    * ledc timer which is used to control the pwm channels of light
    * mode of the ledc timer
    * frequency of the ledc timer
    * pwm channel number of the light
    * bit number of the ledc timer
* A light device can provide:
    * iot_light_channel_regist function to add channel to corresponding channel id
    * iot_light_duty_write function to set the duty of corresponding channel and it support setting duty directly or gradually
    * iot_light_breath_write function to set the corresponding channel to breath mode and breath period can be set
    * iot_light_blink_starte and iot_light_blink_stop function to make some of channels to blink in appointed period. Note that if any channel works in blink mode, all the other channels would be turned off.

* To use the light device, you need to:
    * create a light object returned by iot_light_create()
    * regist the light channels according the channel number by iot_light_channel_regist()
    * To free the object, you can call iot_light_delete to delete the button object and free the memory.

### NOTE:
> If any channel(s) work(s) in blink mode, all the other channels would be turned off. iot_light_blink_stop() must be called before setting any channel to other mode(write duty or breath).

repository: espressif/esp-iot-solution

repo_name: espressif/esp-iot-solution


text:
> note: this is incomplete documentation and is more of a brain dump whilst herald is being developed...

## Processes

**Herald** tags samples and experiments with _processes_. Processes included "sequencing", "basecalling", "pipeline X" etc.

### Adding a process

> note: the UI will only be updated if the process is for samples (I've left the experiment processes harcoded in the UI for now)

1. add a process definition in `processes.go`

This file is located in the source code (`src/data/processes.go`). An example function call is:

```go
createProcessDefinition("mypipeline", []string{"sequence", "basecall"}, false, true)
```

This will create a process called `mypipeline` which depends on the processes `sequence` and `basecall` being complete.

## Message passing

### dependencies

Herald uses [Google Protocol Buffers v3](https://developers.google.com/protocol-buffers) for serialisation and [gRPC](https://grpc.io/) for message passing. Current versions:

- Protobuf 3.6.1
- gRPC 1.16.1

### protocol buffers

The protocol buffer definitions are stored under `protobuf/*.proto`.

#### updating the schema

If editing the `*.proto` files, the Go bindings will need to be re-compiled. For example, the bindings for the sample message:

```
protoc -I=protobuf --go_out=plugins=grpc:src/ protobuf/*.proto
go generate
sh build-osx.sh
```

To update the MinKNOW api:

```
protoc --go_out=plugins=grpc:src/ont_rpc -I protobuf/minknow/rpc protobuf/minknow/rpc/rpc_options.proto
```

## Database

Sample records are stored via [bitcask db](https://pkg.go.dev/git.mills.io/prologic/bitcask), which is currently hardcoded to live in `/tmp/db`.

Sample records are stored in a keyvalue store, where the label is the key and the sample protobuf message is the value.

repository: will-rowe/herald

gha_language: Go

repo_name: will-rowe/herald


text:
## CRUD

A minimalistic relational database library for Go.

<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc-refresh-toc -->
**Table of Contents**

- [Install](#install)
- [Initialize](#initialize)
- [Define](#define)
- [Create](#create)
- [CreateAndRead](#createandread)
- [Read](#read)
    - [Reading multiple rows:](#reading-multiple-rows)
    - [Scanning to custom values:](#scanning-to-custom-values)
- [Update](#update)
- [Delete](#delete)
- [Contexts](#contexts)
- [Transactions](#transactions)
- [Logs](#logs)
- [Custom Queries](#custom-queries)
- [What's Missing?](#whats-missing)
- [LICENSE](#license)

<!-- markdown-toc end -->

## Install

```bash
$ go get github.com/azer/crud/v2
```

## Initialize

```go
import (
  "github.com/azer/crud/v2"
  _ "github.com/go-sql-driver/mysql"
)

var DB *crud.DB

func init () {
  var err error
  DB, err = crud.Connect("mysql", os.Getenv("DATABASE_URL"))
  err = DB.Ping()
}
```

## Define

```go
type User struct {
  Id int `sql:"auto-increment primary-key"`
  FirstName string
  LastName string
  ProfileId int
}

type Profile struct {
  Id int `sql:"auto-increment primary-key"`
  Bio string `sql:"text"`
}
```

CRUD will automatically convert column names from "FirstName" (CamelCase) to "first_name" (snake_case) for you. You can still choose custom names though;

```go
type Post struct {
  Slug string `sql:"name=slug_id varchar(255) primary-key required"`
}
```

If no primary key is specified, CRUD will look for a field named "Id" with int type, and set it as auto-incrementing primary-key field.

##### Create & Drop Tables

`CreateTables` takes list of structs and makes sure they exist in the database.

```go
err := DB.CreateTables(User{}, Profile{})

err := DB.DropTables(User{}, Profile{})
```

##### Reset Tables

Shortcut for dropping and creating tables.

```go
err := DB.ResetTables(User{}, Profile{})
```

##### SQL Options

CRUD tries to be smart about figuring out the best SQL options for your structs, and lets you choose manually, too. For example;

```go
type Tweet struct {
 Text string `sql:"varchar(140) required name=tweet"`
}
```

Above example sets the type of the `Text` column as `varchar(140)`, makes it required (`NOT NULL`) and changes the column name as `tweet`.

Here is the list of the options that you can pass;

* Types: `int`, `bigint`, `varchar`, `text`, `date`, `time`, `timestamp`
* `auto-increment` / `autoincrement` / `auto_increment`
* `primary-key` / `primarykey` / `primary_key`
* `required`
* `default='?'`
* `name=?`
* `table-name=?`

If you'd like a struct field to be ignored by CRUD, choose `-` as options:

```go
type Foo struct {
 IgnoreMe string `sql:"-"`
}
```

## Create

Simply pass a struct. It can be pointer or not.

```go
user := &User{1, "Foo", "Bar", 1}
err := DB.Create(user)
```

## CreateAndRead

Create a row, and read it back from the DB. The values of the struct you passed get resetted to whatever the corresponding DB row has. In the other words, `CreateAndRead` creates, and reads. So you got fields generated by the DB scanned to your struct, like ID.

Make sure passing a pointer.

```go
user := User{
  FirstName:"Foo"
}

err := DB.CreateAndRead(&user)

user.Id
// => 123
```

## Read

You can read single/multiple rows, or custom values, with the `Read` method.

 Here is an example;

```go
db := DB.WithContext(context.Background())
```

## Transactions

Use `Begin` method of a `crud.DB` instance to create a new transaction. Each transaction will provide you following methods;

* Commit
* Rollback
* Exec
* Query
* Create
* CreateAndRead
* Read
* Update
* Delete

```go
tx, err := DB.Begin(context.Background())

err := tx.Create(&User{
  Name: "yolo"
})

err := tx.Delete(&User{
  Id: 123
})

err := tx.Commit()
```

CRUD generates an ID for each transaction, and uses that for logging queries and the state of the transactions. You can override transaction IDs in some use cases such as having same IDs and ID field keys with your Rest framework generating request IDs;

```go
tx.Id = requestId
tx.IdKey = "requestId"
```

## Logs

If you want to see crud's internal logs, specify `crud` in the `LOG` environment variable when you run your app. For example;

```
$ LOG=crud go run myapp.go
```

## Custom Queries

````go
result, err := DB.Query("DROP DATABASE yolo") // or .Exec
````

## Running Tests

```bash
DATABASE_URL="?" go test ./...
```

## What's Missing?

* **Hooks:** I'm not sure if this is needed, but worths to consider.
* **Foreign Keys:** [*](https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html)
* **Make UTF-8 Default:** Looks like the default charset is not UTF8.

## LICENSE

[MIT License](https://github.com/azer/crud/blob/master/COPYING)

repository: azer/crud

gha_license_id: WTFPL

repo_name: azer/crud


text:
# *Simple Linear Regression*

## What is Simple Linear Regression?
  - Simple linear regression is a statistical method for obtaining a formula to predict
values of one variable from another where there is a causal relationship between the
two variables

### Plot of the Dataset for Simple Linear Regression
   - `Below is the raw data.`

     X            | Y
     ------------ | -------------
     1            | 1
     2            | 3
     4            | 3
     3            | 2
     5            | 5

   - `Below is a simple scatter plot of x versus y.`
   ![Plot of the Dataset](/image/Dataset-SLR.png)
   - We can see the relationship between x and y looks kind of linear. As in, we could probably draw a line somewhere diagonally from the bottom left of the plot to the top right to generally describe the relationship between the data.
   - This is a good indication that using linear regression might be appropriate for this little dataset.
   - With `simple linear regression` we want to model our data as follows:
                                   `y = B0 + B1 * x`

 ### Plot Predictions as a Line With Our Data

   - `After making predictions we can plot these predictions as a line with our data. This gives us a visual idea of how well the line models our data.`
   ![Plot Dataset](/image/SLR-Model.png)

 ### Conclusion
 - Linear Regression is an algorithm that every Machine Learning enthusiast must know and it is also the right place to start for people who want to learn Machine Learning as well.

 ### References:
   - https://machinelearningmastery.com


text:
# CheckIT Scripts

Scripts used to set up and build CheckIT are included within the scripts directory. The purpose of each script is described below:

* `jenkins/jenkins-build-checkit.sh` - Builds the CheckIT project on a Jenkins server.
* `clean-and-install-dependencies.sh` - Removes any existing bower_components and node_modules folders and
installs bower and npm dependencies.
* `inject-private-info.sh` - Injects private information into the `client/src/app.config.json` and
`server/config/default.json` files.
* `setup.sh` - Installs all dependencies, prompts user for credentials needed for CheckIT, and injects private inforomation.

***Note:*** If you are running the setup.sh script on macOS, you must install `gsed` using homebrew for the `sed` command to function properly. If you are running the setup.sh script on linux, you do not need to install any additional programs. `gsed` can be installed with homebrew using the following command: `brew install gnu-sed --with-default-names`.

## Jenkins Deployment

The jenkins directory contains scripts used to build CheckIT on a Jenkins server. In order to build CheckIT on a Jenkins server, first create a project on a Jenkins server and configure the build to use the `https://github.com/PointSource/checkit-blueoak.git` repository (or your own forked repository) in the "Source Control Management" section. To configure the build, click "Add build step" followed by "Execute shell". Then add the code below to the execute shell text box. Add the necessary credentials and save the build configuration. CheckIT is now ready to be built.

```
# This script is meant to be a template to copy into an "Execute shell" on Jenkins
# Copy the contents below and add the credentials

# Disables logging to the console
set +x

# Add credentials below
API="ENTER_API_HOST"
ALLOWED_ORIGINS="ENTER_ALLOWED_ORIGINS"
GOOGLE_CLIENT_ID="ENTER_GOOGLE_CLIENT_ID"
MONGODB_HOST="ENTER_MONGODB_HOST"
MONGODB_PORT="ENTER_MONGODB_PORT"
MONGODB_DB="ENTER_MONGODB_DB"
MONGODB_USERNAME="ENTER_MONGODB_USERNAME"
MONGODB_PASSWORD="ENTER_MONGODB_PASSWORD"
DECRYPTION_PASSWORD="ENTER_DECRYPTION_PASSWORD"
GOOGLE_DOMAIN="ENTER_GOOGLE_DOMAIN"
SERVICE_ACCOUNT_EMAIL="ENTER_SERVICE_ACCOUNT_EMAIL"
SERVICE_ACCOUNT_KEY_FILE_PATH="ENTER_SERVICE_ACCOUNT_KEY_FILE_PATH"
APP_ACCOUNT_EMAIL="ENTER_APP_ACCOUNT_EMAIL"
NOTIFICATION_METHOD="ENTER_NOTIFICATION_METHOD"
# Remove the HIPCHAT_DOMAIN variable if not using HipChat notifications
HIPCHAT_DOMAIN="ENTER_HIPCHAT_DOMAIN"
# Remove the HIPCHAT_ROOM_ID variable if not using HipChat notifications
HIPCHAT_ROOM_ID="ENTER_HIPCHAT_ROOM_ID"
# Remove the HIPCHAT_AUTH_TOKEN variable if not using HipChat notifications
HIPCHAT_AUTH_TOKEN="ENTER_HIPCHAT_AUTH_TOKEN"

# Enter the company domains to restrict users who can access CheckIT.
# To allow any user with a Gmail account, leave this field alone.
# To restrict users, enter the domain in the format below, replace "example.com" with your domain:
#     "\"companyDomains\":\ \[\"example.com\"\]"
# Multiple domains can be used and must be separated by a comma.
COMPANY_DOMAINS="\"companyDomains\":\ \[\]"

# Enables logging to the console
set -x

# Changes into the absolute path of the directory assigned to the build as a workspace in Jenkins
cd $WORKSPACE
# Runs the build-checkit.sh script on Jenkins
. ./scripts/jenkins/jenkins-build-checkit.sh
```


text:
---
layout: default
---

  Hi, my name is [Kurt Espinosa](about/). I finished my PhD at the National Centre for Text Mining of the University of Manchester under the supervision of Sophia Ananiadou and  Riza Batista-Navarro.

  I dream that one day computers will be able to *read* and *understand* text just like we do. I believe that is possible only if computers can learn to *represent* concepts, which is primarily the core of my [research](research/).

  In my spare time, I enjoy creating small and fun [projects](projects/) or [writing](blog/) about ideas that fascinate me. If you share any of my interests, feel free to <a<EMAIL_ADDRESS>me.


text:
# PigBot, the Bleu Pigs Discord mascot
PigBot is the official Discord bot and mascot of the Bleu Pigs ScriptBuilder community

## What does PigBot do?
Well, it's simple!

### Provide useful commands/services to the Bleu Pigs community

Currently, we only have one bot: RoVer (The open-source version of the ROBLOX-Discord user verification bot). Bleu Pigs, however, was built with being a one stop shop in mind for all ScriptBuilder users. To acheive this goal, PigBot will provide a variety of commands and services from:

  - Auto Roles
  - Semi-automatic identity verification + join process (requires interaction with verification)
  - Developer Announcements (ROBLOX Devforum public section)
  - and other awesome features!

 With PigBot, Staff get access to powerful tools which allow them to make their best possible judgement. Features include:

  - Provide an Action Log for the entire community (Highlighting Joins/Leaves, Moderation actions, Deleted messages, etc)
  - Automate the new member verification process
  - Provide administrative functionality through the bot (kick, ban commands)
  - Automatic vote ignition for Elite Pig status (takes in requirements)
  - Vote System (for voting on various actions/decisions)

### Provide APIs and Services to the ScriptBuilder community:
Because we <3 ScriptBuilders here at Bleu Pigs, we want to provide the community with powerful APIs for making their projects come to life. Some of the services we'll provide include:

  - Online Script Editor
  - Script-based Data Storage
  - Universal Cross Chat for ScriptBuilders (powered by Discord)

And the list goes on! PigBot is a continously on-going project that is built for the ScriptBuilder community. We highly encourage contributions, as any assistance to the project would be greatly appreciated.

repository: reinitialized-archived/PigBot

repo_name: reinitialized-archived/PigBot


text:
# scroll-behavior [![Travis][build-badge]][build] [![npm][npm-badge]][npm]

Scroll management for [`history`](https://github.com/ReactTraining/history).

**If you are using [React Router](https://github.com/reactjs/react-router), check out [react-router-scroll](https://github.com/taion/react-router-scroll), which wraps up the scroll management logic here into a router middleware.**

[![Codecov][codecov-badge]][codecov]
[![Discord][discord-badge]][discord]

## Usage

```js
import createHistory from 'history/lib/createBrowserHistory';
import withScroll from 'scroll-behavior';

const history = withScroll(createHistory());
```

## Guide

### Installation

```
$ npm i -S history
$ npm i -S scroll-behavior
```

### Scroll behaviors

### Basic usage

Extend your history object using `withScroll`. The extended history object will manage the scroll position for transitions.

### Custom scroll behavior

You can customize the scroll behavior by providing a `shouldUpdateScroll` callback when extending the history object. This callback is called with both the previous location and the current location.

You can return:

- a falsy value to suppress the scroll update
- a position array such as `[0, 100]` to scroll to that position
- a truthy value to get normal scroll behavior

```js
const history = withScroll(createHistory(), (prevLocation, location) => (
  // Don't scroll if the pathname is the same.
  !prevLocation || location.pathname !== prevLocation.pathname
));
```

```js
const history = withScroll(createHistory(), (prevLocation, location) => (
  // Scroll to top when attempting to vist the current path.
  prevLocation && location.pathname === prevLocation.pathname ? [0, 0] : true
));
```

### Scrolling elements other than `window`

The `withScroll`-extended history object has a `registerScrollElement` method. This method registers an element other than `window` to have managed scroll behavior on transitions. Each of these elements needs to be given a unique key at registration time, and can be given an optional `shouldUpdateScroll` callback that behaves as above.

```js
const history = withScroll(createHistory(), () => false);
history.listen(listener);

history.registerScrollElement(
  key, element, shouldUpdateScroll
);
```

The `registerScrollElement` method returns an `unregister` function that you can use to explicitly unregister the scroll behavior on the element, if necessary. In general, you will not need to do this, as `withScroll` will perform all necessary cleanup on removal of the last history listener.

[build-badge]: https://img.shields.io/travis/taion/scroll-behavior/master.svg
[build]: https://travis-ci.org/taion/scroll-behavior

[npm-badge]: https://img.shields.io/npm/v/scroll-behavior.svg
[npm]: https://www.npmjs.org/package/scroll-behavior

[codecov-badge]: https://img.shields.io/codecov/c/github/taion/scroll-behavior/master.svg
[codecov]: https://codecov.io/gh/taion/scroll-behavior

[discord-badge]: https://img.shields.io/badge/Discord-join%20chat%20%E2%86%92-738bd7.svg
[discord]: https://discord.gg/0ZcbPKXt5bYaNQ46

repository: LucaGuida/SolidityRegistry

repo_name: LucaGuida/SolidityRegistry


text:
---
title: SFC Spec
sidebar: auto
---

# Vue Single-File Component (SFC) Spec

## Intro

A `*.vue` file is a custom file format that uses HTML-like syntax to describe a Vue component. Each `*.vue` file consists of three types of top-level language blocks: `<template>`, `<script>`, and `<style>`, and optionally additional custom blocks:

``` vue
<template>
  <div class="example">{{ msg }}</div>
</template>

<script>
export default {
  data () {
    return {
      msg: 'Hello world!'
    }
  }
}
</script>

<style>
.example {
  color: red;
}
</style>

<custom1>
  This could be e.g. documentation for the component.
</custom1>
```

`vue-loader` will parse the file, extract each language block, pipe them through other loaders if necessary, and finally assemble them back into an ES Module whose default export is a Vue.js component options object.

`vue-loader` supports using non-default languages, such as CSS pre-processors and compile-to-HTML template languages, by specifying the `lang` attribute for a language block. For example, you can use Sass for the style of your component like this:

``` vue
<style lang="sass">
  /* write Sass! */
</style>
```

More details can be found in [Using Pre-Processors](./pre-processors.md).

## Language Blocks

### Template

- Each `*.vue` file can contain at most one `<template>` block at a time.

- Contents will be extracted and passed on to `vue-template-compiler` and pre-compiled into JavaScript render functions, and finally injected into the exported component in the `<script>` section.

### Script

- Each `*.vue` file can contain at most one `<script>` block at a time.

- The script is executed as an ES Module.

- The **default export** should be a Vue.js [component options object](https://vuejs.org/v2/api/#Options-Data). Exporting an extended constructor created by `Vue.extend()` is also supported, but a plain object is preferred.

- Any webpack rules that match against `.js` files (or the extension specified by the `lang` attribute) will be applied to contents in the `<script>` block as well.

### Style

- Default match: `/\.css$/`.

- A single `*.vue` file can contain multiple `<style>` tags.

- A `<style>` tag can have `scoped` or `module` attributes (see [Scoped CSS](./scoped-css.md) and [CSS Modules](./css-modules.md)) to help encapsulate the styles to the current component. Multiple `<style>` tags with different encapsulation modes can be mixed in the same component.

- Any webpack rules that match against `.css` files (or the extension specified by the `lang` attribute) will be applied to contents in the `<style>` blocks as well.

### Custom Blocks

Additional custom blocks can be included in a `*.vue` file for any project specific needs, for example a `<docs>` block. `vue-loader` will use the tag name to look up which webpack loaders should be applied to the contents of the section. The webpack loaders should be specified in the `loaders` section of `vue-loader` options.

For mode details, see [Custom Blocks](./custom-blocks.md).

### Src Imports

If you prefer splitting up your `*.vue` components into multiple files, you can use the `src` attribute to import an external file for a language block:

``` vue
<template src="./template.html"></template>
<style src="./style.css"></style>
<script src="./script.js"></script>
```

Beware that `src` imports follow the same path resolution rules to webpack module requests, which means:

- Relative paths need to start with `./`
- You can import resources from npm dependencies:

``` vue
<!-- import a file from the installed "todomvc-app-css" npm package -->
<style src="todomvc-app-css/index.css">
```

`src` imports also work with custom blocks, e.g.:

``` vue
<unit-test src="./unit-test.js">
</unit-test>
```

## Syntax Highlighting / IDE Support

Currently there is syntax highlighting support for the following IDE/editors:

- [Sublime Text](https://github.com/vuejs/vue-syntax-highlight)
- [VS Code](https://marketplace.visualstudio.com/items?itemName=octref.vetur)
- [Atom](https://atom.io/packages/language-vue)
- [Vim](https://github.com/posva/vim-vue)
- [Emacs](https://github.com/AdamNiederer/vue-mode)
- [Brackets](https://github.com/pandao/brackets-vue)
- [JetBrains IDEs](https://plugins.jetbrains.com/plugin/8057) (WebStorm, PhpStorm, etc)

Contributions for other editors/IDEs are highly appreciated! If you are not using any pre-processors in Vue components, you can also get decent syntax highlighting by treating `*.vue` files as HTML in your editor.

## Comments

Inside each block you shall use the comment syntax of the language being used (HTML, CSS, JavaScript, Jade, etc). For top-level comments, use HTML comment syntax: `<!-- comment contents here -->`

repository: mediocrity-z/webpack-study

repo_name: mediocrity-z/webpack-study


text:
---
layout: page
title: About
permalink: /about/
---
### Who am i
As everyone, i'm still trying to figure out this answer but for now, i'm Matthew, a self-taught web developer currently living in Brazil, big fan of open source world and the Clojure language.

### My journey into programming
I started my journey around 3 years ago *(January of 2017)*, simply because i had a lot of interest in learning more about tech. Deeply fell in love with programming specially for the web.

In 2018 i discovered functional programming and Lisp by reading[ HTDP](https://htdp.org/2019-02-24/). I had found a language that i loved and i was excited to use it professionally, turns out that the practical modern lisp was: **Clojure**!

This year (2019) i dedicated full time to learn clojure and back-end for the web.

I'm here to share my knowledge and my journey with everyone!

### Contact

The fastest way to get in touch with me is via Telegram: **@crytek**

Other ways of contacting me:

Email<EMAIL_ADDRESS>Twitter: **@MatthewLisp**


text:
# Quizzical
![MIT License](https://img.shields.io/github/license/Ryan778/Quizzical?style=flat-square)
![GitHub release (latest by date)](https://img.shields.io/github/v/release/Ryan778/Quizzical?style=flat-square)

**© 2021 Ryan Zhang**

Quizzical is my submission to FBLA's 2021 Coding and Programming event.

![Quizzical Landing Page on Windows 11](docs/readme/landing.png)

This readme file provides technical documentation on how to build/run Quizzical from source code, as well as instructions on extending Quizzical's functionality. For help on the application itself, use the in-app [Quizzical Help Pages](#quizzical-help-pages) instead.

## Technical Background
Quizzical is built using the open source [Electron](https://www.electronjs.org/) framework, allowing it to run on all major desktop operating systems (Windows, Linux, and MacOS) with equivalent functionality. [Electron Forge](https://www.electronforge.io/) is used to handle development and builds.

[NodeJS](https://nodejs.org) is required as a development dependency because of this, but users do not need it installed on their machines when running production builds as it's packaged into the app.

## Core Features
### Running Quizzical
Production builds can be run by directly launching the executable.

Development builds can by run using `npm start` in the app directory. If development dependencies are not yet installed, they can be installed using `npm install`.

*Note: NodeJS v12 or later is required for development.*

### Building Quizzical
Quizzical comes with a `make` command to turn Quizzical into a production build (that can run on its own, without external dependencies).

You can build Quizzical using `npm run make`.

### Quizzical Help Pages
End user help is available in the interactive help menu, accessible using the "Help" button in the toolbar. Questions are categorized by topic, and users can click on common questions to recieve more information in a separate page.

By placing the help option in the toolbar, users can access the help menu no matter where they are in the application.

## Advanced Features
### Modifying Questions
Questions are stored in a plain text file located under `src/questions.txt`, which is loaded into the application's memory upon startup. This makes it extremely easy to add, edit, or delete questions from the application. You can even make it about something completely unrelated to FBLA!

Question information is written in a semicolon delimited format, with the first "column" denoting the question type. For example, a multiple choice question begins with `mc`. Refer to the table below for all quesiton types:

|Type|Description|
|-|-|
|mc|Multiple Choice|
|tf|True/False|
|sa|Short Answer|
|o|Ordering|
|n|Numerical|

After the question type, write out the question text, another semicolon, and then the answer to the question. In the case of multiple choice questions, additional options can be listed (again, semicolon delimited) after the answer. Quizzical will shuffle the answer options, so don't worry that the correct answer is always first in the file!

#### Example
Let's break down the first question in the questions.txt file:

`mc;Which state was the first FBLA chapter chartered in?;Tennessee;Virginia;California;Delaware`

The first "column" tells us that this is a multiple choice question. This is followed by the question itself (*Which state was the first FBLA chapter chartered in?*) and then the answer (*Tennessee*). Lastly, additional (incorrect) multiple choice options are listed - all separated by semicolons (*Virginia;California;Delaware*).

In Quizzical, this question would render like this:

![Visual depiction of the above example question](docs/readme/question1.png)

### Extending Quizzical
All significant portions of code are well documented to make extending Quizzical easy. Here's a list of important files to be aware of when modifying the application:

- Questions are stored in `src/questions.txt`. Refer to the section above for more details.
- Per Electron convention, the bulk of the code is written in the renderer script, located under `src/window.js`. This file is responsible for nearly everything you see in the window, and all its functions are documented to make extending/modifying easy.
- The backend, "privileged" script is located under `src/index.js`. This code is responsible for lower-level functionality such as creating the application window, displaying the menu bar, and showing system dialogs. The code here is minimal (but still documented) as it has full application-level permissions (i.e., arbitrary filesystem reading/writing).
- The Vue template is in `src/index.html`. On its own the index.html file is merely the "backbone" of the application, as it is the scripts that make it functional. Nonetheless, comments are included with a brief description of each page and what said page does.
- CSS is stored in `src/index.css` and is responsible for the aesthetics.
- Third party libraries are stored under the `src/lib` directory.
- The interactive help menu is its own separate "app", located under the `src/help` directory. It is designed to run standalone - separate from the rest of the application.

## Post NLC Addendum
Quizzical placed **1st** at Colorado's State Leadership Conference (SLC) and **7th** at FBLA's National Leadership Conference (NLC). For reference, the 2021 NLC Topic has been included below.

> **Develop an original computer program to randomly generate a five-question FBLA quiz from a database. The program must complete a minimum of the following tasks:**
>
> - Have at least 50 questions in the database with the ability to see correct answers
> - Include at least 4 types of questions (i.e. multiple choice, T/F, fill-in-the-blank, matching, and dropdown, etc.).
> - Inform the user which questions were correctly answered
> - Calculate the total correct on the five-question quiz
> - Generate a printable report on quiz results
> - Data must be stored persistently. Storage may be in a relational database, a document-oriented NoSQL database, flat text files, flat JSON, or XML files.
> - All data entry must be validated with appropriate user notifications and error messages including the use of required fields

repository: remzh/Quizzical

repo_name: remzh/Quizzical


text:
# UtiliArm

FreeRTOS code for ESP-IDF to control my personal robotic arm.

See documentation here: https://bmleedy.github.io/utiliArm/index.html

repository: bmleedy/utiliArm

repo_name: bmleedy/utiliArm


text:
# Contributing Guide

First of all, thanks for contributing!. Before contributing please read the [CODE_OF_CONDUCT](CODE_OF_CONDUCT.md) and [search the issue tracker](issues); your issue may have already been discussed

## Reporting Issues

  - If you think you've found an issue with the extension, you can open a Github issue.

  - Feel free to reach out to us at sumodojo.slack.com.

## Development
* Fork the [repo](https://github.com/SumoLogic/sumologic-lambda-extensions) 🎉
* Create a feature branch. ☕
* Run unit tests and confirm that it passes. ⚡
* Commit your changes. 📝
* Rebase your local changes against the master branch. 💡
* Create new Pull Request.

## Building
* To install build related dependencies use below command

  `env GO111MODULE=off go install <package>`.
* Always use `go mod tidy` to clean up unwanted dependencies.
* To generate the binary use below command

  ```go build -o target/extensions/sumologic-extension lambda-extensions/sumologic-extension.go```

## Unit Testing

    go test sumoclient_test.go -v

## Deploying the layer
  * Change the *AWS_PROFILE* environment variable.
  * Update the layer version in *config/version.go*.
  * Use below command for creating and deploying layer

        cd scripts/
        sh zip.sh

## Integration Testing (Manual)

Add your layer to lambda by following [docs](https://help.sumologic.com/03Send-Data/Collect-from-Other-Data-Sources/Collect_Logs_from_AWS_Lambda_using_Lambda_Extension) and test the function manually. Confirm that logs are coming to Sumo Logic.


text:
# tfstate - Easily get output from terraform state

`tfstate` is a convenience tool that can output terraform output as a JSON
object from any supplied terraform state. The terraform state references are
loaded using a uri format.

## Key Features

* Supports Remote State (S3 only at the moment)
* Uses a default 60 second cache to reduce network overhead and increase speed of query

## CLI Usage

Get the terraform output for the state stored in an s3 bucket `mybucket` and the
path `infrastructure/production`:

    $ tfstate --state-uri=s3://mybucket/infrastructure/production

## Library Usage

Usage in a library is also equally as simple:

    import tfstate

    state_uri = "s3://mybucket/infrastructure/production"

    output = tfstate.get(state_uri)

The `output` object is simply a dictionary of the terraform output

repository: chadbean/tfstate

repo_name: chadbean/tfstate


text:
# NeoFly-Mission-creator
A little tool you can use with Microsoft Flight Simulator career addon: NeoFly to create missions in order to fly with your friends.

This package require the .Net framework (min version: 4.7.2)

## How it works.
 - First backup your database just in case. (I didn't faced any db issue, but if Neofly updates its missions database model it could lead to some corruption)
 - Simply unzip the folder and launch the tool with "NeoFly Mission Creator.exe" file.
 - Link your db file location into the "Database File" field if not located in the default C:\ProgramData\NeoFly\common.db
 - Copy the same info as your mate mission (departure, arrival, distance, mission Type...)
 - Click "Create Mission"
 - You can then simply hit the "search" button once again on NeoFly UI mission tab and the new mission appears.

When flying a tourrist or emergency mission you have to enter the Target latitude and target longitude (your mate can see them on the bing map into Neofly UI)

## If you meet any trouble.
If you meet any trouble please create an issue on the GitHub Project Page.

## License
This software is licensed under Apache license 2.0

## If you like my work, I like coffee :)
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=G3F8XX7KXN6QQ)


text:
Ti=Sanction of the {_operator} in the event of failure to fulfil its obligations

sec=In the event of failure by the {_operator} to comply with one of its obligations, duly noted according to one of the methods described below, the {_operator} shall have thirty (30) days to remedy such failure. Failing this, the poor performance by the {_operator} of its obligations shall be resolved by sanctions decided by the {_Parties} in accordance with Article 1217 of the Civil Code.

=[G/Z/ol/Base]

repository: CommonAccord/Cmacc-Org

gha_language: CSS

repo_name: CommonAccord/Cmacc-Org


text:
---
layout: docs
title: 'WhereClause.notEqual()'
---

_Since v1.2_

### Syntax

```javascript
table.where(indexOrPrimKey).notEqual(key)
```

### Parameters

indexOrPrimKey: String	Name of an index or primary key registered in Version.stores()

key	Key to compare with. The key MUST be a Number, String, Date or Array instance. Booleans are not accepted as valid keys

### Return Value

[Collection](/docs/Collection/Collection)

### Remarks

Queries the collection for all valid values that does not match given value. Note that you will only find values that are valid indexedDB keys.

Given the following data:

```
{ id: 1, shoeSize: 9 }
{ id: 2, shoeSize: 10 }
{ id: 3, shoeSize: 11 }
{ id: 4 }
{ id: 5, shoeSize: null }
{ id: 6, shoeSize: "abc" }
{ id: 7, shoeSize: false }
{ id: 8, shoeSize: ["a","b","c"]}
```
And the following query:

```javascript
db.people.where('shoeSize').notEqual(10).each(function(x) {
    console.log("Found: " + JSON.stringify(x));
});
```
We get the following result:

```
Found: "{id:1,shoeSize:9}"
Found: "{id:3,shoeSize:11}"
Found: "{id:6,shoeSize:\"abc\"}"
Found: "{id:8,shoeSize:[\"a\",\"b\",\"c\"]}"
```

Note that number 4 was not included in the result because it didn't have a valid `shoeSize` key so it's not indexed. A valid key is a key of type string, number, Date or Array<string \| number \| Date>. Booleans, null and undefined are NOT valid indexedDB keys.

branch_name: refs/heads/gh-pages


text:
---
layout:     post
title:      "S.O.L.I.D in Ruby"
date:       2018-11-26 12:00:00
author:     "Marcy"
header-img: "img/post-bg-2015.jpg"
catalog: true
tags:
    - Ruby on Rails
    - Ruby
    - OOP
    - Design Patterns
---

> "Ruby is the best object-oriented language.. if you use it in the right way"

For a long time working in the Ruby world, primarily working on Ruby on Rails projects, I found many projects do not follow proper Object Oriented programming practices. Ruby, as one of the most complete OOP language, provides tons of useful features to implement OOP. In this article, I will demonstrate how to write Ruby code comply with S.O.L.I.D. And some of the common anti-patterns those violate these principles in Ruby on Rails projects.

## What is S.O.L.I.D

One the most well-known sets of OO design principles are known by an acronym, SOLID. It stands for:

- Single responsibility principle (SRP)
- Open/closed principle (OCP)
- Liskov substitution principle (LSP)
- Interface segregation principle (ISP)
- Dependency inversion principle (DIP)

Let’s take a look at each of them individually, and how you can use them to increase your Ruby code’s quality.

## Single responsibility principle (SRP)

> "A class should have one, and only one, reason to change."

Let's interpret this a little bit. This also means when there is a requirement change, the class should only make the change for the responsibility it holds (so it only has one reason to change).

#### Example

Let's look at the following example:

```ruby
class UserAuthenticator
  def authenticate(email, password)
    if matches?(email, password)
     do_some_authentication
    else
      raise NotAllowedError
    end
  end

  private
  def matches?(email, password)
    user = find_from_db(:user, email)
    user.encrypted_password == encrypt(password)
  end
end
```

The AuthenticatesUser class is responsible for authenticating the user as well as knowing if the email and password match the ones in the database. It has two responsibilities, and according to the principle it should only have one. Let’s extract one:

```ruby
class UserAuthenticator
  def authenticate(email, password)
    if PasswordMatcher.new(email, password).matches?
     do_some_authentication
    else
      raise NotAllowedError
    end
  end
end

class PasswordMatcher
  def initialize(email, password)
     @email = email
     @password = password
  end

  def matches?
    user = find_from_db(:user, @email)
    user.encrypted_password == encrypt(@password)
  end
end
```

#### Why

This makes change much harder!

- The more responsibilities a class has, the more likely we need to change the code in the class when there's requirement change.
- Code for one responsibility may couple to other responsibilities. Changing code for one feature may break other feature.

#### Anti-pattern: Fat Model

One of the most common anti-patterns in Rails is Fat model. In a lot of projects, I've seen developers implement business logic in the model class.

```ruby
class Account < ApplicationModel
  after_create :send_notification_email
  include ReportExportable # exports all accounts
  def signin ... end
  def register ... end
  def add_user(user) ... end
  def cancel ... end
end
```

The model then has a lot of responsibilities
- Holds data of the model record
- Handles database operations provided by ActiveRecord
- All different business logic (with methods, callbacks and concerns)

A fat model class could easily be expanded to hundreds of lines.

What we should do is to
- Use model classes as data holders and use service classes for bussiness logic
- Don't use controllers to handle business logic as it's only responsible for accepting request and returning response
- Concerns in models should only contain helpers for accessing its data.
- Callbacks should only be used for manipulating it's own data instead of doing any extra work.

```ruby
class Account < ApplicationModel
end

class SignupService
  def signup(account)
    ...
    SomeEmailSerive.send_notification_email
  end
end

def UserService
  def add_user(account, user) ... end
end

def ReportService
  def export(records) ... end
end
```

#### Anti-Pattern: Wrong way of extracting a method

We have a class `ContactPolicy` which extends `AccountResourcePolicy`

```ruby
class AccountResourcePolicy
  def show?
    user.account == resource.account
  end
end

class ContactPolicy < AccountResourcePolicy
  def show?
    return false if contact.organization != user.organization
    super
  end
end
```

And now we have another policy `DocumentPolicy` which also extends `AccountResourcePolicy`

```ruby
class ContactPolicy < AccountResourcePolicy
  def show?
    return false if contact.organization != user.organization
    super
  end
end
```

Ok now the developer may think maybe we should extract the duplicate code to a method for matching resource organization to the user's organization

```ruby
class AccountResourcePolicy
  def show?
    user.account == resource.account
  end

  protected
  def organization_matched?
    return false if contact.organization == user.organization
  end
end

class ContactPolicy < AccountResourcePolicy
  def show?
    return false unless organization_matched?
    super
  end
end

class DocumentPolicy < AccountResourcePolicy
  def show?
    return false unless organization_matched?
    super
  end
end
```

Extracting the common logic into a method does improve code reusability. However, the method should not be put into the base class as it is adding a responsibility which the base class should not be responsible for. A better approach is to create another class to handle the responsibility.

```ruby
class AccountResourcePolicy
  def show?
    user.account == resource.account
  end
end

class OrganizationMatcher
  def self.match?(user, resource)
    user.organization == resource.organization
  end
end

class ContactPolicy < AccountResourcePolicy
  def show?
    return false unless OrganizationMatcher.match?(user, resource)
    super
  end
end

class DocumentPolicy < AccountResourcePolicy
  def show?
    return false unless OrganizationMatcher.match?(user, resource)
    super
  end
end
```

## Open/closed principle (OCP)

> "You should be able to extend a classes behavior, without modifying it."

How can something be open and closed?! A class follows the OCP if it fulfills these two criteria:

- Open for extension

This ensures that the class behavior can be extended (by inheritance or composition). As requirements change, we should be able to make a new class behave in new and different ways by using the original class.

- Closed for modification

The source code of such a class is set in stone, no one is allowed to make changes to the code so that we don't need to change the code that uses this class.

#### Example

```ruby
class Report
  def body
     generate_reporty_stuff
  end

  def print
     body.to_json
  end
end
```

This code violates OCP, because if we want to change the format the report gets printed, you need to change the code of the class. Let’s change it then.

```ruby
class Report
  def body
     generate_reporty_stuff
  end

  def print(formatter: JSONFormatter.new)
     formatter.format body
  end
end
```

#### Why

This makes change much harder!

- Changing source code of exisitng classes may break clients those use this
- Adding new code becomes harder as there is no way to reuse existing code

#### How

- Make sure your code comply with SRP
- Anticipate where the change might happen. Make sure you class could adapt to the change (This is a technique for everything in software development...)

## Liskov Substitution Principle (LSP)

This one is complicated so let's talk about this in the end.

## Interface Segregation Principle

> "when a client depends upon a class that contains interfaces that the client does not use, but that other clients do use, then that client will be affected by the changes that those other clients force upon the class"

This one is simpler to demonstrate, if you have a class that has two clients (objects using it):

```ruby
class Car
  def open
  end

  def start_engine
  end

   def change_engine
   end
end

class Driver
  def drive
    @car.open
    @car.start_engine
  end
end

class Mechanic
  def do_stuff
    @car.change_engine
  end
end
```

As you can see, our Car class has an interface that’s used partially by both the Driver and the Mechanic. We can improve our interface like so:

```ruby
class Car
  attr_reader :control, :internals
end

class CarControl
  def open
  end
  def start_engine
  end
end

class CarInternals
  def change_engine
  end
  def change_wheels
  end
end

class Driver
  def drive
    @car_control.open
    @car_control.start_engine
  end
end

class Mechanic
  def do_stuff
    @car_internals.change_engine
  end
end
```

By splitting the interface into two, we can comply to the ISP.

## Dependency Inversion (DI)

> "Abstractions should not depend upon details. Details should depend upon abstractions."

Let’s go back to the first example on the OCP and change it a bit:

```ruby
class Report
  def body
     generate_reporty_stuff
  end

  def print
    JSONFormatter.new.format(body)
  end
end
```

Let's look at this example in deep. The `print` method clearly depends on the concrete class `JSONFormatter`. And the format it prints the report becomes dependent on how `JSONFormatter` prints the report.

To make this flexible, we allow the `print` method to accept a formatter. The `Report` class does not control the format anymore, but only provides the data of the report. And it does not need to know what type of formatter will be passed in to format the data. The only thing it needs to know is that the fomatter object accepts the `format` method. We call this programming to interface.

```ruby
class Report
  def body
     generate_reporty_stuff
  end

  def print(formatter)
    formatter.format body
  end
end
```

This simple example introduces an important technique in OOP - **Dependency Inversion**. Dependency inversion is relying on abstraction and programming to interface. In the above code, the `Report` class depends on a formatter object that accepts a `format` message, instead of a concrete formatter class. We could see the `formatter object that accepts a `format` message` as an interface that any concrete formatter class needs to implement. In Ruby, we don't have a concept of `interface` like java, but we could simulate the concept like this.

```ruby
class FormatterInterface
  def format
    raise NotImplementedError
  end
end

class JSONFormatter < FormatterInterface
  def format(data)
    # format data as json
  end
end
```

The `FormatterInterface` class is an abstraction of the `JSONFormatter`. And our report class is dependent on the abstraction instead of the concrete class, which makes changing the report format much more easily.

## Liskov Substitution Principle (LSP)

> "Derived classes must be substitutable for their base classes."

You may think this is easy, because we only need to make sure that the derived class is really a base class. But this is not sufficient. LSP is not only for class level but also for method level. Which means if you want to create a derived class, you need to make sure all the methods in the base class still works as expected in the derived class.

Here is an example:

```ruby
class Shape
end
class Rectangle < Shape
  def set_height ... end
  def set_width ... end
end
class Square < Rectangle
  def set_length ... end
end
```

Theoretically a square is indeed a rectangle, right? But when we implement this in code it may not be the case. A rectangle may accepts two messages `set_width` and `set_height` which allows the client to set the width and height of the rectangle with different lengths. However, for the Square class, it should only accept a `set_length` method. The `set_width` and `set_height` methods are not needed for the square. If we are forced to implement the two methods for the class, whenever we call `set_width` of a square, we have to to set its 'height' to make sure its width and height has the same length. In this case, we can clearly see that a Square class should not be extending the Rectangle class, because the behavior of the inherited methods differs.

#### Why

This breaks things!

- As the object of your new class may be used as an object of the existing classes and behave in an unexpected way.

[//]: # When we are working on the Office365 adapter, It's based on the Adapter class but it's requirement does not fully follow some of the existing logic in the adapter class. And this caused many bugs and we have to let QA find them and fix them one by one by overriding some of the methods.

#### How

- Follow SCP, OCP and ISP for your base class so your class is small, easier to understand and open for extension
- Don't make assumption on the methods in the base class if you think the behaviour might change
- Try to use Composition over Inheritance when we want to improve code reusability.

[//]: # Review policy classes (PromoPolicy and AccountResourcePolicy)

#### Anti-Pattern: Wrong way of override a method

When we override a method, remember to check if the method breaks LSP. After the method is override, it should still have the expected behaviour of the method in the base class.

Let's review `Adapter#pull_and_handle_orphaned_records`, `SyncGodBase#pull_and_handle_orphaned_records!`.

```ruby
class Adapter
  def full_sync!
    ...
    ...
    pull_and_handle_orphaned_records(...)
  end

  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    ...
    orphan_retry_ids.each do |adapters_resource_id|
      self.delegate_pull!(type_singular, AdaptersResource.find(adapters_resource_id))
    end
    # ...
    mark_missing_records_as_orphaned!(...)
  end
end

class SyncGodBase < Adapter
  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    # ...
    orphan_adapters_resources.find_each do |adapters_resource|
      adapters_resource.resource.try(:force_destroy) if adapters_resource.resource_id
      adapters_resource.destroy
    end
  end
end
```

## Some Real World examples

#### Adapter#pull_and_handle_orphaned_records

Before we move to the actual refactoring, let's think about why the adapter class is bad (We know it is bad) and why we end up with the classes.

The class was created many years ago, and when it is implemented, it probably looks like this:

```ruby
class Adapter
  def pull_organizations! ... end
  def pull_locations! ... end
  def pull_contacts! ... end
  def pull_configurations! ... end

  def full_sync!
    ...
    pull_organizations!
    pull_locations!
    pull_configurations!
    ...

    # some logic to handle orphaned records
  end
end
```

First, this obviously is a fat model that violates the SRP. We would like to turn this into a service at the very beginnning.

```ruby
class AdapterService
  def pull_organizations! ... end
  def pull...

  def full_sync!
    ...
    pull_organizations!
    ...

    # some logic to handle orphaned records
  end
end
```

Now we need some other integrations implemented, but they are provided by `Sync God` so we want to abstract a `SyncGodBaseService` will be a good idea. And the developer thought `SyncGodBaseService` should extend the `AdapterService` class.

```ruby
class SyncGodBaseService < AdapterService
  ...
end
```

So `SyncGod#full_sync!` follows most of the logic in the `full_sync!` method. However, it handles orphaned records a bit differently. So the developer decided to extract the logic for handling orphaned records in `AdapterService` to a new `pull_and_handle_orphaned_records` method. and then let `SyncGodBaseService` overrides the method. Now the method in the `Adapter` class marks adapter resources as orphan but the overriden method in `SyncGodBase` deletes the adapter resource.

```ruby
class AdapterService
  def full_sync!
    ...
    ...
    pull_and_handle_orphaned_records(...)
  end

  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    ...
    orphan_retry_ids.each do |adapters_resource_id|
      self.delegate_pull!(type_singular, AdaptersResource.find(adapters_resource_id))
    end
    # ...
    mark_missing_records_as_orphaned!(...)
  end
end

class SyncGodBaseService < AdapterService
  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    # ...
    orphan_adapters_resources.find_each do |adapters_resource|
      adapters_resource.resource.try(:force_destroy) if adapters_resource.resource_id
      adapters_resource.destroy
    end
  end
end
```

What is the issue of this approach. As we could see the behaviour of the two methods are almost totally different. This indicates the two classes violate the Liskov substitution principle (LSP). Either the `SyncGodBase` is not an `Adapter` or the `Adapter` class has implemented too much for a base class.

The problem here is in the `AdapterService`, it makes the assumption that orphaned records are handled by marking all the records as orphaned, while some other `AdapterService` may handle this in a different ways. Be caution when making assumption in the base class. Because when making assumption, you are creating a contract and the sub class may break the contract after overriding the methods.

To resolve this, we should not make the assumption in a base class. Here is a better approach:

```ruby
class AdapterService
  def full_sync!
    ...
    ...
    pull_and_handle_orphaned_records(...)
  end

  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    raise NotImplementedError
  end
end

class AdapterServiceA < AdapterService
  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    ...
    orphan_retry_ids.each do |adapters_resource_id|
      self.delegate_pull!(type_singular, AdaptersResource.find(adapters_resource_id))
    end
    # ...
    mark_missing_records_as_orphaned!(...)
  end
end

class SyncGodBaseService < AdapterService
  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    # ...
    orphan_adapters_resources.find_each do |adapters_resource|
      adapters_resource.resource.try(:force_destroy) if adapters_resource.resource_id
      adapters_resource.destroy
    end
  end
end
```

Here we have used a design pattern called *Template Pattern*. Now these classes do not violate the Liskov substitution principle (LSP).

But here is another issue, if we want to implement a `AdapterServiceB`, we will need to implement the `#pull_and_handle_orphaned_records` exactly the same to the one in `AdapterServiceA`. How could we reduce the duplicate codes accross differen classes.

The root problem is that `AdapterServiceA` and `AdapterServiceB` violate the Single Responsibility Principle (SRP). The adapter classes should not know how to find orphaned records and how to mark them as orphaned. What we could do is to extract the logics to some `OrphanedRecordHandler` classes.

```ruby
class OrphanedRecordHandler
  def handle!(type, synced_adapters_resource_ids)
    raise NotImplementedError
  end
end

class RetryAndMarkAsOrphanedRecordHandler < OrphanedRecordHandler
  def handle!(type, synced_adapters_resource_ids)
    # retry and mark orphaned records as orphaned
  end
end

class DeleteOrphanedRecordHandler < OrphanedRecordHandler
  def handle!(type, synced_adapters_resource_ids)
    # delete orphaned records
  end
end

class AdapterServiceA < AdapterService
  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    RetryAndMarkAsOrphanedRecordHandler.new.handle!(type, synced_adapters_resource_ids)
  end
end

class AdapterServiceB < AdapterService
  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    RetryAndMarkAsOrphanedRecordHandler.new.handle!(type, synced_adapters_resource_ids)
  end
end

class SyncGodBaseAdapterService < AdapterService
  def pull_and_handle_orphaned_records!(type, synced_adapters_resource_ids)
    DeleteOrphanedRecordHandler.new.handle!(type, synced_adapters_resource_ids)
  end
end
```

This example introduces another important design pattern which is the *Strategy Pattern*. Strategy Pattern uses abstraction to encaupsulate different algorithms.


text:
# MONKEY-SIMD

About
---

SIMD module / wrapper for Monkey-X. Currently C++ target and experimental JavaScript supported. Compiled with MSVC, MinGW, ARM GCC and XCode.

This module has been tested with version 85e of Monkey-X.

ARM's NEON tested on Raspberry PI 2 and iPhone 5S.

SIMD.js is still experimental technology. You can read more about it [here](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/SIMD).

Installation
---

Make a backup of the C++ native file of monkey module. It can be found at *[Monkey Directory]/modules/monkey/native/lang.cpp*.

Copy the file found on *monkey-simd/modules/monkey/native/lang.cpp* into *[Monkey Directory]/modules/monkey/native/lang.cpp*.

This modification of the lang.cpp file includes aligned memory allocations needed by SSE/AVX instructions.

If you are building a project using MinGW you should backup and replace the file *[Monkey Directory]/targets/glfw3/template/gcc_winnt/Makefile* with *monkey-simd/targets/glfw3/template/gcc_winnt/Makefile*

Important
---

The NEON code doesn't implement

*SIMD_Shuffle*

*SIMD.Sqrt*

*SIMD.Rsqrt*

To test HTML5 target you must have [Firefox Nightly Build](https://nightly.mozilla.org/). A polyfill can be enabled for unsupported browsers using the preprocessor macro **#SIMD_JS_POLYFILL = True**.

Monkey-SIMD API Spec.
---

##### Float32x4

SIMD Plain Old Data.

##### Function SIMD.MakeFloat32x4:Float32x4(x:Float, y:Float, z:Float, w:Float)

Returns a Float32x4 with the intialized x, y, z and w values.

##### Function SIMD.MakeFloat32x4Zero:Float32x4()

Returns a Float32x4 with all values initialized to zero.

##### Function SIMD.MakeFloat32x4Reverse:Float32x4(x:Float, y:Float, z:Float, w:Float)

Returns a Float32x4 with the intialized x, y, z and w values reversed.

##### Function SIMD.MakeFloat32x4One:Float32x4(x:Float)

Returns a Float32x4 with all values initialized to x.

##### Function SIMD.Set:Void(destination:Float32x4, x:Float, y:Float, z:Float, w:Float)

Sets the destination vector values to x, y, z and w.

##### Function SIMD.SetZero:Void(destination:Float32x4)

Sets the destination vector values to zero.

##### Function SIMD.SetOne:Void(destination:Float32x4, x:Float)

Sets the destination vector values to x.

##### Function SIMD.SetReverse:Void(destination:Float32x4, x:Float, y:Float, z:Float, w:Float)

Sets the destination vector values to x, y, z and w in reverse.

##### Function SIMD.Load:Void(destination:Float32x4, source:Float[])

Loads values from a Float array to a Float32x4. The size of the array must be 4 or you might get out of range index exception.

##### Function SIMD.Store:Void(destination:Float[], source:Float32x4)

Stores values from a Float32x4 into a Float array. The size of the array must be 4 or you might get out of range index exception.

##### Function SIMD.Add:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Adds two Float32x4 and stores the result in a destination vector.

##### Function SIMD.Sub:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Subtracts two Float32x4 and stores the result in a destination vector.

##### Function SIMD.Mul:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Multiplies two Float32x4 and stores the result in a destination vector.

##### Function SIMD.Min:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Evaluates the smallest vector values and stores them in a destination vector.

##### Function SIMD.Max:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Evaluates the highest vector values and stores them in a destination vector.

##### Function SIMD.Sqrt:Void(destination:Float32x4, source:Float32x4)

Evaluates the square root of a source vector and stores it at a destination vector.

##### Function SIMD.LogicAnd:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Computes a logical *AND* between to vectors and stores result in destination vector.

##### Function SIMD.LogicAndNot:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Computes a logical *AND-NOT* between to vectors and stores result in destination vector.

##### Function SIMD.LogicOr:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Computes a logical *OR* between to vectors and stores result in destination vector.

##### Function SIMD.LogicXor:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Computes a logical *XOR* between to vectors and stores result in destination vector.

##### Function SIMD.CompareEqual:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Compare equality between to vectors and stores result in destination vector.

##### Function SIMD.CompareLowerThan:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Compare lower than between to vectors and stores result in destination vector.

##### Function SIMD.CompareLowerThanOrEqual:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Compare lower than or equal between to vectors and stores result in destination vector.

##### Function SIMD.CompareGreaterThan:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Compare greater than between to vectors and stores result in destination vector.

##### Function SIMD.CompareGreaterThanOrEqual:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4)

Compare greater than or equal between to vectors and stores result in destination vector.

##### Function SIMD.GetTarget:Int()

Returns the ID of the current SIMD target. It can be SSE/AVX, ARM NEON or SIMD.js

##### Function SIMD_Shuffle:Void(destination:Float32x4, operandR:Float32x4, operandL:Float32x4, x:Int, y:Int, z:Int, w:Int)

Shuffles two vectors and stores the result in a destination vector.

repository: bitnenfer/monkey-simd

repo_name: bitnenfer/monkey-simd