text:
---
SPDX-License-Identifier: MIT
path: "/tutorials/secure-ubuntu-server-with-ferm-firewall-and-fail2ban"
slug: "secure-ubuntu-server-with-ferm-firewall-and-fail2ban"
date: "2021-12-01"
title: "Securing Ubuntu 20.04 LTS Sever with Ferm Firewall and Fail2Ban"
short_description: "This tutorial explains how to install and setup a ferm firewall and fail2ban"
tags: ["Administration", "Firewall", "Security"]
author: "Maximilian Schumacher"
author_link: "https://github.com/msch-io"
author_img: "https://avatars.githubusercontent.com/u/87988555?v=4"
author_description: "Linux System Administrator based in Germany"
language: "en"
available_languages: ["en"]
header_img: "header-2"
cta: "cloud"
---

## Introduction

In this tutorial you will learn how to secure your server by installing and setting up a firewall using Ferm and Fail2Ban. Ferm is short and means *"for easy rule making"*.

Ferm uses a script like configuration file style which enables you to easily write and manage firewall rules for iptables. For more information on the project and how to write rules please visit the [Ferm website](http://ferm.foo-projects.org).

Fail2Ban is a service which can automatically block connections from IPs on your firewall which are brute-forcing your services. In this tutorial you will learn how to secure your OpenSSH server with Fail2Ban. For more information on Fail2Ban please visit the [Fail2Ban website](https://www.fail2ban.org).

**Prerequisites**

You will need a server running Ubuntu. In this tutorial I will be using Ubuntu 20.04 LTS.

I assume that you are accessing your server via SSH over its default port (22). Within this tutorial you will need to make changes to text files on your system. If you are not familiar with using a text editor on the command line I would recommend you to start with Nano.

To open a file in Nano editor, just type `nano <filename>`

> _**NOTE:** All commands below require that you have root privileges. If you're not logged in as root user please use `sudo` in front of the commands or switch to root user before starting with `sudo su -`_

## Step 1 - Install And Configure Ferm Firewall

In this step we install Ferm and set-up the first configuration which will allow us to access the server over SSH using port 22.

### Step 1.1 - Install ferm package

```bash
apt install ferm
```

During the installation Ferm will ask you if you wan't Ferm to be enabled on startup. You can answer this question with yes.

> _**NOTE:** This step will automatically start ferm and may block all connections except SSH on port 22_

### Step 1.2 - Adjust Ferm configuration

Next we are going to setup a basic firewall. Therefore open the main Ferm configuration file with your favorite editor and replace the whole file with the following lines:

```bash
nano /etc/ferm/ferm.conf
```

```
# basic ferm firewall
domain (ip ip6) {
  table filter {

    # setup INPUT chain
    # this section handles rules for all kinds of incoming IP packages/connections
    # if you want to also allow other ports/services in future
    # you can insert further rules in this section under the last comment below
    # (see comment "ADDITIONAL INPUT RULES HERE")
    chain INPUT {
      policy DROP;

      # connection tracking
      mod state state INVALID DROP;
      mod state state (ESTABLISHED RELATED) ACCEPT;

      # allow local packet
      interface lo ACCEPT;

      # respond to ping
      proto icmp ACCEPT;

      # allow SSH connections
      proto tcp dport ssh ACCEPT;

      # ADDITIONAL INPUT RULES HERE

    }

    # setup OUTPUT chain
    chain OUTPUT {
      policy ACCEPT;
    }

    # setup FORWARD chain
    chain FORWARD {
      policy DROP;
    }
  }
}

@include ferm.d/;
```

This configuration will allow any incoming packages for SSH (port 22). Also it will allow incoming packages from established connections. Ping and local traffic is also allowed.

> _**NOTE:** This is a stateful firewall. It will use information based on connection tracking tables. Connections once marked as established will be accepted on input until the connection expires or gets closed._

### Step 1.3 - Reload firewall

Now after we setup the firewall configuration properly we can load it by restarting the Ferm service.

```bash
systemctl restart ferm
```

### Step 1.4 - Updating the firewall _(Optional for future use)_

If you need to alter your firewall configuration in future, just update the configuration file. Then use the following command to check if there are any syntax errors in your configuration before restarting the firewall:

```bash
ferm --noexec /etc/ferm/ferm.conf
```

If this command does not show any error messages, then your configuration has no syntax errors. You can now safely reload the firewall with the command above (Step 2.4).

> _**Pro-Tip:** Reloading the firewall with the following command:_ `ferm --interactive /etc/ferm/ferm.conf` _will apply the firewall rules and than ask you for confirmation. If you do not confirm (e.g. if you locked out yourself with the new firewall), Ferm will automatically rollback to the old ruleset after 30 seconds._

## Step 2 - Install and Configure Fail2Ban

In this step we will install and setup Fail2Ban and configure it to monitor failed SSH authentications and block IP addresses if there were to many failed login attempts within a certain period of time.

```bash
apt install fail2ban
```

After this, Fail2Ban is installed and by default it automatically watches the SSH service for failed authentications/logins. For more information on how to configure Fail2Ban, please refer the Fail2Ban documentation. Also this [ubuntu users article](https://wiki.ubuntuusers.de/fail2ban/) on Fail2Ban may be interesting for you.

> _**Pro-Tip:** Use the command `fail2ban-client` in order to query information about blocked IPs and also unban/ban IPs. Here are a few examples of how to use the client:_
> `fail2ban-client status sshd`
> `fail2ban-client set sshd banip <IP-Address>`
> `fail2ban-client set sshd unbanip <IP-Address>`

## Step 3 - Adjust Ferm configuration to always ensure Fail2Ban rules

As a last step we add a configuration to Ferm which wil ensure that all Fail2Ban rules are loaded, even if you restart or stop Ferm. This is required because Ferm always flushes all rules on restart and stop before adding it's own rules.

Open the file `/etc/ferm/ferm.conf` and add the following lines on TOP of the file:

```bash
nano /etc/ferm/ferm.conf
```

```
@hook flush "systemctl restart fail2ban.service";
```

Now save the file. When you restart or stop Ferm in future it will automatically restart Fail2Ban and cause it to reload it's rules into iptables.

## Conclusion

Congratulations! You just installed and configured a Ferm managed firewall and also Fail2Ban service which will now automatically block IP addresses which are trying to brute-force your servers SSH service. For more information on Ferm and Fail2Ban please refer to the articles/links mentioned above.

##### License: MIT

<!--

Contributor's Certificate of Origin

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I have
    the right to submit it under the license indicated in the file; or

(b) The contribution is based upon previous work that, to the best of my
    knowledge, is covered under an appropriate license and I have the
    right under that license to submit that work with modifications,
    whether created in whole or in part by me, under the same license
    (unless I am permitted to submit under a different license), as
    indicated in the file; or

(c) The contribution was provided directly to me by some other person
    who certified (a), (b) or (c) and I have not modified it.

(d) I understand and agree that this project and the contribution are
    public and that a record of the contribution (including all personal
    information I submit with it, including my sign-off) is maintained
    indefinitely and may be redistributed consistent with this project
    or the license(s) involved.

Signed-off-by: Maximilian Schumacher<EMAIL_ADDRESS>
-->

repository: hetzneronline/community-content

repo_name: hetzneronline/community-content


text:
## Query

The `sql.cls.Query` class is inherited by all other classes. Extending its prototype will make it available for all other kinds of statements.

```js
sql.cls.Query.prototype.execute = function() {
  var query = this.toQuery();
  sqlite3.run(query.text,query.args,function() {
  });
}
```

### .toQuery

Builds the query and returns an object with `text` and `args` properties, so you can pass to your favorite executing library.

```js
var query = queryObj.toQuery();
var text = query.text; // String
var args = query.args; // Array
```

### .toText

Builds the query by calling `.toQuery` and then replaces all `?` tokens with corresponding arguments.

```js
var text = queryObj.toText();
```

It accepts a string or a callback which can be used to quote values. Values aren't quoted by default.

```js
var text = queryObj.toText("'");
// same as
var text = queryObj.toText(function(val,idx) {
  return "'" + val + "'";
});
```

license: MIT

repository: yneves/node-bauer-sql

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: yneves/node-bauer-sql


text:
# Huddle
**Huddle** is an android app that allows a user to organize events. Imagine you're in a part of town that you don't normally visit. You have a couple of hours to spend there after your work meetings. You open up Huddle. You check out what is a cool venue around the area and check out who from your contacts' list is also close by. This app is a great way to quickly create events and have spontaneous meetups with your friends.

This is our initial wireframes: https://docs.google.com/presentation/d/1skKVUJvXC-LZcL3suBF1pVtCR_QU1Ju7DTob0NrL2ig/edit?usp=sharing

Time spent: **X** hours spent in total

## User Stories

The following **required** functionality is completed:

* [X] User can create Events
* [X] User can create events (from suggestions based on location / or of their own choosing)
(Slight issues with google maps and using google places. It had worked previously)
* [] User can pick out a radius from current location for suggestion
(We have geo fencing in place to figure close by users)
* [X] User can create an invite list for the event
* [ ] Users who accept the invite get into a group
* [X] User can get notification of invites
(we have versions of push notifications)
* [ ] User can see profile of their friends
* [X] User can search for friends to invite
* [X] User can find friends who are close to location of interest
Optionals
* [ ] User can suggest multiple events for a group
* [ ] Users in a group can select events and have almost a doodle-like poll to decide
* [ ] User can post receipts back to the app to share expenses amongst the attendees
* [ ] User can invite friends to groups (and invite friends to the app)

## Video Walkthrough

Here's a walkthrough of implemented user stories:

<img src='http://i.giphy.com/l0HlQJFNLcaRnhl7O.gif' title='Video Walkthrough' width='' alt='Video Walkthrough' />

GIF created with [LiceCap](http://www.cockos.com/licecap/).

## Notes

Describe any challenges encountered while building the app.

## Open-source libraries used

- [Android Async HTTP](https://github.com/loopj/android-async-http) - Simple asynchronous HTTP requests with JSON parsing
- [Picasso](http://square.github.io/picasso/) - Image loading and caching library for Android

## License

    Copyright 2016 [name of copyright owner]

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

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

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

repository: AndroidHuddle/Huddle

gha_language: Java

repo_name: AndroidHuddle/Huddle


text:
# Recon SDK Samples

For more information, see [Sample Apps Overview](http://www.reconinstruments.com/developers/develop/sample-apps-overview/)

The following projects are included in this folder:

**ActivityStatusDemo** - receive broadcasts on what type of sport activities are being performed, and what their status is

**BluetoothLEDemo** - search for and connect to BLE servers using Androids BLE API introduced in API level 18

**CameraSample** - basic camera app, demonstrating viewfinder and use of camera for pictures and video

**ConnectivityDemo** - allows an app to download and upload files/images from the web (using HTTP Requests) via a paired smartphone

**DemoCompass** - uses the HeadingService to provide the device’s yaw, pitch, and roll in order to determine the position of a user’s head in real time

**ExternalSensorDemo** - demonstrates listening and connecting to external sensors (ANT+ and BLE)

**GlanceDemo** - detect when a user is looking at (or away from) Jet’s screen. Also included is removal detection, which allows your apps to detect when a user removes or puts on their Jet

**KeyInputSample** - demonstrates how to receive key input

**MetricsDemo** - sets up a listener to receive metric data (recieves data such as altitude, distance, grade etc.)

**MyFirstReconApp** - sample app that includes all Recon dependencies and demonstrates some basic functionality

**NotificationDemo** - shows how to create the two basic types of system notifications - passive and interactive

**ReconUIExamples** - demonstrates how to use the various UI elements, themes and styles used by Recon apps, including carousels, dialogs, lists, etc.

repository: alexmcroberts/sdk

repo_name: alexmcroberts/sdk


text:
# Tuple

Tuples are inductive types (see chapter [Inductive Classes](class_inductive.md)
for details). The module `core` defines the tuple type in the following
manner.

    B: ANY

    class
        TUPLE[A,B]
    create
        tuple(first:A, second:B)
    end

Since tuples are used frequently there are some shorthands. `(A,B)` is a
shorthand for `TUPLE[A,B]` and `(a,b)` is a shorthand for `tuple(a,b)`.

`(A,B,C)` is parsed as `(A,(B,C))` and `(a,b,c)` is parsed as `(a,(b,c))`.

There are the functions `first` and `second` to extract the first and the
second element of a tuple.

    first(t:(A,B)): A
            -- The first element of the tuple 't'.
        -> inspect
               t
           case (a,_) then
               a

    second(t:(A,B)): A
            -- The second element of the tuple 't'.
        -> inspect
               t
           case (_,b) then
               b

Since the type `TUPLE` has only one constructor the inspect expressions for
pattern matching need only one case.

The compiler adds an equality function and an inheritance from `ANY` for all
inductive types automatically.

In order to access elements of n-ary tuples, the `first` and `second`
functions have to be applied iteratively. Examples:

    (a,b,c).first          =    a
    (a,b,c).second         =    (b,c)
    (a,b,c).second.first   =    b
    (a,b,c).second.second  =    b

    ((a,b),c).first        =    (a,b)
    ((a,b),c).first.first  =    a
    ((a,b),c).first.second =    b
    ((a,b),c).second       =    c

<!---
Local Variables:
mode: outline
coding: iso-latin-1
outline-regexp: "#+"
End:
-->

repository: andyepx/alba-lang-description

repo_name: andyepx/alba-lang-description


text:
# Replace a provisioned user's information

## Table of contents

1. [Docs](#docs)
1. [Quick start](#quick-start)
1. [Inputs](#inputs)
1. [Outputs](#outputs)

## Docs

Original documentation: https://developer.github.com/v3/scim/#replace-a-provisioned-users-information

Replaces an existing provisioned user's information. You must provide all the information required for the user as if you were provisioning them for the first time. Any existing user information that you don't provide will be removed. If you want to only update a specific attribute, use the [Update a user attribute](https://developer.github.com/v3/scim/#update-a-user-attribute) endpoint instead.

As shown in the following example, you must at least provide the required values for the user: `userName`, `name`, and `emails`.

**Warning:** Setting `active: false` removes the user from the organization, deletes the external identity, and deletes the associated `:scim_user_id`.

## Quick start

```yaml
- uses: maxkomarychev/octions/octions/scim/replace-provisioned-user-information@master
  id: my_step_id
  with:
    token: <token value>
    org: <org value>
    scim_user_id: <scim_user_id value>
- name: Print outputs
  run: |
    echo ${{ steps.my_step_id.outputs.id }}
    echo ${{ steps.my_step_id.outputs.number }}
    echo ${{ steps.my_step_id.outputs.status }}
```

## Inputs

| Name | Is required | Description |
|---|---|---|
|token|true|Token to authenticate the request
|org|true|org parameter
|scim_user_id|true|scim_user_id parameter
|file_output|false|Path to store full output of the action
|custom_outputs|false|Custom outputs to create for step. This has to be YAML multiline string literal `custom_outputs: \|<newline> output_name:path.in.result`

## Outputs

| Name | Description |
|---|---|
|id|`id` field of the response (if exists)|
|number|`number` field of the response (if exists)|
|status|HTTP status of underlying API call|

repository: maxkomarychev/octions

gha_language: JavaScript

gha_license_id: MIT

repo_name: maxkomarychev/octions


text:
# Installation

## Prerequisites

Before proceeding make sure you have [Docker Desktop](https://docs.docker.com/get-docker/) installed on your system. This is fairly straightforward but differs depending on which operating system you use.

If you would like to add Spree to your existing Ruby on Rails application, please [follow this guide instead](../advanced/existing_app_tutorial.md) \(for advanced users\).

### Windows

Windows users will need to [install the Linux subsystem](https://docs.microsoft.com/en-us/windows/wsl/install-win10) to proceed.

## Installation

1. Download [Spree Starter](https://github.com/spree/spree_starter/archive/main.zip)
2. Unzip it
3. Rename `spree_starter-main` directory as you please
4. Run `bin/setup` in said directory
5. Wait for the commands to execute \(it can take around 2-3 minutes\)

## Hello, Spree Commerce

You now have a functional Spree application after running only a few commands!

To stop the webserver, hit `Ctrl-C` in the terminal window where it's running.

### Connecting to the API

Your API server is up and running.[ Download our Open API doc](https://raw.githubusercontent.com/spree/spree/master/api/docs/v2/storefront/index.yaml) and [import it to Postman](https://learning.postman.com/docs/integrations/available-integrations/working-with-openAPI/) to start playing around. Your backend server URL is `http://localhost:4000` so to grab the Products List you can use:

```bash
curl --request GET \
  --url http://localhost:4000/api/v2/storefront/products \
  --header 'Content-Type: application/json'
```

We recommend checking out our [API reference](https://api.spreecommerce.org/) for more details.

### Logging Into the Admin Panel

The next thing you'll probably want to do is to log into the admin interface. Use your browser window to navigate to [http://localhost:3000/admin](http://localhost:3000/admin). You can log in with the username<EMAIL_ADDRESS>and password `spree123`.

Upon successful authentication, you should see the admin screen:

![](../.gitbook/assets/admin_panel_978-2x%20%281%29.jpg)

Feel free to explore some of the Admin Panel features that Spree has to offer and to verify that your installation is working properly.


text:
# Tutorial 1

## Single VM Resource Manager Deployment

The YAML templates in this directory describe a simple deployment of a
single VM into a resource group.

## Usage

Make sure your azure client is logged in, and configured for Azure Resource
Manager mode:

$ azure login
$ azure config mode arm

From the current directory, run `make` to create the JSON files, or
`make deploy` to create them and deploy them to Azure.

$ azure group create myresourcegroup westus
$ make
$ make deploy RG=myresourcegroup

## Overview

Deploying an Azure VM into a Resource Manager group actually results in a
number of infrastructure resources being created:

1. The Group itself
2. A local storage account for the group
2. A virtual network
3. A number of virtual subnets attached to that network
4. A number of virtual NICs attached to those subnets
5. Finally, a VM to which one of those NICs are attached

For small deployments, this is a lot of work. At scale, all this groundwork
really starts to pay dividends.

### Create the Resource Group

Creating the resource group is quick and easy:

```bash
$ azure group create rg-01 northeurope

```

*Hint*: Use `azure location list` to see the names of the available locations.

### Start your template

First order of the template is the metadata and skeleton layout.  A template
skeleton looks like this:

YAML:

```yaml

$schema: "$schema: http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#"
contentVersion: "<IP_ADDRESS>"
parameters: {}
variables: {}
resources: []
outputs: {}
```

JSON:

```json
"$schema": "$schema: http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "<IP_ADDRESS>",
"variables": {},
"parameters": {},
"resources": [],
"outputs": []
```

### Set your variables

For this template, there are a few values that need to be used over and over
again.  We're going to create them as variables:

```yaml
variables:
  location: "[resourceGroup().location]"
  apiVersion: "2015-06-15"
  adminUserName: "[parameters('adminUserName')]"
  adminPassword: "[parameters('adminPassword')]"
```

You'll notice that we're referencing the template function parameters() in
that last bit. No worries, we'll get to that in just a bit.

### Create your resources

#### Local Storage Account

Storage accounts are where the disks, file shares, and other stored data
of a resource group are kept.

Storage names have to be uniqiue across an account, so we'll be lazy and use
automatic name generation to take care of this.

First, we create a variable to store the name of the storageAccount:

```yaml
variables:
  newStorageAccountName: "[concat('storage', uniqueString(resourceGroup().id))]"
  storageAccountType: Standard_LRS
```

The storage account type has been set to "Standard_LRS".  The possible types
are:

* Standard_LRS
* Standard_ZRS
* Standard_GRS
* Standard_RAGRS
* Premium_LRS

For pricing, see the [Azure Storage Pricing documentation][storage_pricing].

This uses two new functions:

* `concat`: Like python's `string.join`
* `uniqueString()`: a hash made from the supplied parameter, in this case
  `resourceGroup().id`

The resulting name will be something like `storageabexxyxasdf`.

Second, we create the resource definition under `resources:` in our template:

```yaml
resources:
  - type: "Microsoft.Storage/storageAccounts"
    name: "[variables('newStorageAccountName')]"
    apiVersion: "[variables('apiVersion')]"
    location: "[variables('location')]"
    properties:
      accountType: "[variables('storageAccountType')]"
```

In theory, we could crack on now and deploy this template. Let's convert it to
JSON and give it a whirl.

Save the file as `simple-vm.yaml` and use the `compile.py` script to turn it
to JSON:

```bash
../../utils/compile.py simple-vm.yaml
Compiling simple-vm.yaml
Compiling base template:
- simple-vm.yaml -> simple-vm.json
OK
```
The resulting template looks like this:

```json

{
  "contentVersion": "<IP_ADDRESS>",
  "parameters": {},
  "outputs": {},
  "variables": {
    "adminUserName": "[parameters('adminUserName')]",
    "newStorageAccountName": "[concat('storage-', uniqueString(resourceGroup().id",
    "location": "[resourceGroup().location]",
    "apiVersion": "2015-06-15",
    "adminPassword": "[parameters('adminPassword')]"
  },
  "$schema": "$schema: http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "resources": [
    {
      "location": "[variables('location')]",
      "type": "Microsoft.Storage/storageAccounts",
      "properties": {
        "accountType": "[variables('storageAccountType')]"
      },
      "apiVersion": "[variables('apiVersion')]",
      "name": "[variables('newStorageAccountName')]"
    }
  ]
}
```
Let's give that a deploy!

```bash
$ azure group create rg-01 northeurope
$ azure group deployment create -f simple-vm.json rg-01
```

Looking in the Azure portal, you should see something like this:

![Storage Deployment Succeeded][storage_succeeded]

### Define Parameters

So far, we're referencing two parameters:

* `adminUserName`
* `adminPassword`

Defining parameters is pretty straightforward:

```yaml

parameters:
  adminUserName:
    type: string
    metadata:
      description: User name for administrator
```

[storage_pricing]:https://azure.microsoft.com/en-us/pricing/details/storage/
[storage_succeeded]:https://dl.dropboxusercontent.com/u/12268528/ehwio-azure-templates/01_simple-vm/01_simple-vm_storage.png

repository: ehwio/ehwio-azure-templates

repo_name: ehwio/ehwio-azure-templates


text:
# Application of Machine Vision for Injection Moulding Products Detection and Recognition

Python scripts for image acquisition, feature extraction, SVM algorithm training and object detection and recognition.
Final result is object contour, position and orientation.
Research resulted in professional paper [(Bazina, Marković, Pavletić, & Jurković, 2017)](#references).

## Abstract

Machine Vision is found useful in industry, especially at facilities where measuring and quality control are of key importance. Also, where there is requirement for automatic robot manipulation, Machine Vision is very valuable. This paper presents an overview of fundamental concepts related to image processing, as a basis for the application of Machine Vision. Different methods of digital image analysis and detection or recognition of objects are presented in this work paper, together with their application examples, supported by theoretical elaboration. Python programming language and the OpenCV and NumPy program packages, were used for development of software solution for detection and recognition of products, manufactured by the plastic injection molding process. The efficiency of the software solution in object recognition, contour detection, position and orientation definition is tested on a series of images, obtained with an industrial camera.

## Content

Structure:
* `grayscale_resize.py`
  * Reducing image size, converting images to grayscale and saving in .pgm
    format
* `testImage_resize.py`
  * Resizing test images
* `FLANN_ORB_match.py`
  * GUI for comparing ORB, SIFT and SURF features
  * Matching features using FLANN
  * Sliders for parameter adjustment
* obj_detector:
  * `contour_detection.py`
    * GUI and sliders for contour detection algorithm parameters adjustment
    * bilateralFilter, Canny, morphologyEx, findContours, areaThresholding
  * `detector.py`
    * Extracting and descripting features from train images, K-means clustering, constructing and saving BOVW, training and saving SVM
  * `non_maximum.py`
    * NMS (non-maximum suppression) algorithm written in pure Python according to [Tombone's Computer Vision Blog](#references)
  * `pyramid.py`
    * Image pyramid algorithm
  * `sliding_window.py`
    * Sliding window technique
* `obj_SW_IP_NMS.py`
  * Testing on test images
* `managers.py`
  * Capturing video
* `bow_vocabulary_ind.xml`
  * saved BOVW vocabulary
* `svm_data_ind.xml`
  * saved and trained SVM algorithm
* trainImages:
  * Folder containing images of two different objects for SVM training
* testImages/test2:
  * Folder containing images for SVM testing

Parts of code were written according to [(Minichino & Howse, 2015)](#references)

### Prerequisites

Following Python modules were used:
* [OpenCV](https://github.com/opencv/opencv)
* [NumPy](https://github.com/numpy/numpy)

## References

* [Bazina, T., Marković, M., Pavletić, D., & Jurković, Z. (2017, January). Application of Machine Vision for Injection Moulding Products Detection and Recognition. In 7 International Conference Mechanical Technologies and Structural Materials 2017.](http://www.strojarska-tehnologija.hr/img/pdf/MTSM2017_CONFERENCE_PROCEEDINGS.compressed.pdf)
* [Tombone's Computer Vision Blog: blazing fast nms.m](http://www.computervisionblog.com/2011/08/blazing-fast-nmsm-from-exemplar-svm.html)
* Minichino, J., & Howse, J. (2015). Learning OpenCV 3 Computer Vision with Python - Second Edition. Packt Publishing.

## License

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


text:
> [Go to French version](/fr/Règlements/Textes%20réglementaires/94/39.md)

# Order Respecting the Remission of a Portion of Certain Fees Paid in Respect of Certain Licensed Activities Under the Atomic Energy Control Act

**SI/94-39**

Enabling authorities:
- [FINANCIAL ADMINISTRATION ACT](/en/Acts/Revised%20Statutes%20of%20Canada/F/F-11.md)

Date registered: 20 April 1994

----------

His Excellency the Governor General in Council, considering that it is in the public interest to do so, is pleased hereby, on the recommendation of the Minister of Energy, Mines and Resources and the Treasury Board, pursuant to subsection 23(2.1)[*] of the [Financial Administration Act](/en/Acts/Revised%20Statutes%20of%20Canada/F/F-11.md), to make the annexed Order respecting the remission of a portion of certain fees paid in respect of certain licensed activities under the Atomic Energy Control Act.

*: S.C. 1991, c. 24, s. 7(2)

## Short Title

**1** This Order may be cited as the Atomic Energy Control Board Cost Recovery Fees Remission Order.

## Interpretation

**2** Words and expressions in this Order have the same meaning as in the AECB Cost Recovery Fees Regulations, 1993.

## Application

**3** This Order applies in respect of annual and bi-annual fees paid pursuant to the AECB Cost Recovery Fees Regulations and the AECB Cost Recovery Fees Regulations, 1993.

## Remission

**4** Remission is hereby granted of a portion of the fees that were paid but not refunded under the AECB Cost Recovery Fees Regulations and the AECB Cost Recovery Fees Regulations, 1993, so that
- **(a)** any person who pays a fee for a licence or approval, and requests the revocation of the licence or approval or requests a change in the licensed or approved activity, shall, if the Board or a designated officer approves the request pursuant to the Atomic Energy Control Regulations or the Uranium and Thorium Mining Regulations, be refunded by the Board the portion of the fee paid that is equal to the product obtained by multiplying
	- **(i)** the quotient obtained by dividing the amount of the applicable fee for the licence or approval by the number of days in the fee period
by
	- **(ii)** the number of days remaining in the fee period, beginning with the day on which the Board or a designated officer approves the revocation or change in the licensed or approved activity;
- **(b)** any person who pays an annual or a bi-annual fee for a licence or approval and the fee for the licence or approval is subsequently changed to an hourly rate fee shall be refunded by the Board the portion of the fee paid that is equal to the product obtained by multiplying
	- **(i)** the quotient obtained by dividing the amount of the fee paid by the number of days in the fee period
by
	- **(ii)** the number of days remaining in the fee period as of the day of the change to an hourly rate fee; and
- **(c)** any person who pays a fee for a licence and the fee for the licence is subsequently reduced shall be refunded by the Board the portion of the fee paid that is equal to the product obtained by multiplying
	- **(i)** the quotient obtained by dividing the difference obtained by subtracting the current fee from the fee paid, by the number of days in the fee period
by
	- **(ii)** the number of days remaining in the fee period as of the day of the reduction of the fee.

repository: TravisMadill/CanadianLaws

repo_name: TravisMadill/CanadianLaws


text:
# Command API

## Default Configuration
```
{
	name: 'Command Name',
	args: {},
	noValidate:false,
	help: 'describe args usage here',
	logLevel: 0
}
```
## Arguments and validation
the `args` option takes an Array of object with the following properties :
- type ('string,'number','object')

from v1.1.0 :
- validOptions : Array(String)
- optional : true/false

The validator will expect your command to have the exact number of required arguments, of the right type.
To skip the default(basic) validation, set `noValidate:true`. The args option is then unnecessary.

Once the Bot recognizes a command, the following happens:
- message.text is parsed into an array of arguments, double-quoted blocks count as one.
- if the noValidate option isn't set, the array is validated against the Command config
- the array is then reinjected into the original message.text property
- the command `execute(message)` method is called.

##Methods

###  Constructor
```javascript
constructor(dataStore, config) {
  this.store = dataStore;
  this.config = Object.assign(defaultConfig, config);
  this.expected = {};
}
```
The store property is a Slack Datastore, with all its helper methods, [see here for more info](https://github.com/slackapi/node-slack-sdk/blob/master/lib/data-store/memory-data-store.js)

###  ```Command.init()```

Will be called on command load, when the program starts. Defaults to doing nothing silently.

### ```Command.requestModuleComponent(to,component,method)```

Requests a component fom one of the installed modules. [See here for example use.]()
Once the module replies, the method specified will be called with the component as an argument *Command.method(component)*

###  ```Command.execute(message)```
```
{
    "id": 1,
    "type": "message",
    "channel": "C024BE91L",
    "text": ['say','"Hello world!"']
}
```
This is the structure of the message as it arrives into the `.execute()` method. The channel field is a channel or DM id.
The default execute() command is a dispatcher that does the following :
```javascript
execute(msg) {
	const args = msg.text;
	if (args.length > 1) {
		this[args.shift()](args, msg.channel);
	}else {
		this[args[0]](msg.channel);
	}
}
```
So, if it receives ['foo','bar'], it'll call the method this.foo(bar,channel). In most cases, you don't need to overwrite it, except if you have only one type of arguments (or no arguments at all), in which case the whole execution can happen in the execute() method.

## Sending messages

### ```Command.send(message, channelID [,callback])```

Sends a message to a channel or DM

### ```Command.sendMulti(message, Array(ChannelID))```

Sends a message to an array of channels or DM

## Expecting user input

In some cases, one command does not suffice and we want a series of interactions between a user and the bot (usually in the bot's DM channel)
To achieve that, we need to tell our Command to "expect" the next message in the channel to be a "reply" to whatever it is waiting for.
See (Rock, paper, scissors)[] for more details and a full example.

### ```Command.expect(channelID, obj [,replyMethodName])```

Tells the bot to expect a message in the channel specified
This message will be sent directly to the `reply()` method of the command. If you have set a `replyMethodName`, it'll go to this instead. The message WILL NOT be parsed.
In addition, you can store an object into this.expects, containing parameters necessary to the next steps.

### ```Command.reply(message)```

The expected message will arrive here, to be processed as needed. think of it as a secondary `execute()` method.

### ```Command.rmExpect(channelID)```

If the `reply()` method has parsed and validated the response message, release the expect on this particular channel.

### ```Command.isExpected(channelID)```

Retrieves the object stored in the `expect()` method

### ```Command.getExpected(channelID)```

Alias for `isExpected`

## Misc

### ```Command.blockify(text)```

Returns provided text encased in triple backticks, to be displayed as a block in Slack.

### ```Command.log(text)```

repository: xShirase/hotbot

repo_name: xShirase/hotbot


text:
# Microsoft.CodeAnalysis.Testing

## Installation

Separate packages are provided for each language and test framework.

### Azure Packages feed for prerelease packages

To reference prerelease packages, add a **NuGet.Config** file to your solution directory containing the following:

```xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="dotnet-tools" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-tools/nuget/v3/index.json" />
  </packageSources>
</configuration>
```

### MSTest

* C#
  * Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.MSTest
  * Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.MSTest
  * Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing.MSTest
  * Microsoft.CodeAnalysis.CSharp.SourceGenerators.Testing.MSTest
* Visual Basic
  * Microsoft.CodeAnalysis.VisualBasic.Analyzer.Testing.MSTest
  * Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.MSTest
  * Microsoft.CodeAnalysis.VisualBasic.CodeRefactoring.Testing.MSTest
  * Microsoft.CodeAnalysis.VisualBasic.SourceGenerators.Testing.MSTest

### NUnit

* C#
  * Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.NUnit
  * Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.NUnit
  * Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing.NUnit
  * Microsoft.CodeAnalysis.CSharp.SourceGenerators.Testing.NUnit
* Visual Basic
  * Microsoft.CodeAnalysis.VisualBasic.Analyzer.Testing.NUnit
  * Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.NUnit
  * Microsoft.CodeAnalysis.VisualBasic.CodeRefactoring.Testing.NUnit
  * Microsoft.CodeAnalysis.VisualBasic.SourceGenerators.Testing.NUnit

### xUnit.net

* C#
  * Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.XUnit
  * Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.XUnit
  * Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing.XUnit
  * Microsoft.CodeAnalysis.CSharp.SourceGenerators.Testing.XUnit
* Visual Basic
  * Microsoft.CodeAnalysis.VisualBasic.Analyzer.Testing.XUnit
  * Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.XUnit
  * Microsoft.CodeAnalysis.VisualBasic.CodeRefactoring.Testing.XUnit
  * Microsoft.CodeAnalysis.VisualBasic.SourceGenerators.Testing.XUnit

## Verifier overview

Testing analyzers and code fixes starts with the selection of a *verifier* helper type. A default analyzer and code fix
verifier types is defined for each test framework and language combination:

* `AnalyzerVerifier<TAnalyzer>`
* `CodeFixVerifier<TAnalyzer, TCodeFix>`

The verifier types provide limited functionality intended to serve the majority of analyzer and code fix tests:

1. Creating a `DiagnosticResult` representing a diagnostic reported by an analyzer
2. Executing a "basic use case" analyzer test
3. Executing a "basic use case" code fix test

Each of the verifier helper types is supported by a *test* helper type, which provides the primary implementation of
each test scenario:

* `AnalyzerTest<TAnalyzer, TVerifier>`
* `CodeFixTest<TAnalyzer, TCodeFix, TVerifier>`

### Imports

This document is written on the assumption that users will alias a verifier or code fix type to the name `Verify` within
the context of a test class.

```csharp
using Verify = Microsoft.CodeAnalysis.CSharp.Testing.XUnit.AnalyzerVerifier<SomeAnalyzerType>;
```

Users writing tests involving compiler errors may also want to import the static members of the `DiagnosticResult` type,
which provides the helper method `CompilerError` and `CompilerWarning`.

```csharp
using static Microsoft.CodeAnalysis.Testing.DiagnosticResult;
```

## Best practices

### Use code fix testing when possible

`VerifyCodeFixAsync` automatically performs several tests related to code fix scenarios:

1. Verifies that the analyzer reports an expected set of diagnostics
2. Verifies that the code fix result does not contain fixable diagnostics
3. Verifies that the code fix applied to one diagnostic at a time produces the expected output
4. Verifies that Fix All operations, when supported by the code fix provider, produce the expected output

With this library, separation of analyzer and code fix tests increases complexity and code duplication, and tends to
decrease the overall confidence in the test suite. For analyzers that provide a code fix, it is preferable to only test
with the code fix verifier for test cases where diagnostics are reported in the input source. For test cases where no
diagnostic is reported in the input source, `VerifyAnalyzerAsync` remains appropriate.

## Examples

### Basic use cases

Basic use cases are supported by static helper methods in the verifier helper types. These helpers set the following
properties:

* `TestCode`: the single input source file
* `ExpectedDiagnostics`: the diagnostics expected to appear in the input source file
* `FixedCode`: (code fix tests only) the single output source file produced by applying a code fix to the input
* Other properties are set to their default values

#### Analyzer with no diagnostics

```csharp
string testCode = @"original source code";
await Verify.VerifyAnalyzerAsync(testCode);
```

#### Analyzer without a code fix

```csharp
string testCode = @"original source code";
var expected = Verify.Diagnostic().WithLocation(1, 7);
await Verify.VerifyAnalyzerAsync(testCode, expected);
```

#### Analyzer with a code fix

```csharp
string testCode = @"original source code";
string fixedCode = @"fixed source code";
var expected = Verify.Diagnostic().WithLocation(1, 7);
await Verify.VerifyCodeFixAsync(testCode, expected, fixedCode);
```

For cases where the code fix does not always offer a fix for a diagnostic, the `fixedCode` may be set to the `testCode`
to verify that no fix is offered for the scenario:

```csharp
string testCode = @"original source code";
var expected = Verify.Diagnostic().WithLocation(1, 7);

// Verifies that the expected diagnostics are reported, but no code fix is offered
await Verify.VerifyCodeFixAsync(testCode, expected, testCode);
```

#### Compiler errors

```csharp
string testCode = @"void Method() { return }";
var expected = DiagnosticResult.CompilerError("CS0246").WithLocation(1, 23).WithMessage("; expected");
await Verify.VerifyAnalyzerAsync(testCode, expected);
```

### Advanced use cases

Advanced use cases involve the instantiation of a test helper, setting the appropriate properties, and finally calling
`RunAsync` to run the test. These steps can be combined using the object initializer syntax:

```csharp
await new CSharpAnalyzerTest<SomeAnalyzerType, XUnitVerifier>
{
    // Configure test by setting property values here...
}.RunAsync();
```

#### Additional files

```csharp
await new CSharpAnalyzerTest<SomeAnalyzerType, XUnitVerifier>
{
    TestState =
    {
        Sources = { @"original source code" },
        ExpectedDiagnostics = { Verify.Diagnostic().WithLocation(1, 7) },
        AdditionalFiles =
        {
            ("File1.ext", "content1"),
            ("File2.ext", "content2"),
        },
    },
}.RunAsync();
```

#### Overriding the default verifier behavior

💡 If the same set of steps needs to be performed for each test in a test suite, consider creating a customized set of
verifier and test types. For example, [Microsoft/vs-threading](https://github.com/Microsoft/vs-threading) uses specific
Additional Files and metadata references in most of its tests, so it uses custom verifier and test types to allow the
use of "basic use cases" for test scenarios that would otherwise be considered advanced.

```csharp
public static class CSharpAnalyzerVerifier<TAnalyzer>
    where TAnalyzer : DiagnosticAnalyzer, new()
{
    public static DiagnosticResult Diagnostic(string diagnosticId = null)
        => CSharpAnalyzerVerifier<TAnalyzer, XUnitVerifier>.Diagnostic(diagnosticId);

    public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor)
        => new DiagnosticResult(descriptor);

    public static Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
    {
        var test = new Test { TestCode = source };
        test.ExpectedDiagnostics.AddRange(expected);
        return test.RunAsync();
    }

    // Code fix tests support both analyzer and code fix testing. This test class is derived from the code fix test
    // to avoid the need to maintain duplicate copies of the customization work.
    public class Test : CSharpCodeFixTest<TAnalyzer, EmptyCodeFixProvider>
    {
    }
}

public static class CSharpCodeFixVerifier<TAnalyzer, TCodeFix>
    where TAnalyzer : DiagnosticAnalyzer, new()
    where TCodeFix : CodeFixProvider, new()
{
    public static DiagnosticResult Diagnostic(string diagnosticId = null)
        => CSharpCodeFixVerifier<TAnalyzer, TCodeFix, XUnitVerifier>.Diagnostic(diagnosticId);

    public static DiagnosticResult Diagnostic(DiagnosticDescriptor descriptor)
        => new DiagnosticResult(descriptor);

    public static Task VerifyAnalyzerAsync(string source, params DiagnosticResult[] expected)
    {
        var test = new CSharpAnalyzerVerifier<TAnalyzer>.Test { TestCode = source };
        test.ExpectedDiagnostics.AddRange(expected);
        return test.RunAsync();
    }

    public static Task VerifyCodeFixAsync(string source, string fixedSource)
        => VerifyCodeFixAsync(source, DiagnosticResult.EmptyDiagnosticResults, fixedSource);

    public static Task VerifyCodeFixAsync(string source, DiagnosticResult expected, string fixedSource)
        => VerifyCodeFixAsync(source, new[] { expected }, fixedSource);

    public static Task VerifyCodeFixAsync(string source, DiagnosticResult[] expected, string fixedSource)
    {
        var test = new Test
        {
            TestCode = source,
            FixedCode = fixedSource,
        };

        test.ExpectedDiagnostics.AddRange(expected);
        return test.RunAsync();
    }

    public class Test : CSharpCodeFixTest<TAnalyzer, TCodeFix, XUnitVerifier>
        where TAnalyzer : DiagnosticAnalyzer, new()
        where TCodeFix : CodeFixProvider, new()
    {
        public CSharpCodeFixTest()
        {
            // Custom initialization logic here
        }

        // Custom analyzers and/or code fix properties here
    }
}

```

repository: dotnet/roslyn-sdk

branch_name: refs/heads/main

gha_language: C#

repo_name: dotnet/roslyn-sdk


text:
Hi there!

We look forward to seeing you at the workshop on Wednesday 6th April. To get you thinking about the topic, please reply with answers to **one of the questions below**, by **6pm on Wednesday 30th March**.

* 1. What are three things you already know about UX?
* 2. What's one example of good UX that you've experienced? What's one example of bad UX that you've experienced?

When you reply to this message, we'll update your RSVP to Yes. **If you don't reply to this message by 6pm on Wednesday 30th March, we'll update your RSVP to No.** Eep!

branch_name: HEAD


text:
---
title: .NET Platform Guide
description: Learn about the .NET Platform.
keywords: .NET, .NET Core
author: cartermp
ms.author: ronpet
ms.date: 05/02/2017
ms.topic: article
ms.prod: .net
ms.technology: dotnet-standard
ms.devlang: dotnet
ms.assetid: bbfe6465-329d-4982-869d-472e7ef85d93
---

# .NET Platform Guide

The .NET Platform Guide provides a large amount of information about the .NET Platform.  Depending on your familiarity with .NET, you may wish to explore different sections of this guide and other sections of the .NET documentation.

## New to .NET

If you're new to .NET, check out the [Get Started](get-started.md) article.

If you prefer to have a guided tour through major features of .NET, check out the [Tour of .NET](tour.md).

You can also read about [.NET Architectural Components](components.md) to get an overview of the various "pieces" of .NET and how they fit together.

## New to .NET Core

If you're new to .NET Core, check out [Get Started with .NET Core](../core/get-started.md).

## New to .NET Standard

If you're new to .NET Standard, check out [.NET Standard Library](library.md).

## Porting .NET Framework Code to .NET Core

If you're looking to port an application, service, or some component of a system to .NET Core, check out [Porting to .NET Core from .NET Framework](../core/porting/index.md).

## Porting a NuGet package from .NET Framework to .NET Standard or .NET Core

If you're looking to port a NuGet package to .NET Standard, check out [Porting to .NET Core from .NET Framework](../core/porting/index.md).  Tooling for .NET Standard and .NET Core are shared, so the content will be relevant for porting to .NET Standard as well as .NET Core.

## Interested in Major .NET Concepts

If you're interested in some of the major concepts of .NET, check out:

* [.NET Architectural Components](components.md)
* [.NET Standard Library](library.md)
* [Native Interoperability](native-interop.md)
* [Garbage Collection](garbagecollection/index.md)
* [Base Types in .NET](base-types/index.md)
* [Collections](collections/index.md)
* [Dates, times, and time zones](datetime/index.md)
* [Asynchronous Programming](async.md)

Additionally, check out each language guide to learn about the three major .NET languages:

* [C# Guide](../csharp/index.md)
* [F# Guide](../fsharp/index.md)
* [Visual Basic Guide](../visual-basic/index.md)

## API Reference

Check out the [.NET API Reference](../../api/index.md) to see the breadth of APIs avaialable.


text:
### [CVE-2020-13632](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-13632)
![](https://img.shields.io/static/v1?label=Product&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Version&message=n%2Fa&color=blue)
![](https://img.shields.io/static/v1?label=Vulnerability&message=n%2Fa&color=brighgreen)

### Description

ext/fts3/fts3_snippet.c in SQLite before 3.32.0 has a NULL pointer dereference via a crafted matchinfo() query.

### POC

#### Reference
- https://www.oracle.com/security-alerts/cpujul2020.html
- https://www.oracle.com/security-alerts/cpuoct2020.html

#### Github
- https://github.com/garethr/snykout

repository: trickest/cve

gha_language: HTML

repo_name: trickest/cve


text:
# Build Scripts for golang-portable-windows

This tool is currently used to update [golang-portable-windows](https://github.com/josephspurrier/golang-portable-windows).

repository: josephspurrier/goappmation

path: /project/Go Portable/README.md

repo_name: josephspurrier/goappmation


text:
# combineReducers
项目的复杂程度增加，导致了需要把reducer的函数拆分成独立的部分，每个函数管理state中独立的部分，但是每个app最终只会又一个`state`树，因此需要用到`combineReducers`

```javascript

function assertReducerShape(reducers) {
  Object.keys(reducers).forEach(function (key) {
    var reducer = reducers[key];
    var initialState = reducer(undefined, {
      type: ActionTypes.INIT
    });
    // reducer的初始化数据initialState可以是null，但是不能是undefined
    if (typeof initialState === 'undefined') {
      throw new Error("Reducer \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined.");
    }

    if (typeof reducer(undefined, {
      type: ActionTypes.PROBE_UNKNOWN_ACTION()
    }) === 'undefined') {
      throw new Error("Reducer \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle " + ActionTypes.INIT + " or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null.");
    }
  });
}

/**
 * Turns an object whose values are different reducer functions, into a single
 * reducer function. It will call every child reducer, and gather their results
 * into a single state object, whose keys correspond to the keys of the passed
 * reducer functions.
 *
 * @param {Object} reducers An object whose values correspond to different
 * reducer functions that need to be combined into one. One handy way to obtain
 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
 * undefined for any action. Instead, they should return their initial state
 * if the state passed to them was undefined, and the current state for any
 * unrecognized action.
 *
 * @returns {Function} A reducer function that invokes every reducer inside the
 * passed object, and builds a state object with the same shape.
 */
function combineReducers(reducers) {
  var reducerKeys = Object.keys(reducers);
  var finalReducers = {};

  for (var i = 0; i < reducerKeys.length; i++) {
    var key = reducerKeys[i];

    if (process.env.NODE_ENV !== 'production') {
      if (typeof reducers[key] === 'undefined') {
        warning("No reducer provided for key \"" + key + "\"");
      }
    }

    if (typeof reducers[key] === 'function') {
      finalReducers[key] = reducers[key];
    }
  }

  var finalReducerKeys = Object.keys(finalReducers);
  var unexpectedKeyCache;

  if (process.env.NODE_ENV !== 'production') {
    unexpectedKeyCache = {};
  }

  var shapeAssertionError;

  try {
    assertReducerShape(finalReducers);
  } catch (e) {
    shapeAssertionError = e;
  }

  return function combination(state, action) {
    if (state === void 0) {
      state = {};
    }

    if (shapeAssertionError) {
      throw shapeAssertionError;
    }

    if (process.env.NODE_ENV !== 'production') {
      var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);

      if (warningMessage) {
        warning(warningMessage);
      }
    }

    var hasChanged = false;
    var nextState = {};

    for (var _i = 0; _i < finalReducerKeys.length; _i++) {
      var _key = finalReducerKeys[_i];
      var reducer = finalReducers[_key];
      var previousStateForKey = state[_key];
      var nextStateForKey = reducer(previousStateForKey, action);

      if (typeof nextStateForKey === 'undefined') {
        var errorMessage = getUndefinedStateErrorMessage(_key, action);
        throw new Error(errorMessage);
      }

      nextState[_key] = nextStateForKey;
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
    }

    return hasChanged ? nextState : state;
  };
}
```

## 入参
不同的reducer函数组成的对象
```javascript
function todos(state = [], action) {
  switch (action.type) {
    case 'ADD_TODO':
      return state.concat([action.text])
    default:
      return state
  }
}

function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    default:
      return state
  }
}

// combineReducers把多个reducer函数组成一个
combineReducers({
  todos,
  counter
})

```

## 返回
合并后的reducer函数，简单的说就是把一个对象中的多个函数转换成了一个函数中的多个对象

repository: sammffl/react-redux-review

repo_name: sammffl/react-redux-review


text:
---
layout: post
title: "Faster Deep Q-learning using Neural Episodic Control"
date: 2018-01-06 05:17:49
categories: arXiv_AI
tags: arXiv_AI Reinforcement_Learning Deep_Learning
author: Daichi Nishio, Satoshi Yamane
mathjax: true
---

* content
{:toc}

##### Abstract
The Research on deep reinforcement learning to estimate Q-value by deep learning has been active in recent years. In deep reinforcement learning, it is important to efficiently learn the experiences that a agent has collected by exploring the environment. In this research, we propose NEC2DQN that improves learning speed of a algorithm with poor sample efficiency by using a algorithm with good one at the beginning of learning, and we demonstrate it in experiments.

##### Abstract (translated by Google)
深度强化学习对深度学习Q值的研究近年来一直活跃。在深度强化学习中，通过探索环境来有效地学习代理人收集的经验是非常重要的。在这项研究中，我们提出NEC2DQN，通过在学习开始时使用一个好的算法来提高样本效率较差的算法的学习速度，我们在实验中证明了这一点。

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

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


text:
# Sudokus Colored

In this experiment I create oversimposed colored sudokus. The project is inspired by Alex Bellos' tridokus, which I found in his book *Snowflake Seashell Star: Colouring Adventures in Numberland*.
<img src="https://fronkonstin.com/wp-content/uploads/2018/05/1930_20180523221339.png" height="650" width="650" align="middle">

## Getting Started

### Prerequisites

You will need to install the following packages (if you don't have them already):

```
install.packages("ggplot2")
install.packages("dplyr")
install.packages("gtools")
install.packages("colourlovers")
install.packages("sudoku")
```

## More info

A complete explanation of the experiment can be found [at fronkonstin](https://fronkonstin.com/2018/06/01/coloring-sudokus/)

An article on [The Guardian](https://www.theguardian.com/books/2015/sep/17/nested-fish-and-golden-triangles-adult-colouring-and-the-beauty-of-maths) by Alex Bellos

## Authors

* **Antonio Sánchez Chinchón** - [@aschinchon](https://twitter.com/aschinchon)

repository: jeonghyunwoo/sudokus-colored

repo_name: jeonghyunwoo/sudokus-colored


text:
---
name: Feature request
about: Suggest an idea for the visualizer
title: ''
labels: enhancement, visualizer ui
assignees: ''

---

**Version info:**

- Visual Studio version:
- Visualizer location: [VS install path, or Documents subfolder]
- Version: [GitHub release version or project commit]

Note that the visualizer location and version can be found at the bottom of the **Settings** popup (click the gear icon).

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Screenshots**
If applicable, add screenshots to help explain the problem you are trying to solve.

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.

repository: icxldd/ExpressionTreeVisualizer

repo_name: icxldd/ExpressionTreeVisualizer


text:
---
extends: about/jobs/_job.html
smalltitle: Jobs at Stencila
title: Software Engineer (Frontend)
---

Join a team developing the next-generation of tools for data-driven scientific discovery. Stencila aims to lower the barriers to reproducible research and enable collaboration between researchers with different levels of technical expertise. We're looking for a full-time software engineer to lead development of novel user interfaces for data exploration, visualization and analysis.

## About you

- You are passionate about understanding how our users think, what their problems are, and building engaging user experiences that solve those problems.
- You are an engineer with a sense of aesthetics: you have strong technical skills and can build a beautiful interface.
- You are keen to join in-person user workshops, value user feedback, and act upon it.
- Are committed to open-source and know from experience what it takes to grow a community around open-source software.
- Have a strong bias towards getting it done; you choose completion over perfection. You get a buzz out of getting things shipped.
- Take initiative, ownership and responsibility; you don’t need to wait for permission, don’t mind admitting you were wrong, and fix things when you are.
- Want to work as part of a diverse team with complementary skills; you give support and take advice.
- Comfortable working across time zones as part of a small, remote, geographically distributed team. You review asynchronous feedback, and get to work independently.
- You are comfortable regularly communicating on wins, progress, and roadblocks.

## Your Skills & Experience

- Experienced at building, testing, and deploying user interfaces in Javascript.
- Familiar with frontend frameworks like React, Vue and Polymer and state management approaches such as Redux, Mobx, and GraphQL.
- At home with modern front-end languages e.g. ES2016, Typescript, and build tools e.g. Webpack, Rollup, NPM.
- Experienced in test driven development and testing frameworks e.g. Jest, Puppeteer.
- Experienced at building from mockups using modern CSS approaches and frameworks e.g Bulma, Tailwind, Semantic UI.
- It’s a nice-to-have if you have a research or science background working with data.
- Proficient in the English language, both written and verbal.

## About us

- [Stencila](https://stenci.la) is building a toolbox of modular, interoperable software components for researchers ranging from Stencila [Dockter](https://github.com/stencila/dockter) (a command line tool that makes it easier to create Docker images) to Stencila [Hub](https://hub.stenci.la) (a web app that integrates our tools with third party services like Github and Dropbox) - and plenty of others in between!
- We're passionate about making data-driven discovery more accessible to more people and closing the gaps in collaboration between coders and non-coders.
- We’re obsessed with building tools that make simple things easy and complex things possible.
- With funding from the Alfred P. Sloan Foundation we are building a core team to take Stencila from a prototype to production.
- We are a small diverse, 100% remote, 100% open-source team linked to a broad open source and open science community.
- Stencila is proud to be an equal opportunity employer. We value diversity and do not discriminate on the basis of race, religion, color, national origin, citizenship, gender identity or expression, sexual orientation, age, marital or family status, veteran status, or disability. We work hard to accommodate the needs of our team members and community.

## Examples of things you’ll do

- Be part of the team designing and implementing an open, extensible architecture for user interfaces for data-driven discovery.
- Work with our product designer to design, build, test, and deploy user interfaces for data analysis and visualization.
- Be involved in user testing to understand usability problems that users are having. Then fix those problems.
- Engage with the open-source developer community to encourage contributions. Improve documentation, merge pull requests, respond to issues.

## What’s unique about this job?

- Be part of a unique team working with scientists and other researchers to make data-driven research more open, effective, and reproducible.
- Opportunities to connect with a global community of people working on open source software for science and scholarship, including Code for Science & Society, Collaborative Knowledge Foundation, eLife, Substance, and more!

## Compensation

- US \$100,000 / year

Please send your CV and a covering letter to [mailto:jobs<EMAIL_ADDRESS>by 13 January 2019.
We are hoping the successful applicant will start 4 February 2019, although there is some flexibility on this, particularly for the right person.

repository: stencila/website

repo_name: stencila/website


text:
[scusjs占坑]Daily Ubuntu Tips – Adding User Accounts In Ubuntu
================================================================================
Ubuntu is a multi-user operating system. Multi-user OS means that more than one users are access the computer with separate and individual profile with home folder, documents, and settings. User A can login and make changes to his/her profile without affecting user **B’s** profile.

So, instead of creating a single shared account for everyone in your household, you can create an individual account for each user who will be using your home computer. This brief tutorial is going to show you how to do that when using Ubuntu.

To get started, click on the far fight of the menu bar and select the gear icon, then click System Settings.

![](http://www.liberiangeek.net/wp-content/uploads/2013/09/ubuntulockscreendisable4.png)

When that opens, click ‘**User Accounts**’ from the bottom of your screen as shown below

![](http://www.liberiangeek.net/wp-content/uploads/2013/09/useraccountsubuntu.png)

You need administrative privileges to  add user accounts to Ubuntu. If you do, click Unlock before adding accounts.

![](http://www.liberiangeek.net/wp-content/uploads/2013/09/useraccountsubuntu1.png)

Next,  click the plus ( + ) button to create a user account.

![](http://www.liberiangeek.net/wp-content/uploads/2013/09/useraccountsubuntu2.png)

There are two primary account types when creating new users. **Standard User** and **Administrator**. User with administrative rights can delete users, install software and drivers, change the date and time and can make changes that may render the computer unstable.

Standard won’t be able to make these changes. He/she can only change stuff in his/her profile.

When you enter the full name of the user, the username will automatically be selected for you based on his full name. It’s ok to keep it but you can change it if you like. When you’re done, click Create to create the account.

By default, the account is disabled and will remain so until you change/add a password. To enable the account, click the Account disabled button, then type a new password.

![](http://www.liberiangeek.net/wp-content/uploads/2013/09/useraccountsubuntu3.png)

If you want to user to automatically logon without typing password, you can choose the drop-down option while setting his/her password to logon automatically.

Enjoy!
--------------------------------------------------------------------------------

via: http://www.liberiangeek.net/2013/09/daily-ubuntu-tips-adding-user-accounts-ubuntu/

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译，[Linux中国](http://linux.cn/) 荣誉推出

译者：[译者ID](https://github.com/译者ID) 校对：[校对者ID](https://github.com/校对者ID)

url: https://raw.githubusercontent.com/stamhe/TranslateProject/f925790555314142d8a9092378f39f334ef86376/sources/Daily Ubuntu Tips – Adding User Accounts In Ubuntu.md

repository: stamhe/TranslateProject

repo_name: stamhe/TranslateProject


text:
# Microsoft Cognitive Services Anomaly Detector tutorial projects

This tutorial shows the features of the Microsoft Cognitive Services Anomaly Detector REST API by using C#, Java, Python and JavaScript(HTML).

## Getting started

### Installation

1. Clone the repository, or download the repository as a .zip file and extract the .zip file into an empty directory.
2. Install Visual Studio 2017, Community Edition.
3. Install latest Newtonsoft.Json package with NuGet Packages Manager.

You are now ready to begin the tutorial.

repository: conhua/AnomalyDetector

repo_name: conhua/AnomalyDetector


text:
---
layout: post
title: "Weekend in Bilene"
date: 2016-12-18
author: Coloma Farré
backgrounds:
    - /img/bilene/0000_IMG_7967.JPG
thumb: /img/bilene/0000_IMG_7996.JPG
categories: Family Mozambique Weekend Birthday
comments: true
---

We took a **one-night trip to Bilene**, a town by a calm and clear lagoon, just an hour from home, to celebrate my 30th Birthday!! Joe, Ramona, me and Djer (our neighbor from across the street and Ramona's best friend in Mozambique).

**It was a last minute plan**, and we were lucky to find a place to stay because most of the hotels were booked. **It was also a last minute decision to take Djer with us**! He always talked about how he had never gone to the beach, how excited he was about to go one day, asking me to show him pictures of the beach, etc. So, on Saturday morning we talked to his mom and she agreed. He quickly packed his bag and join us for the trip! Ramona was so happy and entertained with him, and he was more than excited with the whole experience!!

**Djer had never had pizza before either**. Not that we needed an extra excuse to get some, but since there is no pizza place in Manhiça, and since Joe was almost as excited about it as Djer was about the beach, we searched out Bilene's pizza joint. We ended up at a restaurant we really liked. It had great views, space for the kids to play, a big library with all sorts of books, a cool ambiance and yummy cheesy pizzas. Perfect evening with the ocean breeze!

On Sunday we did more of the same: beach and pool!

On the way back we stopped at this big street market to buy some fruit (no mangos!). So beautifully arranged that you just wanna buy everything!

This weekend was fun in so many ways: spending time with my family, a lovely beach, the perfect temperature, good food, nice people. Way too many mosquitoes at night, but nothing is perfect. **It was especially good to be able to share it with our new friend**! To see him get so excited to be at the beach for the first time, jumping in the water with the biggest smile, making up a "pizza" song while waiting for dinner to be ready... All those emotions and excitement that sometimes, as adults, we forget... kids make us realize and appreciate more. The good things in life!

And here is a short **video of the trip**:


text:
---
layout: post
#h2
title: NSF Funding, Soup and Goats

 ## The Secret Formula

---

For my 2nd project, I decided to see if there existed some secret formula that, when configured
just right, could predict the amount of grant funding you could be awarded by the NSF.  I thought
this might be a worthwhile project because:

* a) Grant proposals are the stuff of nightmares, and are therefore in need of some sort 		     of magical cure, and
* b) I like the idea of taking a complicated process, throwing it into a
	     regressor, and coming up with a nice linear equation, and transforming the whole
	     process into a seemingly harmless little collection of coefficients and vectors.
![alt_text](/pics/Perfect-Grant-Writing-Formula-Cartoon-1024x773.jpg)

To start this project, I had to reach for some soup.  Specifically the beautiful kind, as in BeautifulSoup in python to scrape the NSF website for award summary data:

[National Science Foundation Awards Summary](https://dellweb.bfa.nsf.gov/AwdLst2/default.asp)

But unfortunately I ran into some issues right away, as the NSF award statistics webpage was configured such that the html code populated their award summary data table only when the user selected a specific State or Institution, which was then sent to their servers as query response data and which generated asp requests to get the corresponding award summary information.  Neither BeautifulSoup nor Selenium (the other web scraping option available in python) were able to automatically generate these requests and responses alone (I would have had to incorporate scrapy as well).

So instead, I used BeautifulSoup to scrape their download data page to retrieve xml files containing award statistics from 2013-2018.  That gave me around 60,000 awards to look at over the 5 year period.

I then started exploring.  Could any of the information contained in these files provide the secret formula for grant funding?  Well, first I needed to see what I had to work with.  I had data on award effective dates and end dates, award amended dates, state, university/institution name, fields (Social sciences, computer science, engineering, etc) and abstracts.  I did some simple pandas calculations to quantify these features: grant lengths, amended lengths, word count of abstracts, and I also pulled in university rankings (by amount of R&D expenditure and total number of graduate students) as well as historical data (number of grant proposals submitted vs number of grants approved).

### Time to cook!

I tried a simple linear regression at first.  I split the data (70/30) into a training and testing set and fit the training data to the linear regression model in python.  I then generated predicted award amount values for the features in the testing set.  My model did not predict very well at all, as shown in this plot of predicted vs actual values:

As my model was fitting so poorly and my RSME values were so high, I decided to do some model diagnostics.  First, I plotted a correlation heatmap and looked at the distribution of the data to get a better sense of how the data varied with abstract funding:

Then I calculated the variance inflation factor to see if any of the independent features in my dataset should be removed:

While the VIF for Grant Length was not extremely high, it was still over 5, so I re-ran my linear regression model without this feature in the dataset, but it did not make an appreciable difference to the results.

I then looked at the variance of the error in my model by plotting the predicted award amounts against the residuals of the model: ![alt_text](/pics/residuals.png)  In this plot you can clearly see that the distribution of residuals is not random, so the error variance is not constant.

So I decided to try a log transformation of the award amount data to fit into my linear regressor.  In this case, I would be trying to see if any of the features listed above had any significant effect on the log of the award amount data.  Here are the results of my model below:
![alt_text](/pics/exppred.png)
![alt_text](/pics/residuals2.png)
There is now more randomness to the residuals plot, and the regressor did seem to improve, giving RSME scores of 0.92 and R-squared scores of 0.39 for the test sets.  Unfortuntely, there wasn't a clear linear pattern in the relationship between the features and the award amount.  Alas, no secret formula.

So instead of a wonderful linear regression model with the magical secret to maximizing your NSF grant funding, I leave you with what's behind door number 3: the Monty Hall Goat!
![alt_text](/pics/montyhallgoat.png)

Thanks!


text:
# Stateoscope

[![Build Status](https://travis-ci.org/padde/stateoscope.svg)](https://travis-ci.org/padde/stateoscope)
[![Code Climate](https://codeclimate.com/github/padde/stateoscope/badges/gpa.svg)](https://codeclimate.com/github/padde/stateoscope)
[![Test Coverage](https://codeclimate.com/github/padde/stateoscope/badges/coverage.svg)](https://codeclimate.com/github/padde/stateoscope/coverage)
[![Inline docs](http://inch-ci.org/github/padde/stateoscope.svg?branch=master)](http://inch-ci.org/github/padde/stateoscope)
[![Gem Version](https://badge.fury.io/rb/stateoscope.svg)](https://badge.fury.io/rb/stateoscope)
[![Yard Docs](http://img.shields.io/badge/yard-docs-blue.svg)](http://www.rubydoc.info/gems/stateoscope)

Visualize State Machines using GraphViz

## External Dependencies

Stateoscope depends on [GraphViz](http://www.graphviz.org/) for generating the
graphs. You need to make sure that GraphViz is properly installed on your system
before you will be able to generate graphs. If you are on a Mac, you can install
GraphViz via [Homebrew](http://brew.sh/)

```
$ brew install graphviz
```

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'stateoscope', '~> 0.1.3', group: :development
```

And then execute:

    $ bundle

## Using the rake task

To generate a state machine visualization for your `Model`, run

```ruby
rake 'stateoscope:visualize[Model]'
```

If you have multiple state machines defined on your model, you can pass the name
of the state machine as second parameter

```ruby
rake 'stateoscope:visualize[Model,specific_state_machine]'
```

If you want to highlight a specific state of your state machine, add the name as a third argument.

```ruby
rake 'stateoscope:visualize[Order,order_state,delivered]'
```

In any case, a PDF file containing the graph visualization will be saved to
the current directory.

## Using Stateoscope directly

Stateoscope exposes a `visualize` method that allows for a more fine-grained and dynamic usage.

Example:

```ruby
filename = Stateoscope.visualize(
  Order,
  state_machine_name: "order_state",
  current_state: "delivered",
  dir: Rails.root.join("public"), # default current directory
  format: "png" # default "pdf", possible are all formats that GraphViz supports
)

# filename will be for example RAILS_ROOT/public/order_state-20191201145422.png
```

## Adapters

Stateoscope ships with adapters for the following state machine gems:

- [AASM](https://github.com/aasm/aasm)

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`.

## Release

To release a new version, perform the following steps:

- update changelog
- update version in `version.rb`
- update version in the installation instructions in `README.rb`
- run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org)
- create a release for the new version on [github.com](https://github.com/padde/stateoscope/releases/new)

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/padde/stateoscope.

repository: padde/stateoscope

gha_language: Ruby

repo_name: padde/stateoscope


text:
# Ballbot

Extending the self [balancing robot] (https://github.com/laurensvalk/segway) to higher dimensions...

2DOF: On a [small plastic ball] (https://www.youtube.com/watch?v=PX7RNmyJgEs)

3DOF: Can also turn the longitudinal axis, [BB8 style] (https://youtu.be/3GlxzoE0jcg)

repository: LEGO-Robotics/BallBot

repo_name: LEGO-Robotics/BallBot


text:
# Pattern Recognition Exercises

These are my solutions to the exercises for the pattern recognition class in SS2018 at TU Munich.

## Exercise 2
This exercise is about performance metrics in pattern recognition. The exercise discusses *Receiver Operating Characteristic (ROC) Curve*, *Precision Recall Curve (PRC)* and cost based evaluation of a binary classifier on 2 gaussian class distributions.

## Exercise 3
Bayesian classification and feature analysis are the topics for this exercise.

We were presented with data of disease symptoms and the assigned classes of disease. We first had to visually analyse the data by plotting histograms and identified the underlying distribution functions. Either by extracting the relevant parameters (e.g. mean and standard deviation) or by treating the histogram as the underlying *probability density function (pdf)*.

The next task was to implement a bayesian classifier that uses the distribution functions from task 1 and considers the known class distributions (given in the problem description) as prior information.

The bayesian classifier is optimal with respect to the conditional risk. The last task was to visualise the conditional risk that we face for a sample based on the *zero-one loss* with respect to two of the parameters (the result is one pretty surface plot).

## Exercise 6
This exercise was kind of lame. There wasn't much todo besides filling out three very small blocks of code but the underlying concepts are quite interesting.

The idea of exercise 6 is to use a concept called bayesian inference or bayesian learning to efficiently estimate a *psychometric function* - a type of function that models the relationship between a physical stimulus and forced-choice responses of human testees (Wikipedia) - applied to human vision examination. Psychometric functions are represented by a threshold T, which is the magnitude of the stimulus where the probability of a correct response is greater than 75 %. The aim is to find the threshold with the maximal probability given the set of responses.

$$max~p(T|\vec{R}).$$

We start with a set of psychometric functions with thresholds in a discrete range and simulate a forced-test with a stimulus placed at the threshold of a randomly selected function in the set. We calculate the probability of the response R given the threshold for each model

$$p(R|T)$$

and apply Bayes' theorem

$$p(T|R) = \frac{p(R|T) \cdot p(T)}{p(R)}.$$

The denominator is only required for normalisation and can be replaced by normalising the term in the numerator to a sum of 1. We could stop here and find the maximum of $p(T|R)$ but the strength of bayesian inference lies in recursive application of Bayes' theorem. $p(T)$ is unknown in the first iteration and can only be guessed (e.g. by assuming a uniform distribution). In the next iteration however, we can use the result of the previous step as prior information to the next step but we have to make a few modifications to the formula first

$$p(T|R) = \frac{p_n(R|T) \cdot p_{n-1}(T)}{p_n(R)} \Leftarrow p_n(R|T) = p_{n-1}(R|T) \cdot p(R_n|T)$$

where $p_n$ is the probability in the n-th iteration and $R_n$ is the response in the n-th iteration. $p_n(R|T)$ is the likelihood of all responses that were acquired until this iteration. We do some math and get the following expressions.

$$p(T|R) = \frac{p_{n-1}(R|T) \cdot p(R_n|T) \cdot p_{n-1}(T)}{p_n(R)} \leftarrow p_{n-1}(R|T) = \frac{p_{n-1}(T|R) \cdot p_{n-1}(R)}{p_{n-1}(T)}\Leftrightarrow$$

$$p(T|R) = \frac{p_{n-1}(T|R) \cdot p_{n-1}(R) \cdot p(R_n|T)}{p_n(R)} \Leftarrow \frac{p_{n-1}(R)}{p_n(R)} = \frac{1}{p(R_n)} \Leftrightarrow$$

We use the *law of total probability* to derive the marginal probability $p(R_n)$

$$p(T|R) = \frac{p_{n-1}(T|R) \cdot p(R_n|T)}{p(R_n)} \Leftarrow p(R_n) = \sum_T p(R_n|T) \cdot p_{n-1}(T)$$

or we could just neglect $p(R_n)$, because it's the same for all models, and normalise $p(T|R)$ to a sum of 1, which we do in the exercise because it leads to the same result anyway.

We do this recursion for a number of iterations that is acceptable - we do 200 in the exercise - and plot the result.

## Exercise 8
This exercise featured one of the most popular clustering algorithms called *k-means* or *vector quantisation*.

Clustering algorithms aim to reveal structure in the data by finding suitable class centres that result in a low reconstruction or classification error of the test data. The topic for this exercise was to implement k-means which is an iterative clustering algorithm that is guaranteed to converge eventually.

We start by defining a set of starting class centres - or codebook vectors. I randomly select some of the data points for that purpose. The next step is to find the nearest codebook vector for each data point which associates it with one of the codebook vectors. The last step is to move each codebook vector into the centroid - the mean in the feature space - of the associated data points. The algorithm finishes when no codebook vector has moved more than a threshold.

license: Unlicense


text:
This example show you how to extract part of information from pivot table. Due to hierachical structure of pivot tables, the data of pivot table is complex and it is not easy to get.

The `PivotExtract` process can help you to get data from pivot table. The resulted data is in normal tabular format so you can use them to display on table or draw chart.

More information of `PivotExtract` and its documentation you may find [here](https://www.koolreport.com/packages/pivot).

repository: koolreport/examples

repo_name: koolreport/examples


text:
[VIRB922W termid ENDING OBJECT nnnnnnnn](https://virtel.readthedocs.io/en/latest/manuals/virtel/Virtel459MG/messages.html?highlight=VIRB922W#VIRB922W)

`Module`
- VIR0B09

`Meaning`
- Terminal termid associated with a batch line has finished processing.

`Action`
- None.

repository: olepicard/tldrZ

repo_name: olepicard/tldrZ


text:
---
title: "Mitigating Position Falsification Attacks in Vehicular Platooning"
authors: ["Felipe Boeira", "Mikael Asplund", "Marinho Barcellos"]
publication: "Proceedings of IEEE Vehicular Networking Conference (VNC)"
publication_short: "*IEEE VNC*"
publication_types: ["1"]
date: 2018-12-05
publishDate: 2018-12-05
featured: false
tags: ["VANETS", "security", "safety", "platooning"]
links:
- name: DL
  url: https://ieeexplore.ieee.org/document/8628427
doi: "10.1109/VNC.2018.8628427"

#url_pdf: "papers/2018-VNC-boeira.pdf"
#url_code: '#'
#url_dataset: '#'
#url_poster: '#'
#url_project: ''
#url_slides: ""
#url_source: '#'
#url_video: '#'

abstract: "As connected vehicles are envisioned to provide novel intelligent transportation systems, cyber-attacks and security schemes are becoming an increasing concern. Several studies have shown that algorithms that make use of location information from other vehicles, such as vehicular platoon controllers, are vulnerable to message falsification attacks. Moreover, the ability for an attacking vehicle to appear as several vehicles through a so-called Sybil attack can significantly increase the severity of the attack. In this paper, we investigate how these attacks can be detected using Vouch location proof scheme (by identifying false location messages) and propose several reaction strategies to mitigate them. We also show through simulation that it is possible to prevent collisions by reacting appropriately to the false beacons in time while not reacting to false positives coming from the detector."

# Summary. An optional shortened abstract.
summary:  An optional shortened abstract.

# Associated Projects (optional).
#   Associate this publication with one or more of your projects.
#   Simply enter your project's folder or file name without extension.
#   E.g. `internal-project` references `content/project/internal-project/index.md`.
#   Otherwise, set `projects: []`.
#projects:
#- P4Sec

# Slides (optional).
#   Associate this publication with Markdown slides.
#   Simply enter your slide deck's filename without extension.
#   E.g. `slides: "example"` references `content/slides/example/index.md`.
#   Otherwise, set `slides: ""`.
# slides: example
---

repository: marinho-barcellos/academic-kickstart

repo_name: marinho-barcellos/academic-kickstart


text:
These samples are provided for reference purposes on an "as is" basis, and are without warranties of any kind.

It is strongly advised that these samples are not run against production systems.

Any issues discovered using the samples should not be directed to QRadar support, but be reported on the Github issues tracker.

# Introductory Samples

Scripts in this directory serve as an introduction to using the API.
Basics such as how to authenticate with the system, how to
pass various types of parameters, and an introduction to the
types of errors you might encounter are covered here.

For a list of the endpoints that you can use along with the parameters
they accept you can view the REST API interactive help page at
`https://<hostname>/api_doc`
You can also retrieve a list of available endpoints through the api itself
at the `/api/help/versions` endpoint.

The scripts in this directory include:

### 01_GetTenant.py
This sample demonstrates how to retrieve the list of tenant, and how to send a simple request
to a REST API endpoint.

### 02_CreateUpdateDeleteTenant.py
This sample demonstrates how to create, modify and delete a tenant with a REST API
endpoint.

repository: kali-ren/api-samples

repo_name: kali-ren/api-samples


text:
```js
l1.repeat(callback, [interval = 1])
```

Will execute a callback repeatedly every `interval` amount of game updates. Think of it as a `setInterval` that is controlled by updates from a game loop.

## Arguments

`callback` (Function): Executed every `interval` amount of game updates. Is called with two arguments: `counter` (integer): the amount of game updates since the behavior was created. `deltaTime` (float): the time since the last update. The value is the same as the one passed to `update`. In `PixiJS` this number is `1` at 60 FPS.

`interval` (Integer, optional): Game updates before executing the callback.

## Returns

(Object): A `behavior` object. Has two properties that can be set:

Option | Type | Description
-- | -- | -- |
**id** | String | Used with `get` and `remove`
**labels** | Array (String) | Used to group behaviors together

## Misc

The behavior object will not be removed until you call `l1.remove`.

## Example

TODO: More examples and better examples
TODO: Use ID and labels here

```js
const sprite = new PIXI.Sprite()

l1.repeat((counter) => {
  sprite.x = counter
})
```

gha_language: TypeScript


text:
beautify
========

A simple Python script that makes use of the open source music identification system Echoprint (http://echoprint.me/) and the Spotify Web API to set the right details for each track in your music library

For now, only songs placed in the same directory as beautify.py are 'beautify'd.

## Requirements

* [eyed3](http://eyed3.nicfit.net/ "eyed3")
* [Python HTTP Requests for Humans](https://github.com/kennethreitz/requests "Python-Requests")
* Pillow
* [echoprint-codegen](https://github.com/echonest/echoprint-codegen "echoprint-codegen")

repository: vigneshwerv/beautify

repo_name: vigneshwerv/beautify


text:
---
layout: post
category : diy
title: "Fix Dry Wall Surface"
tags : [plastering,fix-it]
---
{% include JB/setup %}

If you've tried ripping anything off drywall (like Tiles for instance), you've probably notice a problem. It utterly destroys the surface of the drywall. It is fairly easy to fix.

## Step 1 - Things you need

You're going to need the following items:

- 2 plaster knives. These are not knives as in 'stab stab', these are broad and flat scraper like tools. Plastic versions cost about $5 each.
- a tub of pre-mixed plaster. Get the "final coat" or "top coat" stuff. It spreads a lot more easily than the premixed "multi-purpose" version.
- sanding block or paper

First, use the sanding block to remove any bits of drywall paper that are sticking out, and generally smooth the surface.

 Mix it around a bit if the liquid has seperated and is sitting on top. Now, to get plaster ready to spread on your plaster knife, you need to "play" with it a bit. Remember as a kid how you would roll around a ball of play-dough and swap it from hand to hand? Do something similar with your two plaster knives.

Scoop some plaster onto one knife, then scrape it on to the other knife, and vice versa. Doing this a few times makes sure it will be easy to spread.

## Step 3 - Spread the plaster

Make sure your blob of plaster is in the middle of the knife, then put the knife up to the wall and spread the plaster. You want a fairly thin (but even) coat. If you put it on too thick, you will need to do a lot of sanding after it dries.

After you have spread the plaster on the knife, use the second knife to scrape the first knife clean. Then use the clean knife to scrape the excess plaster off. You want enough pressure to scrape the surface smooth and flat, but not so much that you are exposing the old wall.

## Step 4 - Let it dry

Leave the plaster to dry overnight. You may or may not need a second coat. Give it a light sand to smooth it over. If the new coat is completely hiding the damaged wall, then you are good to go. If it is still showing through, repeat all steps.

If the wall is not visibly smooth, keep sanding until it is.

## Step 5 - Finishing

At this point you are good to prime and paint. If you want to match the existing paint, chip a little bit off and take it to a paint store (or Bunnings), they should be able to get a near perfect match.

 Awesome!


text:
---
id: 11500
title: Occupy Planning Dept
date: 2012-02-28T10:36:14+00:00
author: Tamara Shopsin
layout: post
guid: http://codeforamerica.org/?p=11500
permalink: /2012/02/28/occupy-planning-dept/
dsq_thread_id:
  - 586273898
categories:
  - 2012 fellows
  - Commentary
  - Santa Cruz
---
<img class="alignnone size-full wp-image-11502" title="IMG_0702" src="http://codeforamerica.org/wp-content/uploads/2012/02/IMG_0702.jpg" alt="" />

**8:00 am:** People trickle in one by one.

A woman is starting a personal training business. She draws her floor plan on the back of a land use form. The city takes the plan though it is missing a dimension.

The municipal code is in a three ring binder. It and the GIS (mapping with information layered on top) are consulted regularly.

**10:00 am:** There’s a one person wait.

A man wants to add a deck to his home. The GIS shows he is in a butterfly zone and will need to do a special survey. He is assured it’s not really a hurdle, so long as he doesn’t want to add a fireplace.

**11:45 am:** Waiting room is full, people have to stand.

A real estate broker wants to know if a perspective buyer can build a garage, gazebo, or deck.

Graphic designer pays her zoning fee with a tastefully designed check.

Public hours are over.

**1:30 pm:** Weekly staff meeting.

Carrot cake is served.

GIS and zoning info is projected on the wall as plans are dissected.

“The building was much cuter before. What happened?”

“It’s been value engineered before it’s even been approved.”

“Tell them we can’t approve it. It is not harmonious in form and proportion.”

_Laughter_ followed by a plan to discuss code violations with the builder.

Twiddle = two-way left turn lane aka “Suicide lane”

“Signalize intersection” is said seven times and a planning angel gets their wings.


text:
# 77PIXELS

## By [Derrick Cheboi](https://github.com/CheboiDerrick/)

## Description
77Pixels is an online photo gallery application that show cases amazing pictures from different places. The pictures are uploaded with categories and locations they were taken.
## Application Behaviour
These are the behaviours/features that the application implements for use by a user.

A user should be able to:
* Provide the user with all pictures uploaded on the homepage
* Redirect a user to the pictures of a particular category or location
* Provide the details of a picture in a modal when clicked on.

## Screenshots
* Home Page

* Categories

* Location

* Picture details

## SetUp / Installation Requirements
### Prerequisites
* python3.8
* pip3
* pipenv
* Git and Github

### Cloning
* In your terminal:

        $ git clone https://github.com/CheboiDerrick/my-gallery-django.git
        $ cd my-gallery-django

## Running the Application
* Install all dependencies by running

      $ pipenv install

* Set up your database and add it to the settings in the photogallery  project folder
* To run the application, in your terminal:

        $ python manage.py runserver

* Open your browser and navigate to http://localhost:8000 to view the web app

## Technologies and Languages Used
* Python -(3.8)
* Django

## License
[MIT](https://github.com/CheboiDerrick/my-gallery-django/blob/main/LICENSE)

©2021

repository: CheboiDerrick/my-gallery-django

repo_name: CheboiDerrick/my-gallery-django


text:
---
layout: post
published: true
title: Coins on a Square Table
date: 2017/03/10
---
> Two players are seated at a square table. The first player places a coin on the table, the second places a coin on the table, and they carry on placing coins one after another, with the only condition being that the coins are not allowed to touch. The winner is the person who places the final coin on the table, meaning that he or she fills the last remaining space between the other coins.
>
>The table has to be larger than a single coin, and all the coins placed must be identically sized.
>
>One player is always guaranteed to win if they use a certain strategy. Which one is it — the one who starts or the one who goes second? And what is his or her strategy?

<!--more-->

([fivethirtyeight](https://fivethirtyeight.com/features/who-will-win-the-space-race/))

## Solution:

The first player (X) always wins. X places the first coin in the center of the table. After that, whenever Y places a coin, X places the next one symmetrically, so that the two coins are the same distance from the center coin and all three of those coins are in the same line.  After each of X's moves, the table is symmetric (it has 180-degree rotational symmetry about the center), so that any open spot for Y to place a coin is mirrored by a spot for X's next coin. It follows that Y will be first to be unable to place a coin.

<br>


text:
---
title: Hello World!
layout: post
date:   2014-03-01 00:00:00
categories: thinking
---

Ok, I decided I should blog about the interesting things I am doing at my work. So let me introduce myself.

I am Pedro Axelrud, an entrepreneur and developer. I run a startup called Mailee.me, we develop an email marketing platform called [Mailee.me](http://mailee.me).

Today my work is mixed between developing and taking care of the business. I started as a Ruby developer and at the same time I also had the sysadmin role, so naturally the DevOps role came very naturally.

The infrastructure required for sending emails is very complicated, so it made me learn a lot. For example, today we send more than 20M emails per month. Once we must be able to track all the emails sent, if you do the math considering we started more than 4 years ago, you should have noticed that our database ain't easy to maintain. Join this with all the complicated rules you must follow to send millions of emails per month without going to SPAM folder and you will understand my daily routine.

That's what I will talk about here :)

extension: markdown


text:
# FREED

**Let's take a legal escape**

FREED is an app which is helping to maintain student leave records in our university, that is completely focused on minimizing and making most of the documenting process and easy to maintain the records in a systematic manner. Our App will reduce paperwork, save time and convenient for the user.

## Contributing

If you notice issues, have questions or want to suggest enhancements, please raise an issue in this repo.

## ScreenShot