text:
---
author: Ricardo Adao
published: true
post_date: 2018-10-10 00:51:00
last_modified_at: null
header:
  teaser: /assets/images/featured/powershell-150x150.png
title: Powershell - Wrapping GET and POST Rest API calls
categories:
  - powershell
tags:
  - powershell
  - coding
  - automation
  - vcf
  - vvd
toc: true
slug: powershell-wrapping-post-rest-api-calls
lastmod: 2023-06-21T08:14:42.689Z
---
# Code Bits&Pieces and Context

This post is not an _Eureka_ moment, so do not expect any _breakthrough_ or _light bulb moment_.

However, sometimes we forgot one of the basic rules of code development that we learned or read in the past.

Typically, if we re-utilize a bit code more than 3 to 5 times, it could to _promote it_ to a separate function/method to consolidate it in a single place, making it easier to update or correct if necessary, since it would be a single place to change instead of all the places where we re-utilized it.

Adding to that easy to understand advantage it will also be a _code refactoring_ exercise, since once that function/method is created, we will be able to optimize or re-code it completely without affecting the expected functionality.

## Using GET and POST REST API Methods as an example

As an example we can create some _wrapping functions_ to simplify the interaction with a REST API.

We will create 2 functions:

* _**Get-RestAPICall**_
  * **Method** - GET
  * **Parameters** - headers, url

* _**Post-RestAPICall**_
  * **Method** - POST
  * **Parameters** - headers, url, payload

These 2 _wrappers_ will be a way of simplifying the use of _Powershell cmdlet Invoke-RestMethod_ and even handling some of the errors/exceptions.

## Functions code

We added some error/exception handling to the functions to give the functions to make them a bit more than a _passthrough_ to the [_Invoke-RestMethod_](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-6).

### Get-RestAPICall

```powershell
function Get-RestAPICall {
    param(
        [Parameter(Position=0, Mandatory = $true, ValueFromPipeline = $true)] `
            [string]$url,
        [Parameter(Position=1, Mandatory = $false, ValueFromPipeline = $true)] `
            [System.Collections.Generic.Dictionary[[String],[String]]]$headers
    )
    try {
        if ($headers) {
            $request = Invoke-RestMethod -Method GET -Headers $headers -Uri $url
        } else {
            $request = Invoke-RestMethod -Uri $url
        }
    } catch [System.Net.WebException] {
        $exceptionError = $_.Exception

        switch ($exceptionError.Response.StatusCode.value__) {
            "200"   {
                Write-Host "=> Get-RestAPICall -> OK - $url <=" `
                    -ForegroundColor Green
            }
            "400"   {
                Write-Host "=> Get-RestAPICall -> Bad Request - $url <=" `
                    -ForegroundColor Red
                $request = $null
            }
            "404"   {
                Write-Host "=> Get-RestAPICall -> Not Found - $url <=" `
                    -ForegroundColor Red
                $request = $null
            }
            "405"   {
                Write-Host "=> Get-RestAPICall -> Invalid Method - $url <=" `
                    -ForegroundColor Red
                Write-Host "=> StatusCode:" $exceptionError.Response.StatusCode.value__ `
                    -ForegroundColor Yellow
                Write-Host "=> StatusDescription:" $exceptionError.Response.StatusDescription `
                    -ForegroundColor Yellow
                Write-Host "=> Type:" $exceptionError.GetType() -ForegroundColor Yellow
                Exit
            }
            "500"   {
                Write-Host "=> Get-RestAPICall -> Internal Server Error - $url <=" `
                    -ForegroundColor Red
                Write-Host "=> StatusCode:" $exceptionError.Response.StatusCode.value__ `
                    -ForegroundColor Yellow
                Write-Host "=> StatusDescription:" $exceptionError.Response.StatusDescription `
                    -ForegroundColor Yellow
                Write-Host "=> Type:" $exceptionError.GetType() -ForegroundColor Yellow
                Exit
            }
            "503"   {
                Write-Host "=> Get-RestAPICall -> Service Unavailable - $url <=" `
                    -ForegroundColor Red
                Write-Host "=> StatusCode:" $exceptionError.Response.StatusCode.value__ `
                    -ForegroundColor Yellow
                Write-Host "=> StatusDescription:" $exceptionError.Response.StatusDescription `
                    -ForegroundColor Yellow
                Write-Host "=> Type:" $exceptionError.GetType() -ForegroundColor Yellow
                Exit
            }
            default  {
                Write-Host "=> Get-RestAPICall -> Unspecified Error - $url <=" `
                    -ForegroundColor Red
                Write-Host "=> StatusCode:" $exceptionError.Response.StatusCode.value__ `
                    -ForegroundColor Yellow
                Write-Host "=> StatusDescription:" $exceptionError.Response.StatusDescription `
                    -ForegroundColor Yellow
                Write-Host "=> Type:" $exceptionError.GetType() -ForegroundColor Yellow
                Exit
            }
        }
    }

    return $request
}
```

### Post-RestAPICall

```powershell
function Post-RestAPICall {
    param(
        [Parameter(Position=0, Mandatory = $true, ValueFromPipeline = $true)] `
            [string]$url,
        [Parameter(Position=2, Mandatory = $true, ValueFromPipeline = $true)] `
            [string]$payload,
        [Parameter(Position=3, Mandatory = $false, ValueFromPipeline = $true)] `
            [System.Collections.Generic.Dictionary[[String],[String]]]$headers
    )
    # Load constants
    . "$PSScriptRoot\..\shared\shared.constants.ps1"

    try {
        if ($headers) {
            $request = Invoke-RestMethod -Method POST -Headers $headers -Body $payload -Uri $url
        } else {
            $request = Invoke-RestMethod -Body $payload -Uri $url
        }
    } catch [System.Net.WebException] {
        $exceptionError = $_.Exception

        switch ($exceptionError.Response.StatusCode.value__) {
            "200"   {
                Write-Host "=> Post-RestAPICall -> OK - $url <=" -ForegroundColor Green
            }
            "400"   {
                Write-Host "=> Post-RestAPICall -> Bad Request - $url <=" -ForegroundColor Red
                $request = $null
            }
            "500"   {
                Write-Host "=> Post-RestAPICall -> Internal Server Error - $url <=" `
                    -ForegroundColor Red
                Write-Host "=> StatusCode:" $exceptionError.Response.StatusCode.value__ `
                    -ForegroundColor Yellow
                Write-Host "=> StatusDescription:" $exceptionError.Response.StatusDescription `
                    -ForegroundColor Yellow
                Write-Host "=> Type:" $exceptionError.GetType() -ForegroundColor Yellow
                Exit
            }
            default  {
                Write-Host "=> Post-RestAPICall -> Unspecified Error - $url <=" `
                    -ForegroundColor Red
                Write-Host "=> StatusCode:" $exceptionError.Response.StatusCode.value__ `
                    -ForegroundColor Yellow
                Write-Host "=> StatusDescription:" $exceptionError.Response.StatusDescription `
                    -ForegroundColor Yellow
                Write-Host "=> Type:" $exceptionError.GetType() -ForegroundColor Yellow
                Exit
            }
        }
    }

    return $request
}
```

## Examples

Examples how to use the newly defined functions.

The examples below are part of a future post where these _wrapping functions_ will be used to interact with the [_VMware Cloud Foundation(VCF)_](https://docs.vmware.com/en/VMware-Cloud-Foundation/index.html) _bringup appliance_ API, to automate the deployment of a _VMware cluster_, following the _Consolidated Architecture Model_ defined in the [_VMware Validated Designs (VVD)_](https://docs.vmware.com/en/VMware-Validated-Design/index.html).

### Get-RestAPICall

In this example we are just making a quick _GET call_ to the _VCF bringup service_ to check the service version.

```powershell
$url = "http://localhost:9080/bringup-app/bringup/about"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type" , "application/json")

if (($request = Get-RestAPICall -url $url -headers $headers).name -notmatch "BRINGUP") {
    Write-Host "--> bringup - Bringup service is not UP <--" -ForegroundColor Red
    Exit
} else {
    Write-Host "--> bringup - Bringup service is UP and running <--" -ForegroundColor Green
    Write-Host "--> bringup - $($request.name) - $($request.serviceId) - $($request.version) <--" -ForegroundColor Green
}
```

### Post-RestAPICall

This example will be a _POST call_ and will require some extra headers and a _payload_.
The extra headers is to specify that the _payload_ will be in _JSON format_.
The _payload_ will be a _JSON_ with all the information needed by the _VCF bringup service_  to deploy the _VMware cluster_.

```powershell
$url = "http://localhost:9080/bringup-app/bringup/sddcs"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type" , "application/json")
$headers.Add("Content-Accept" , "application/json")

$request = Post-RestAPICall -url $url -headers $headers -payload $vpodJSON
$bringupId = $request.id
```

gha_language: HTML

gha_license_id: MIT


text:
## Name: Ronnie Winter

# Form3client

# Documentation of technical desicions
This can be found on the file named [TechnicalDecisions.md](TechnicalDecisions.md)

# Instructions

## Using library

Install the form3client to your `$GOBIN` path (usually `$GOPATH/bin`) by running the command `go install form3client`.
Then set the `$API` environment variable on your host to point to the address of form3's `accountapi` service (e.g: `http://localhost:8080/`).
Afterwards, you can create a new go project and use the library in this way:
```
package main

import (
	form3client "github.com/form3interview"
)

func main() {
	// Create(). Param pointer to form3client.Account struct holding the account data
	form3client.Create(&form3client.Account{}) // Returns form3client.Data struct holding the created account, and error

	// Fetch(). Param id of account to fetch
	form3client.Fetch("<the id (uuid) of the account to fetch>") // Returns form3client.Data struct holding the fetched account, and error

	// List(). Params pageSize and pageNumber (optional)
	form3client.List(0, 20) // Returns form3client.DataList struct holding the fetched accounts, and error

	// Delete(). Params id of account to fetch and version
	form3client.Delete("<the id (uuid) of the account to fetch>", 0) // Returns status bool of whether or not the deletion was successful, and error.
}
```

## Running tests

In order to run tests locally, make sure you have set the environment variable `$API` to point to form3's `accountapi` (e.g: `http://localhost:8080/`)

You can also run tests as part of the docker-compose stack definition. For this, make sure you have Docker and docker-compose installed, then execute the command `docker-compose up`.

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# Solidus Reviews

[![CircleCI](https://circleci.com/gh/solidusio-contrib/solidus_reviews.svg?style=svg)](https://circleci.com/gh/solidusio-contrib/solidus_reviews)
[![codecov](https://codecov.io/gh/solidusio-contrib/solidus_reviews/branch/master/graph/badge.svg)](https://codecov.io/gh/solidusio-contrib/solidus_reviews)

Straightforward review/rating functionality, updated for [Solidus](https://solidus.io).

While the gem's name has changed, the module namespace and commands are still `spree` for now.

## Installation

Add solidus_reviews to your Gemfile:

```ruby
gem 'solidus_reviews'
```

Bundle your dependencies and run the installation generator:

```shell
bin/rails generate solidus_reviews:install
```

## Usage

The `Spree::ReviewsController` controller provides all the CRUD functionality for product reviews.

The `Spree::FeedbackReviewsController` allows user to express their feedback on a specific review.
You can think of these as meta-reviews (e.g. the classic "Was this useful?" modal).

You can approve, edit and delete reviews and feedback reviews from the backend.

## Development

### Testing the extension

First bundle your dependencies, then run `bin/rake`. `bin/rake` will default to building the dummy
app if it does not exist, then it will run specs. The dummy app can be regenerated by using
`bin/rake extension:test_app`.

```shell
bin/rake
```

To run [Rubocop](https://github.com/bbatsov/rubocop) static code analysis run

```shell
bundle exec rubocop
```

When testing your application's integration with this extension you may use its factories.
You can load Solidus core factories along with this extension's factories using this statement:

```ruby
SolidusDevSupport::TestingSupport::Factories.load_for(SolidusReviews::Engine)
```

### Running the sandbox

To run this extension in a sandboxed Solidus application, you can run `bin/sandbox`. The path for
the sandbox app is `./sandbox` and `bin/rails` will forward any Rails commands to
`sandbox/bin/rails`.

Here's an example:

```
$ bin/rails server
=> Booting Puma
=> Rails <IP_ADDRESS> application starting in development
* Listening on tcp://<IP_ADDRESS>:3000
Use Ctrl-C to stop
```

### Releasing new versions

Please refer to the [dedicated page](https://github.com/solidusio/solidus/wiki/How-to-release-extensions) in the Solidus wiki.

## License

Copyright (c) 2023 Solidus Contrib, released under the New BSD License.

gha_language: Ruby


text:
# Meal Tracker

#### An App to Track Caloric Intake

#### Made by Charles Ewel

## Description

An app that allows user to enter their food intake for a day and see their total caloric intake along with options to filter meals by high and low calories

## Instructions

* Clone the repository
* If on a mac, install node.js on your machine by running >"brew install node" (must have Homebrew installed). if on PC or Linux google node.js, go their website and follow the instructions there. This will install npm automatically
* In the console, run ">npm install bower -g" to install bower globally
* In the console, run ">npm install" to set up the node modules
* In the console, run ">bower install" to set up the bower components
* In the console, run ">gulp build; gulp serve" to launch the website

## Specs

The program should handle: | Example Input | Example Output
----- | ----- | -----
Adding New Foods| User fills out a form with name, details, and calories | That food is added to the list of foods eaten for that day
Editing Foods | User clicks a food which brings up an edit menu, they then change some of the values in that menu | The values are changed in that food object and that is reflected in the display and total calories
Filtering Foods | User selects "High Calories" from the filter drop down menu | Only high calorie foods (>500 cal) are displayed in the list

## Technologies Used

* Angular2 Javascript
* Node.js
* Bower
* Typescript

## Known Bugs

None

### License

Licensed under the MIT License.

license: MIT

repository: CharlesEwel/mealtracker-js

repo_name: CharlesEwel/mealtracker-js


text:
![image](https://user-images.githubusercontent.com/2890683/30096520-60ab121e-930b-11e7-8488-39a67dc0ea09.png)

# BrowerSync VSCODE

Starts a browserSync Static server with watch mode at `:3000` by default. The UI for browsersync is available at `:3001`.

- Right click on the folder from your VSCODE explorer menu. And click on `BrowerSync Start`.

![image](https://user-images.githubusercontent.com/2890683/30096027-b67db406-9308-11e7-8fe9-6f3bf893668d.png)

- This will start the server at `localhost:3000` and open up your default browser. And serve the `index.html` file in the directory if present.

![image](https://user-images.githubusercontent.com/2890683/30096048-d4046ff6-9308-11e7-85f0-5aae0bedc29a.png)

- Once started, you can manage the running server on left menu status bar. Which will show the server is running at. Once you click on it, it will give you reload or stop option.

![image](https://user-images.githubusercontent.com/2890683/30096057-dcfad604-9308-11e7-948d-d3d1989a36ec.png)

- Once stop/reload is clicked, it will stop or reload the browsersync server.

![image](https://user-images.githubusercontent.com/2890683/30096069-e9adfe8a-9308-11e7-9098-2fe7f8fe5a36.png)

> Currently, you can only run one server at a time in the workspace. Starting another server within the workspace will close the current running server and spinup a new one at localhost:3000.

# Options

Browsersync allows for 2 options:

1. `openBrowser`: Whether you want to trigger a browser open when server is started.
2. `openExternal`: Opens with external URL
3. `options`: Pass browsersync options from https://www.browsersync.io/docs/options

# Development

Clone the repo and `cd` into `browsersync` folder. Run `npm install`, and you are ready for development.

# Issues

Raise issues [here](https://github.com/remicass/vscode-exts/tree/master/issues).

repository: jeremyrajan/vscode-exts

gha_language: TypeScript

repo_name: jeremyrajan/vscode-exts


text:
# Syllabus

## Course Metadata
School: School of Computing and Academic Studies
Program: Computer Systems Technology
Course Credits: 3
Start Date: January 07, 2019
End Date: April 19, 2019
Total Hours: 45
Total Weeks: 15
Hours/Weeks: 3
Delivery Type: Lecture
Prerequisites: COMP 2510 or COMP 2526
CRN: 86101

## Course description
This course provides the students with an opportunity to develop a software
application that works across the internet. An overview of various internet
software development technologies is provided.
Students will learn how to build a web application using a modern webapp
MVC framework and Apache server technology; and how to use XML for data
representation, structure and transport.

## Course goals
This course is about webapp development, using best practices.
In small teams, the students will build a robust RESTful webapp backend,
to complement their option projects.
The teams will collaborate using a shared code repository and gitflow workflow,
with appropriate supporting tools.

*Detailed learning outcomes*:
1  Build a moderate MVC web application using a suitable framework.
	1.1  Setup a suitable webapp development environment
	1.2  Build a basic RESTish webapp backend
	1.3  Build a moderately complex RESTful webapp backend
2  Build distributed capabilities into an MVC web application
	2.1  Use common representation protocols for distributed systems
	2.2  Use common transport protocols for distributed systems
	2.3  Use common application protocols for distributed systems
3  Demonstrate proper team collaboration for webapp development
	3.1  Use collaborative workflow to develop a webapp
	3.2  Use a shared code repository to develop a webapp

## Course learning outcomes / competencies
Upon successful completion of this course, the student will be able to:
 1  Construct an MVC web application using a suitable framework.
 2  Construct a valid and well-formed XML document, and constrain it with a DTD.
 3  Process XML data using DOM.

## Evaluation criteria
Quizzes & participation - 10% ... Readings & lab attendance (motivation)
Labs - 40% ... 10 walkthrough labs (guidance)
Assignments - 30% ... 2-3 assignments (practice)
Final exam - 20% ... Multiple choice, short & long answer (assessment)

## Attendance requirements
Students missing more than two labs will receive an Unsatisfactory grade in the course, and fail.

## Learning resources
Open-source tool set, including
- AMP (Apache + MySQL + PHP7) server environment, suitable for the student's platform;
    eg [xAMP stack](https://bitnami.com/stacks/infrastructure)
- PHP and HTML/CSS aware editor, eg [NetBeans 8](https://netbeans.org/downloads/8.2/),
    [NetBeans 10](https://netbeans.apache.org/download/nb100/nb100.html)  or
    [PhpStorm](https://jetbrains.com/phpstorm) ,
    or text editor, eg. [Sublime 3](https://www.sublimetext.com/3)
- [Composer](https://getcomposer.org) , PHP dependency manager
- CodeIgniter 4 webapp framework [starter project](https://packagist.org/packages/codeigniter4/appstarter)
- [MongoDB](https://www.mongodb.com) document database

## Course specific requirements

The expected workload for this course is one hour out-of-class for each timetabled hour.
The expectation is that a student will spend one hour on the assigned reading and
related quiz/questionnaire, and two hours collaborating on their assignment(s).

Weekly readings will be assigned, starting with the second week, following a
"flipped" learning model. The readings are in place of a textbook.
Students are to encouraged to read these lessons ahead of time, and have the
opportunity to complete a weekly survey by the evening before that
week's lecture. Survey responses are used to tailor the lecture to
address unclear topics.

Most labs will use pair programming, though some will be individual.
Most of these labs will have starter projects, on github.
The usual submission, if needed, will be a readme file in a D2L dropbox,
containing a link to the students' github repository they used to complete the work.
Lab grading will be by rubric, and the two members of a pair do not have to r
eceive the same grade. Lab work is meant to be completed during the lab period, with
time available to apply the lab's outcomes to the students' assignments.

Assignments will be completed in student-selected project teams of 3-5 members.
The same team will be used for all assignments. If a student does not have a team,
they will be assigned one by the instructor. Teams of one or of two members are not acceptable.
Team members' grades are commensurate with their contribution, as well as
performance assessed by an assignment rubric. Team submissions will be in the
form of a readme file in a D2L dropbox, with a link to the team's git repository for their project.

Course materials (lessons, examples, tutorials, labs and assignments) will be
shared through a public website (the course “hub”), with sensitive material on D2L.
Lab and assignment feedback will be provided through the D2L dropboxes that
readme files are submitted to. The D2L gradebook will be useful only to review
D2L-captured grade components, and it will not provide an accurate final grade in the course.

Students who miss class for an acceptable reason will be excused from attendance
and survey/quiz/questionnaire completion, should those fall during the excused
period. Missed readings or lab work will need to be made up by the student.

## Course schedule

**Week & Material Covered**
1 Introduction to MVC Webapps
2 MVC Frameworks
3 Collaborative Workflow
4 Controllers & Routing
5 Responses
6 Relational Models
7 Entities
8 Non-relational models
9 Representation Glue - XML
10 Representation Glue - JSON
11 Transport Glue
12 Application Glue - REST
13 Authentication
14 Final exam week

This course does not have a midterm. Students may request an individual or team interview with the instructor.
Refer to the organizer on the course hub home page for more detailed schedule information.

## Assignments
1 – RESTish backend - Create and access model data, with JSON data exchange (End of week 5)
2 – RESTful resource - Full model CRUD, supporting JSON data exchange (End of week 9)
3 - RESTful API service - Add service API, with XML support added to CRUD (End of week 13)

## BCIT policy
The following statements are in accordance with the BCIT Policies 5101, 5102, 5104, and 7507, and their accompanying procedures. To review these policies and procedures please click on the links below.
### Attendance/Illness:
In case of illness or other unavoidable cause of absence, the student must communicate as soon as possible with his/her instructor or Program Head or Chief Instructor, indicating the reason for the absence. Prolonged illness of three or more consecutive days must have a BCIT medical certificate sent to the department. Excessive absence may result in failure or immediate withdrawal from the course or program. Please see Policy 5101 - Student Regulations, and accompanying
procedures.
### Academic Integrity:
Violation of academic integrity, including plagiarism, dishonesty in assignments, examinations, or other academic performances are prohibited and will be handled in accordance with Policy 5104 - Academic Integrity and Appeals, and accompanying procedures.
### Accommodation:
Any student who may require accommodation from BCIT because of a physical or mental disability should refer to BCIT's Policy on Accommodation for Students with Disabilities (Policy #4501), and contact BCIT's Disability Resource Centre (SW1 2360,<PHONE_NUMBER>) at the earliest possible time. Requests for accommodation must be made to the Disability Resource Centre, and should not be made to a course instructor or Program area.
Any student who needs special assistance in the event of a medical emergency or building evacuation (either because of a disability or for any other reason) should promptly inform their course instructor(s) and the Disability Resource Centre of their personal circumstances.
### Human Rights, Harassment and Discrimination:
The BCIT community is made up of individuals from every ability, background, experience and identity, each contributing uniquely to the richness and diversity of the BCIT community as a whole. In recognition of this, and the intrinsic value of our diversity, BCIT seeks to foster a climate of collaboration, understanding and mutual respect between all members of the community and ensure an inclusive accessible working and learning environment where everyone can succeed.

Campus Mediation Services is a supportive resource for both students and employees of BCIT, to foster a respectful learning and working environment. Any student who feels that they are experiencing discrimination or harassment (personal or human rights-related) can confidentially access this resource for advice and support. Please see Policy 7507 – Harassment and Discrimination and accompanying procedure.

Students should make themselves aware of additional Education, Administration, Safety and other BCIT policies listed at http://www.bcit.ca/about/administration/policies.shtml

## Policy for School of Computing and Academic Studies
Attempts: Students must successfully complete a course within a maximum of three (3) attempts at
the course. Students with two attempts in a single course will be allowed to repeat the course only
upon special written permission from the Associate Dean. Students who have not successfully
completed a course within three attempts will not be eligible to graduate from their respective
program.


text:
# Changelog

## 5.2.1

- Fix bug where block creation toggle could get stuck open

## 5.2.0

- Address embed issues where manually typing in HTML was impossible

## 5.1.0

- Generate a unique ID for <Field /> and its associated label
- Content may now be updated by passing a key/value pair to
  `onChange`. See the following section for more info.

### Content may now be updated by passing a key/value pair

We've hit many situations where we need to update a deeply nested key
in CK. This is particularly painful when updating an index of an
array:

```javascript
let tags = this.props.metadata.tags.concat()

tags[1] = 'jellybeans'

this.props.onChange({
  metadata: { ...this.props.content.metadata, tags }
})`
```

Instead, with this release you can provide a key path. This behaves
similarly to [Lodash's set function](https://lodash.com/docs#set):

```
this.props.onChange('title', 'My Dessert Foods')
this.props.onChange('metadata.tags.1', 'jellybeans')
```

By providing a string of `dot` separated values, CK will drill down
into content properties on your behalf. This aims to greatly improve
the ergonomics of updating nested keys.

## 5.0.2

- Fix build issue where Object.assign compiled to `true`

## 5.0.1

- Remove uglify step to avoid unexpected minification errors

## 5.0.0

Upgrade to support React 16.0

### Breaking Changes

Component definitions must now be React class instances. If your
components use the React.createClass syntax, consider moving over to
ES6 classes, or use the `react-create-class` package.

## 4.3.0

- Inline the uid module

## 4.2.1

- Use ref callback pattern. This change removes deprecation warnings in
  the browser console when Colonel Kurtz is used with React 15.6.0.

## 4.2.0

- Add `maxDepth` config option to ColonelKurtz application

## 4.1.0

- Blocks assign default content when mounted. This is technically a
  bug, but the fix impacts content assignment (default values will
  start to show up), so we're releasing it under a minor revision.

## 4.0.0

- Upgraded dependencies
- Removed deprecation warnings for React 15.x
- Added support for React 15.x

## 3.5.1

- Added a style tag to the HTML embed addon to cut default body margins

## 3.5.0

- Added a fallback state for when a block type is not recognized.

## 3.4.0

- Upgrade Microcosm to 9.21.x
- The `<Field />` component is once again controlled. Upgrading
  Microcosm addressed issues with using a controlled input inside
  of this add-on.
- Fix html embed styles

### Upgrading

If you are using the `<Field />` component, verify that it continues to
work as expected. We moved away from controlled inputs in a prior
release when we were unable to determine why cursor position would
erratically move to the end of an input when it changed. This was due
to a way older versions of Microcosm batched state changes
together. This is no longer an issue, so we moved back to the original
controlled strategy.

If you would like to keep the old behavior, instead of passing a
`value` property into the `<Field />` component, send in
`defaultValue`. This is the method exposed by React for uncontrolled
inputs.

For more information on controlled inputs, see the React
documentation:

https://facebook.github.io/react/docs/forms.html#controlled-components

## 3.3.0

- Added `html-embed` add-on. This component may be used to include
  HTML and accompanying scripts within Colonel Kurtz.

## 3.2.0

- The menu item component is now available as the third argument of
  onClick handlers for custom menu items.

## 3.1.1

- Fixed style issue in Firefox where menu items were truncated

## 3.1.0

- Added a `clientOnly` property to blocks. This is a boolean property
  indicating if the block was created by the user during the current
  editing session (as opposed to being present when the editor starts).

## 3.0.0

- **Important Update**: This update makes breaking changes to support
  React 0.14. colonel-kurtz now takes advantage of
  `react-addons-css-transition-group` and utilizes `react-dom` for
  rendering.

## 2.23.1

- Address bug where default content block information was not
  respected.

## 2.23.0

### Noticeable Changes

- The BlockType creator menu now properly displays focus state
- BlockTypes given a `group` property will display as a dropdown in
  the BlockType creator menu.

### Upgrading

All changes are non-breaking. For those not including the Colonel
Kurtz stylesheet via `node_modules`, you will need to update your
stylesheet in order to benefit from the new focus state on the
BlockType creator menu

BlockTypes can be grouped! To do this, add a `group` property to your
block type like so:

```javascript
let blockTypes = [
  {
    id: 'youtube',
    group: 'Embedded'
    // other props
  },
  {
    id: 'twitter',
    group: 'Embedded'
    // other props
  },
  {
    id: 'facebook',
    group: 'Embedded'
    // other props
  }
]
```

## 2.22.0

### Noticeable Changes

- Added a `hint` property the `<Field />`
- Added `uid` dependency to generate unique ids for `<Field />` hints
- Updated some development dependencies
- The YouTube addon will now accept a URL in addition to ID. The ID of
  the YouTube video will be extracted and saved (no breaking change)
- Updated the labels and hints for the YouTube addon to make it clear
  that a URL may also be pasted into the field.
- Added hint property to `<Embeddable />` to allow hint text on its
  `<Field />` component
- Added padding to right of `<Field />` label to handle very long
  labels colliding with menu button.

### Upgrading

There are small style updates to `<Field />` those not pulling in the
style sheet from node_modules should update theirs accordingly.

## 2.21.0

- The `<Field />` component is no longer a [controlled input](https://facebook.github.io/react/docs/forms.html#controlled-components)
- The `<Field />` component label now wraps its input

## 2.20.0

- Added Embedded common component addon. The YouTube addon now uses it.

## 2.19.0

- BlockTypes are provided a default component definition that only renders children. This is to provide a standard default for block types that are containers for other blocks.
- This project no longer compiles in Babel loose mode.

## 2.18.0

### Noticeable Changes

- Focus places upon the navigation element instead of the first button
  of a block creator menu when opened.
- Improved focus state of block creator menu buttons.
- Added `col-block-editor` and `col-block-children` css hooks
- `Field` component can take an `element` option (for text areas, defaults to `input`)
- Added `allow` property to configuration options to only allow specific blocks
- The Youtube and Image addons strip white space when checking to open
- Upgraded Microcosm to 8.1.0
- Added `root` property to blockTypes. When set to false, it will prevent it from displaying in the default block menu
- Added `maxChildren` property to Colonel instances and BlockTypes to limit the number of children
- Returned "Move up" and "Move down" phrasing in menu items.

## 2.17.0

### Noticeable Changes

- The content object of a block is always defined as an object.

## 2.16.2

### Internal Changes

- Bump react-ink to 0.4

## 2.16.1

### Internal Changes

- Lock down a few dependencies to prevent installation of React 0.14

## 2.16.0

### Noticeable Changes

- Slightly increased padding of switch navigation buttons. This is
  present when block type labels exceed the min-width of those buttons
- Tweaked vertical alignment of secondary add block buttons
- Increased contrast of button focus background for block menu
- Improve animation for menus, add closing animation.
- "Move Up" and "Move Down" have been renamed to "Move Before" and
  "Move After". This is in anticipation for block types that display
  children horizontally.
- `Dialog` addon accepts `title` and `headingComponent` props for
  customizable headings.
- `Dialog` y-axis overflow scrolls when necessary.

### Upgrading

This releases an update to the stylesheet. If you are not including it
from `node_modules`, be sure to pull down the latest files from `./style`

# 2.15.0

### Noticeable Changes

- The menu to add new blocks will now collapse when the escape key is
  pressed.
- Refactored switch navigation to be smarter about secondary
  buttons.
- Improved animation for switches. Refactored Switch css

### Upgrading

This releases an update to the stylesheet. If you are not including it
from `node_modules`, be sure to pull down the latest files from `./style`

## 2.14.0

New style updates warranted a minor release, however we also
refactored some internal components related to block type navigation.

### Noticeable Changes

- Improved the appearance and opening animation of the dialog addon
- Improved focus for switch navigation
- Fixed a case where an error would be thrown related to menus of torn
  down blocks.

### Upgrading

The stylesheet for this release was updated, for a stylesheet specific
to this version, reference the `style` directory that is pulled down
with the `npm` module.

## 2.13.0

### Breaking changes

- Custom menu items are no longer defined in `statics`. Instead, they
  are returned from a `getMenuItems` method on the component itself.
- The component lifecycle method `menuWillSelect` has been
  removed. For the purposes it was required for, `getMenuItems` is sufficient

### Upgrading

- For those using custom menu items, see the updated `menu.md` doc for
  the updated API.

## 2.12.2

- `react-ink` was missing in the build. Originally it was compiled
  into the main payload, this changed when we updated the build
  process. `react-ink` is now a standard dependency.

## 2.12.1

- Publishing to NPM occurs by pushing the `dist` folder. Instead, the root folder was published

## 2.12.0

### Breaking changes

- Addons are now available directly under
  `colonel-kurtz/addons`, their `colonel-kurtz/build` counterparts
  have been removed. This is due to a change in the build process to
  help expose components for use when building new UI.

### Noticeable Changes

- New menu items may now be added on an individual block type
  level. For more information, see `./docs/menus.md`
- Style for addons has been moved to `./style/addons` so that it is
  easier to pull down all styles at once or reference the directory in
  `node_modules`.

### Upgrading

This release has a breaking change to improve the ease of including
React components defined by Colonel Kurtz when building new block
types. If you are including addons, the following change is necessary:

In the case of the YouTube component addon, in the previous release it
can be included using:

`let YouTube = require('colonel-kurtz/build/addons/youtube')`

This has now become:

`let YouTube = require('colonel-kurtz/addons/youtube')`

## 2.11.0

### Noticeable Changes

- Youtube and Image components can accept children. This is intended
  to better support additional fields.

## 2.10.0

### Noticeable Changes

- Colonel Kurtz will now inherit theme colors from upcoming
  active_material gem. Beyond exposing variables, no visual
  differences should be observed.

### Bug fixes

- Fixed some style inconsistencies in Firefox

## 2.9.0

### Noticeable Changes

- Colonel's `blocks` option can accept an input or textarea

## 2.8.0

As of this release, we will break out changes into those noticeable to
users and those internal to Colonel itself.

### Noticeable changes

- Menu items will always display for moving blocks. If a block can not
  be moved further, the item will be disabled.

### Internal changes

- Change internal moving method to eliminate edge cases and fragility
- Increase test coverage

## 2.7.0

- Add experimental "Section" block type addon

## 2.6.0

- Reworked build process to speedup setup time

## 2.5.2

- Externalize react-focus-trap so it gets patches

## 2.5.1

- Upgrade react focus trap for better focus management of menus

## 2.5.0

- Upgraded Microcosm to 7.0.0.
- Renamed Toolbar to Menu, be sure to upgrade CSS with this change.
- Refactored some internals, though nothing should surface itself

## 2.4.0

- Set up more sharing between Youtube and Image addons
- Improve animations of Image and Youtube UI

## 2.3.0

- Refined YouTube UI

## 2.2.0

- Added a section addon
- Improved focus state of buttons

## 2.1.1

- Internal updates. We make better use of `react-focus-trap` and
  resolve some testing issues

## 2.1.0

- Menus will no longer automatically close, this is to improve the
  experience of keyboard navigation

## 2.0.1

- Fixed main entry point

## 2.0.0

- Each Colonel Kurtz is now an isolated instance with its own state
- Refactored internals to achieve higher test coverage
- Compliance with React 0.13.0
- Updated UI to better support nested blocks
- Added block menus (instead of just a remove button)
- Colonel Kurtz is now a layer on top of
  [Microcosm](https://github.com/vigetlabs/microcosm/). It now
  benefits from the features provided by this system.
- Added a plugin system which will run before Colonel Kurtz starts

### Breaking changes

- `addCallback` is now `listen`
- `removeCallback` is now `ignore`
- `simulateChange` is now `emit`
- Block types must provided within the `blockTypes` key when instantiating Colonel Kurtz
- `render` is now `start`. `start` comes from Microcosm and will run
  through all configured plugins and render the app.

repository: vigetlabs/colonel-kurtz

gha_language: JavaScript

repo_name: vigetlabs/colonel-kurtz


text:
---
author:
  avatar: https://avatars.githubusercontent.com/u/64388301?v=4
  email: null
  name<EMAIL_ADDRESS>  url: null
  username: nine-theme
bugs: https://github.com/nine-theme/vuepress-plugin-comments/issues
category: plugin
date: '2020-08-13T02:31:02.302Z'
deprecated: false
description: vuepress' comments plugin for vuepress
downloads: null
homepage: https://github.com/nine-theme/vuepress-plugin-comments#readme
keywords:
- vuepress
- comments
license: MIT License
maintainers: null
name: '@nines/vuepress-plugin-comments'
npm: https://www.npmjs.com/package/%40nines%2Fvuepress-plugin-comments
publisher:
  avatar: null
  email<EMAIL_ADDRESS>  name: null
  url: null
  username: wangjia_1919
repository: https://github.com/nine-theme/vuepress-plugin-comments
score: 0.4186036623656289
stars: 0
unstable: true
version: 0.0.2
watchers: 0

---

# vuepress-plugin-comments
![GitHub last commit](https://img.shields.io/github/last-commit/nine-theme/vuepress-plugin-comments)
![npm (scoped)](https://img.shields.io/npm/v/@nine-theme/vuepress-plugin-comments)
![npm](https://img.shields.io/npm/dt/@nine-theme/vuepress-plugin-comments)
![NPM](https://img.shields.io/npm/l/@nine-theme/vuepress-plugin-comments)

---
vuepress theme comments

repository: ahmad-swedani/vuepress-tools

repo_name: ahmad-swedani/vuepress-tools


text:
# generator-black-ds [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Status][daviddm-image]][daviddm-url]
> Generator for Black Design System

## Installation

First, install [Yeoman](http://yeoman.io) and generator-black-ds using [npm](https://www.npmjs.com/) (we assume you have pre-installed [node.js](https://nodejs.org/)).

```bash
npm install -g yo
npm install -g generator-black-ds
```

Then generate your new project:

```bash
yo black-ds
```

## Getting To Know Yeoman

 * Yeoman has a heart of gold.
 * Yeoman is a person with feelings and opinions, but is very easy to work with.
 * Yeoman can be too opinionated at times but is easily convinced not to be.
 * Feel free to [learn more about Yeoman](http://yeoman.io/).

## License

MIT © [José Luis Vizcaíno Martínez](xjoshx.github.com)

[npm-image]: https://badge.fury.io/js/generator-black-ds.svg
[npm-url]: https://npmjs.org/package/generator-black-ds
[travis-image]: https://travis-ci.org/xJoshx/generator-black-ds.svg?branch=master
[travis-url]: https://travis-ci.org/xJoshx/generator-black-ds
[daviddm-image]: https://david-dm.org/xJoshx/generator-black-ds.svg?theme=shields.io
[daviddm-url]: https://david-dm.org/xJoshx/generator-black-ds

repository: blackwoodseven/generator-design-system

repo_name: blackwoodseven/generator-design-system


text:
# PyVora
Snake game like on old Nokia phones

## Clone proyect

```bash
git clone git@github.com:SaulHormazabal/PyVora.git
```

## Install dependencies

This game use the PyGame library, for the installation follow the next link.

[http://www.pygame.org/download.shtml](http://www.pygame.org/download.shtml)

## Feel homesick

```bash
python main.py
```

repository: SaulHormazabal/PyVora

repo_name: SaulHormazabal/PyVora


text:
# go-ruleguard

![Build Status](https://github.com/quasilyte/go-ruleguard/workflows/Go/badge.svg)
![Build Status](https://github.com/quasilyte/go-ruleguard/workflows/Merge/badge.svg)
[![PkgGoDev](https://pkg.go.dev/badge/mod/github.com/quasilyte/go-ruleguard)](https://pkg.go.dev/mod/github.com/quasilyte/go-ruleguard)

![Logo](_docs/logo2.png)

## Overview

[analysis](https://pkg.go.dev/golang.org/x/tools/go/analysis)-based Go linter that runs dynamically loaded rules.

**Features:**

* Custom linting rules without re-compilation and Go plugins
* Diagnostics are written in a declarative way
* [Quickfix](_docs/dsl.md#suggestions-quickfix-support) actions support
* Powerful match filtering features, like expression [type pattern matching](_docs/dsl.md#type-pattern-matching)
* Not restricted to AST rules; it's possible to write a comment-related rule, for example
* Rules can be installed and distributed as [Go modules](https://quasilyte.dev/blog/post/ruleguard-modules/)
* Rules can be developed, debugged and profiled using the conventional Go tooling
* Integrated into [golangci-lint](https://github.com/golangci/golangci-lint)

It can also be easily embedded into other static analyzers. [go-critic](https://github.com/go-critic/go-critic) can be used as an example.

## Quick start

It's advised that you get a binary from the [latest release](https://github.com/quasilyte/go-ruleguard/releases/tag/v0.3.18) {[linux/amd64](https://github.com/quasilyte/go-ruleguard/releases/download/v0.3.18/ruleguard-linux-amd64.zip), [linux/arm64](https://github.com/quasilyte/go-ruleguard/releases/download/v0.3.18/ruleguard-linux-arm64.zip), [darwin/amd64](https://github.com/quasilyte/go-ruleguard/releases/download/v0.3.18/ruleguard-darwin-amd64.zip), [darwin/arm64](https://github.com/quasilyte/go-ruleguard/releases/download/v0.3.18/ruleguard-darwin-arm64.zip), [windows/amd64](https://github.com/quasilyte/go-ruleguard/releases/download/v0.3.18/ruleguard-windows-amd64.zip), [windows/arm64](https://github.com/quasilyte/go-ruleguard/releases/download/v0.3.18/ruleguard-windows-arm64.zip)}.

If you want to install the ruleguard from source, it's as simple as:

```bash
# Installs a `ruleguard` binary under your `$(go env GOPATH)/bin`
$ go install -v github.com/quasilyte/go-ruleguard/cmd/ruleguard@latest

# Get the DSL package (needed to execute the ruleguard files)
$ go get -v -u github.com/quasilyte/go-ruleguard/dsl@latest
```

> If inside a Go module, the `dsl` package will be installed for the current module,
> otherwise it installs the package into the $GOPATH and it will be globally available.

If `$GOPATH/bin` is under your system `$PATH`, `ruleguard` command should be available after that:

```bash
$ ruleguard -help
ruleguard: execute dynamic gogrep-based rules

Usage: ruleguard [-flag] [package]

Flags:
  -rules string
    	comma-separated list of ruleguard file paths
  -e string
    	execute a single rule from a given string
  -fix
    	apply all suggested fixes
  -c int
    	display offending line with this many lines of context (default -1)
  -json
    	emit JSON output
```

Create a test `rules.go` file:

```go
//go:build ruleguard
// +build ruleguard

package gorules

import "github.com/quasilyte/go-ruleguard/dsl"

func dupSubExpr(m dsl.Matcher) {
	m.Match(`$x || $x`,
		`$x && $x`,
		`$x | $x`,
		`$x & $x`).
		Where(m["x"].Pure).
		Report(`suspicious identical LHS and RHS`)
}

func boolExprSimplify(m dsl.Matcher) {
	m.Match(`!($x != $y)`).Suggest(`$x == $y`)
	m.Match(`!($x == $y)`).Suggest(`$x != $y`)
}

func exposedMutex(m dsl.Matcher) {
	isExported := func(v dsl.Var) bool {
		return v.Text.Matches(`^\p{Lu}`)
	}

	m.Match(`type $name struct { $*_; sync.Mutex; $*_ }`).
		Where(isExported(m["name"])).
		Report("do not embed sync.Mutex")

	m.Match(`type $name struct { $*_; sync.RWMutex; $*_ }`).
		Where(isExported(m["name"])).
		Report("do not embed sync.RWMutex")
}
```

Create a test `example.go` target file:

```go
package main

import "sync"

type EmbedsMutex struct {
	key int
	sync.Mutex
}

func main() {
	var v1, v2 int
	println(!(v1 != v2))
	println(!(v1 == v2))
	if v1 == 0 && v1 == 0 {
		println("hello, world!")
	}
}
```

Run `ruleguard` on that target file:

```bash
$ ruleguard -rules rules.go -fix example.go
example.go:5:1: exposedMutex: do not embed sync.Mutex (rules.go:24)
example.go:12:10: boolExprSimplify: suggestion: v1 == v2 (rules.go:15)
example.go:13:10: boolExprSimplify: suggestion: v1 != v2 (rules.go:16)
example.go:14:5: dupSubExpr: suspicious identical LHS and RHS (rules.go:7)
```

Since we ran `ruleguard` with `-fix` argument, both **suggested** changes are applied to `example.go`.

There is also a `-e` mode that is useful during the pattern debugging:

```bash
$ ruleguard -e 'm.Match(`!($x != $y)`)' example.go
example.go:12:10: !(v1 != v2)
```

It automatically inserts `Report("$$")` into the specified pattern.

You can use `-debug-group <name>` flag to see explanations
on why some rules rejected the match (e.g. which `Where()` condition failed).

The `-e` generated rule will have `e` name, so it can be debugged as well.

## How does it work?

First, it parses [ruleguard](_docs/dsl.md) files (e.g. `rules.go`) during the start to load the rule set.

Loaded rules are then used to check the specified targets (Go files, packages).

The `rules.go` file is written in terms of [`dsl`](https://pkg.go.dev/github.com/quasilyte/go-ruleguard/dsl) API. Ruleguard files contain a set of functions that serve as a rule groups. Every such function accepts a single [`dsl.Matcher`](https://pkg.go.dev/github.com/quasilyte/go-ruleguard/dsl#Matcher) argument that is then used to define and configure rules inside the group.

A rule definition always starts with [`Match(patterns...)`](https://pkg.go.dev/github.com/quasilyte/go-ruleguard/dsl#Matcher.Match) method call and ends with [`Report(message)`](https://pkg.go.dev/github.com/quasilyte/go-ruleguard/dsl#Matcher.Report) method call.

There can be additional calls in between these two. For example, a [`Where(cond)`](https://pkg.go.dev/github.com/quasilyte/go-ruleguard/dsl#Matcher.Where) call applies constraints to a match to decide whether it's accepted or rejected. So even if there is a match for a pattern, it won't produce a report message unless it satisfies a `Where()` condition.

## Troubleshooting

For ruleguard to work the `dsl` package must be available at _runtime_. If it's not, you are going to see an error like:

```
$ ruleguard -rules rules.go .
ruleguard: load rules: parse rules file: typechecker error: rules.go:6:8: could not import github.com/quasilyte/go-ruleguard/dsl (can't find import: "github.com/quasilyte/go-ruleguard/dsl")
```

This is fixed by adding the dsl package to the module:

```
$ ruleguard-test go get github.com/quasilyte/go-ruleguard/dsl
go: downloading github.com/quasilyte/go-ruleguard v0.3.18
go: downloading github.com/quasilyte/go-ruleguard/dsl v0.3.21
go: added github.com/quasilyte/go-ruleguard/dsl v0.3.21
$ ruleguard-test ruleguard -rules rules.go .
.../test.go:6:5: boolExprSimplify: suggestion: 1 == 0 (rules.go:9)
```

If you have followed past advise of using a build constraint in the rules.go file, like this:

```
$ ruleguard-test head -4 rules.go
//go:build ignore
// +build ignore

package gorules
```

you are going to notice that `go.mod` file lists the dsl as an indirect dependency:

```
$ grep dsl go.mod
require github.com/quasilyte/go-ruleguard/dsl v0.3.21 // indirect
```

If you run `go mod tidy` now, you are going to notice the dsl package disappears from the `go.mod` file:

```
$ go mod tidy
$ grep dsl go.mod
$
```

This is because `go mod tidy` behaves as if all the build constraints are in effect, _with the exception of `ignore`_. [This is documented in the go website](https://go.dev/ref/mod#go-mod-tidy).

This is fixed by using a different build constraint, like `ruleguard` or `rules`.

## Documentation

* [Ruleguard by example](https://go-ruleguard.github.io/by-example/) tour
* [Ruleguard files](_docs/dsl.md) format documentation
* [dsl package](https://pkg.go.dev/github.com/quasilyte/go-ruleguard/dsl) reference
* [ruleguard package](https://pkg.go.dev/github.com/quasilyte/go-ruleguard/ruleguard) reference
* Introduction article: [EN](https://quasilyte.dev/blog/post/ruleguard/), [RU](https://habr.com/ru/post/481696/)
* [Using ruleguard from the golangci-lint](https://quasilyte.dev/blog/post/ruleguard/#using-from-the-golangci-lint)

## Rule set examples

* Basic rule set from the ruleguard: [go-ruleguard/rules](rules)
* [Damian Gryski](github.com/dgryski/) rule set: [github.com/dgryski/semgrep-go/ruleguard.rules.go](https://github.com/dgryski/semgrep-go)
* [go-critic](https://github.com/go-critic/go-critic) rule set: [github.com/go-critic/go-critic/checkers/rules/rules.go](https://github.com/go-critic/go-critic/blob/master/checkers/rules/rules.go)
* Partial [Uber-Go](https://github.com/uber-go/guide) style rule set: [github.com/quasilyte/uber-rules](https://github.com/quasilyte/uber-rules)
* [go-perfguard](https://github.com/quasilyte/go-perfguard) rule set: [github.com/quasilyte/go-perfguard/perfguard/_rules/universal_rules.go](https://github.com/quasilyte/go-perfguard/blob/master/perfguard/_rules/universal_rules.go)

Note: `go-critic` and `go-perfguard` embed the rules using the IR precompilation feature.

## Extra references

* Online ruleguard playground: [go-ruleguard.github.io/play](https://go-ruleguard.github.io/play)
* [gogrep](https://github.com/quasilyte/gogrep) - underlying AST matching engine
* [NoVerify: Dynamic Rules for Static Analysis](https://medium.com/@vktech/noverify-dynamic-rules-for-static-analysis-8f42859e9253)
* [Ruleguard comparison with Semgrep and CodeQL](https://speakerdeck.com/quasilyte/ruleguard-vs-semgrep-vs-codeql)

repository: quasilyte/go-ruleguard

gha_language: Go

repo_name: quasilyte/go-ruleguard


text:
# datasig
Generating signature of data structures to check compatibility

The aim is to check for data structure change during compile time to catch incompatible binary changes.

This idea is to use gdb to recursively dump a global structure (mainly offset and size of each fields) and generate checksum of the output.


text:
***ApiMonkey is undergoing a major overhaul for version 1.0.0***

# ApiMonkey
Makes building data-driven APIs in Rails a breeze by providing an easy to use DSL for declaring API resources.

[ ![Codeship Status for thebadmonkeydev/api_monkey](https://img.shields.io/codeship/4e0f5230-d46d-0133-21d4-0af10aec3b5e/master.svg)](https://codeship.com/projects/142421)
[![Code Climate](https://codeclimate.com/github/thebadmonkeydev/api_monkey/badges/gpa.svg)](https://codeclimate.com/github/thebadmonkeydev/api_monkey)
[![Test Coverage](https://codeclimate.com/github/thebadmonkeydev/api_monkey/badges/coverage.svg)](https://codeclimate.com/github/thebadmonkeydev/api_monkey/coverage)
[![Issue Count](https://codeclimate.com/github/thebadmonkeydev/api_monkey/badges/issue_count.svg)](https://codeclimate.com/github/thebadmonkeydev/api_monkey)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'api_monkey'
```

And then execute:

    $ bundle

## Usage
Once you have ApiMonkey installed, declare your model as an ApiMonkey model:

```ruby
# app/models/product.rb

class Product < ActiveRecord::Base
  include ApiMonkey
end
```

### Filter Params
Filter params provide a clean and easy way to add request-based
filtering of your active record models.  To use filter params, ApiMonkey
expects the parameters send to rails to resolve like this:

```ruby
# http://my.domain/products?filter[price]=200

{
  filter: {
    price: 200
  }
}
```
This would filter our Product query to only those with `price = 200`

More complex filters can be applied using an operator shorthand that
allows for equality and comparison operators.  The list of possible
operators are:

|SQL Operator|Operator Shorthand|
|---|---|
|=|eq|
|>|gt|
|<|lt|
|<=|leq|
|>=|geq|

To use these, just change the concrete value for `price` in the above
hash to it's own hash using the operators as keys:

```ruby
# http://my.domain/products?filter[price[gt]]=200

{
  filter: {
    price: {
      'gt' => 200
    }
  }
}
```

Or:

```ruby
# http://my.domain/products?filter[price[gt]]=200&filter[price[leq]]=350

{
  filter: {
    price: {
      'gt' => 200,
      'leq' => 350
    }
  }
}
```

To use ApiMonkey in an exisitng Rails app, you have to include the ApiMonkey module in your model like this:

```ruby
class Product < ActiveRecord::Base
  include ApiMonkey
end
```

This will create all the necessary filtering methods that will be used
in your controller.  Next we want to add the filter to our controller. Use a methodology similar to
strong parameters.  We recommend using a controller method like this:

```ruby
# app/controllers/products_controller.rb

class ProductsController < ApplicationController
  def index
    @products = if params[:filter]
                  Product.filter(filter_params)
                else
                  Product.all
  end

  protected

  def filter_params
    params.require(:filter).permit(Product.filter_params)
  end
end
```

`Model.filter_params` is a simple hash so it supports methods like
`include` and `except` to help control the fields that can be filtered
against.
`filter` is designed so that passing either `nil` or `{}` to it will
produce an empty set (`where(nil)`). Therefore, you should ensure that
filter exists as a key in `params`. Passing `nil` to one of the
`filter_xxx` will result in a `where(xxx: nil)`.

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake rspec` 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`. To release a new version, update the version number in `version.rb`, and then 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).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/michaelkelly322/api_resource. Guidelines and suggestion can be found in our [CONTRIBUTE.md file](https://github.com/michaelkelly322/api_monkey/blob/master/CONTRIBUTE.md). This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
---
title: "Enoch"
pdf: "enoch.pdf"
description: "the man who \"was not, because God took him.\""
tableOfContents: false
template: topic.jade
---

by Pastor Mark Perkins, Front Range Bible Church, Denver, Colorado

Genesis 5:22-24 tells Enoch’s story:

“Enoch lived with God for three hundred years after the birth of
Methuselah (his son). Thus all the days of Enoch came to three hundred
and sixty five years. Enoch lived with God, and he was not, for God took
him.”

Hebrews 11:5 provides us with further interpretation:

“By faith Enoch was transferred [to heaven] so that he should not see
death; and he was not found because God took him up; for he obtained the
witness that before his being taken up he was pleasing to God.”

Jude verses 14 and 15 quotes from the apocryphal book of Enoch, and it
says,

“And about these also Enoch, in the seventh generation from Adam,
prophesied, saying,”Behold, the Lord came with many thousands of His
holy ones, to execute judgmeent upon all, and to convict all the ungodly
of all their ungodly deeds which they have done in an ungodly way, and
of all the harsh things which ungodly sinners have spoken against Him."

When he was sixty five years of age, Enoch was transferred - body, soul,
and spirit - to the presence of God in heaven. There he stayed for three
hundred years, at which time his soul and spirit were painlessly removed
from his body, and he was transferred to paradise.

Enoch also was a prophet while he remained on planet earth, and he
talked about his own generation, as evidenced by his prophecy recorded
in Jude’s epistle.

Enoch lived in a time of great apostasy. This time began during the life
of Enosh, and was fully developed by the time Enoch came around.

The apostasy of that time was unbridled, since the Mosaic law had not
yet been written.

Rom. 5:20, “And the Law came in the side door, so that the sin might
increase; but where sin increased, grace abounded all the more.”

The time included a tremendous amount of demonism, even to the point of
sexual relations with them. The demons were attacking the genetic line
of Christ, hoping to pollute His human genetic purity and thus destroy
His role as mediator.

Therefore, they seduced human women (and only women), and impregnated
them. By the time of Noah’s life, all but Noah’s family had succumbed.

The human women were weakened by their hatred of God (see Enosh), and
easily enticed by the attractiveness of these demons.

There was great violence, and the human race was in a constant state of
war. The half-angelic humans had great superhuman powers (see Hermes,
Aphrodite, Apollo, Neptune, etc.), and they were superintelligent and
superattractive (see Helen of Troy and Aphrodite) as well.

Many strange and terrible creatures roamed the earth, the brood of
demons. Their fossil record remains - thanks to the great fossilizing
powers of the flood.

It was in this time that Enoch lived, moved to maturity following the
plan of God, and was transferred to heaven by the omnipotence of God.
Enoch did not see physical death because of his maturity, and he stands
as a precursor to resurrection.

-   Although Enoch was not truly resurrected, his transfer to heaven was
    very much like a resurrection.

 It is probably a comment on his maturity that
    he was able to stand it, though in his sinful body.

-   After three hundred years of life with God, he was then transferred
    to paradise, under the earth.

-   At the resurrection of Christ he was transferred to heaven along
    with all the Old Testament Saints.

repository: grace-notes/website

gha_language: CoffeeScript

repo_name: grace-notes/website


text:
PIDantic
========

This library is an abstraction for communicating with child processes.
The processes can run via supervisord or within an ION
container.  This code should provide a seamless interface to both
allowing the user to start/stop/monitor processes without the concern
of how the processes were run.

The specifics of communicating with the different types of processes
is handled in PIDantic drivers.  The drivers may implement any blocking
IO with gevent.

Using PIDantic
--------------

To use PIDantic, you must create a PIDantic factory, and then you can
use this factory to start processes.

### SupervisorD

An example of how to start an interact with a process:

    from pidantic.supd.pidsupd import SupDPidanticFactory

    # Create our factory
    persistence_directory = "/tmp"
    persistence_name = "pidantic_test"

    factory = SupDPidanticFactory(directory=persistence_directory,
            name=persistence_name)

    # Start a process
    cmd = "sleep 100"
    name = "sleeper"
    dir = persistence_directory

    pid = self.factory.get_pidantic(command=cmd, process_name=name,
            directory=dir)
    pid.start()

    # Check process status
    processes = factory.reload_instances()
    factory.poll()

    # Print status of each process
    for name, process in processes.iteritems():
        print "Process %s has status %s" % (name, process.get_status())

    # Terminate all processes
    for name, process in processes.iteritems():
        process.cleanup()

    # Shut down the factory
    factory.terminate()

Copyright 2013 University of Chicago

repository: ooici/pidantic

repo_name: ooici/pidantic


text:
# express-saml2
High-level API for Single Sign On (SAML 2.0)

##Description

This module provides high-level API for scalable Single Sign On (SSO) implementation. Developers can easily configure the Service Providers and Identity Providers by importing the corresponding metadata. SAML2.0 provides a standard guide but leaves a lot of options, so we provide a simple interface that's highly configurable.

##Glossary

Metadata: A public XML document specifies the entity's preference

Identity Provider: An entity authenticates the users

Service Provider: An entity provides services/resources

##Get Started

```bash
$ git clone https://github.com/tngan/express-saml2.git
```

##Branches

Currently we are working on v1.1, it will be noticed if we are ready to release the alpha version. In terms of long term development and integration, for those who love coding with ES6, we are happy to announce that we will embrace ES6 later on, and compile with [Babel](https://babeljs.io/).

##API Reference
```javascript
var saml = require('express-saml2');
```
###Entity-Level API
This type of API defines the actions taken by the entity, is designed to be called directly in the routing files.

####Entity
The following methods can be used in `IdentityProvider` and `ServiceProvider`:
```
methods:
	+ getEntityID()
        Get the entity ID specifies in metadata<br/>
	+ getEntitySetting()
        Get the entity Setting
	+ parseMetadata()
        Get the essential elements from metadata
	+ getMetadata()
        Get the metadata in XML format
	+ exportMetadata(exportFile)
        parameter:
        | exportFile <string> - file path (e.g. ./path/mymetadata.xml)
        Export the metadata to a file
	+ entityMeta
        Get the Metadata object
```

####IdentityProvider
#####Construct a new Identity Provider
```
methods:
	+ saml.IdentityProvider(setting,metadata)
		Construct it by both metadata and setting
	+ saml.IdentityProvider(metadata)
		Construct it by importing metadata, use unless you confirm that the idp follows our default setting
	+ saml.IdentityProvider(setting)
		(Advanced) Construct it by custom setting, a new metadata will be also generated

parameters:

  + metadata <string> - path of the metadata (e.g. ./path/mymetadata.xml)
  + setting <object> - declares the perference of identity provider

  symbol representation
    o: optional
    m: must set if metadata is not imported

  {
    requestSignatureAlgorithm <string|o>  Default is 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'
    loginResponseTemplate <string|o>      Login response template (#1)
    logoutRequestTemplate <string|o>      Logout request template (#1)
    generateID <function|o>               Function to generate the ID of request/response
    entityID <string>                     Define the entity ID, a.k.a issuer
    privateKeyFile <string|o>             File path of .pem file
    privateKeyFilePass <string|o>         Set if your .pem file has protected passpharse (recommend)
    signingCertFile <string|m>            File path of .cer file which is your X.509 certificate (#2)
    nameIDFormat <[string]|o>             Define the support name ID format
    singleSignOnService <[object]|m>      Define binding and location of each single sign on service
    singleLogoutService <[object]|o>      Define binding and location of each single logout service (#3)
    wantAuthnRequestsSigned <boolean|o>   Define whether login request need signature (Default is false) (#4)
    wantLogoutResponseSigned <boolean|o>  Define whether logout response need signature (Default is false) (#5)
  }

remarks:

  #1: Need to set up another callback function in order to dynamically replace the tag in template
  #2: We recommend to have signature so this field should be specified when metadata is not imported
  #3: Optional depends on whether you provide logout service in your user case
  #4: Service Provider signs login request if set to true
  #5: Service Provider signs logout response if set to true
```
#####Example
```javascript
// Sample of IDP setting used to construct an identity provider
var idpSetting = {
    entityID:'https://idp.example.org/metadata',
    nameIDFormat:['urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'],
    privateKeyFile: './privateKey.pem',
    privateKeyFilePass: 'myPassword',
    signingCertFile: './certificate.cer',
    singleSignOnService:[{
        Binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
        Location: 'https://idp.example.org/sso/SingleSignOnService'
    },{
        Binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        Location: 'https://idp.example.org/sso/SingleSignOnService'
    }],
    singleLogoutService:[{
        Binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
        Location: 'https://idp.example.org/sso/SingleLogoutService'
    },{
        Binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        Location: 'https://idp.example.org/sso/SingleSignOnService'
    }]
};

// Example 1: Construct Identity Provider manually
var idp = saml.IdentityProvider(idpSetting);

// Example 2: Construct Identity Provider with metadata and without signing key
var idp = saml.IdentityProvider('./metadata_idp.xml');

//  Example 3: Construct Identity Provider with metadata and include signing key
var idp = saml.IdentityProvider({
    privateKeyFile: './privateKey.pem',
    privateKeyFilePass: 'myPassword'
},'./metadata_idp.xml');
```
#####Actions taken by Identity Provider
```
methods:

	+ idp.sendLoginResponse(sp,requestInfo,binding,user,callback,rcallback)

        parameters:
        | sp <ServiceProvider>   Declare the target entity
		| requestInfo <object>   Callback parameter from parseLoginRequest (set null when idp-initiated)
        | binding <string>       Define the binding used to send login response, only support 'post'
        | user <object>          User information in your session (e.g. req.user)
        | callback <function>    Function with parameters rendered in a form post
        | rcallback <function|o> Function with loginResponseTemplate defined in setting object (#1)

        Generates the login response and callback to developers to design their own method

	+ idp.parseLoginRequest(sp,binding,req,callback)

        parameters:
        | sp <ServiceProvider>   Declare the source entity
        | binding <string>       Define the binding of login request is received, 'post' or 'redirect'
        | req <object>           req object in express
        | callback <function>    Function with parameter

        Validation and callback parsed the URL parameters (#2)

	+ idp.sendLogoutRequest(sp,binding,user,relayState,callback,rcallback)

        parameters:
        | sp <ServiceProvider>   Declare the target entity
        | binding <string>       Define the binding used to send logout request, 'post' or 'redirect'
        | user <object>          User information in your session (e.g. req.user)
        | relayState <string>    URL to which to redirect the user when logout is complete
        | req <object>           req object in express
        | callback <function>    Function with parameter
          - callback(url)        url is the logout request redirect URL (Redirect binding)
          - callback(obj)        parameters rendered in a form post (Post binding)
        | rcallback <function|o> Function with logoutRequestTemplate defined in setting object (#1)

        Generates the logout request and callback to developers to design their own method

	+ idp.parseLogoutResponse(sp,binding,req,callback)

        parameters:
        | sp <ServiceProvider>   Declare the source entity
        | binding <string>       Define the binding of logout response is received, 'post' or 'redirect'
        | req <object>           req object in express
        | callback <function>    Function with parameters

        Validation and callback parsed the URL parameters

remarks:

  #1: User can replace the tags in their custom logout request template in this rCallback
  #2: We provide basic checking, user can continue their checking in callback function
```

####ServiceProvider
#####Construct a new Service Provider
```
methods:
	+ saml.ServiceProvider(setting,metadata)
		Construct it by both metadata and setting
	+ saml.ServiceProvider(metadata)
		Construct it by importing metadata, use unless you confirm that the idp follows our default setting
	+ saml.ServiceProvider(setting)
		(Advanced) Construct it by custom setting, a new metadata will be also generated

parameters:

  + metadata <string> - path of the metadata (e.g. ./path/mymetadata.xml)
  + setting <object> - declares the perference of service provider

  symbol representation
    o: optional
    m: must set if metadata is not imported

  {
    requestSignatureAlgorithm <string|o>  Default is 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'
    loginRequestTemplate <string|o>       Login request template (#1)
    logoutResponseTemplate <string|o>     Logout response template (#1)
    generateID <function|o>               Function to generate the ID of request/response
    entityID <string>                     Define the entity ID, a.k.a issuer
    privateKeyFile <string|o>             File path of .pem file
    privateKeyFilePass <string|o>         Set if your .pem file has protected passpharse (recommend)
    signingCertFile <string|m>            File path of .cer file which is your X.509 certificate (#2)
    nameIDFormat <[string]|o>             Define the support name ID format
    assertionConsumerService <[object]|m> Define binding and location of each single assertion consumer service
    singleLogoutService <[object]|o>      Define binding and location of each single logout service (#3)
    wantAssertionsSigned <boolean|o>      Define whether assertion need signature (Default is false) (#4)
    wantLogoutRequestSigned <boolean|o>   Define whether logout request need signature (Default is false) (#5)
  }

remarks:

  #1: Need to set up another callback function in order to dynamically replace the tag in template
  #2: We recommend to have signature so this field should be specified when metadata is not imported
  #3: Optional depends on whether you provide logout service in your user case
  #4: Identity Provider signs login assertion (response) if set to true
  #5: Identity Provider signs logout request if set to true
```
#####Example
```javascript
// Sample of IDP setting used to construct an service provider
var spSetting = {
    entityID:'https://sp.example.org/metadata',
    nameIDFormat:['urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'],
    privateKeyFile: './privateKey.pem',
    privateKeyFilePass: 'myPassword',
    signingCertFile: './certificate.cer',
    assertionConsumerService:[{
        Binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
        Location: 'https://sp.example.org/sso/acs'
    },{
        Binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        Location: 'https://sp.example.org/sso/acs'
    }],
    singleLogoutService:[{
        Binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
        Location: 'https://sp.example.org/sso/slo'
    },{
        Binding: 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        Location: 'https://sp.example.org/sso/slo'
    }]
};

// Example 1: Construct Service Provider manually
var sp = saml.ServiceProvider(spSetting);

// Example 2: Construct Service Provider with metadata and without signing key
var sp = saml.ServiceProvider('./metadata_sp.xml');

//  Example 3: Construct Service Provider with metadata and include signing key
var sp = saml.ServiceProvider({
    privateKeyFile: './privateKey.pem',
    privateKeyFilePass: 'myPassword'
},'./metadata_sp.xml');
```
#####Actions taken by Service Provider
```
methods:

	+ sp.sendLoginRequest(idp,requestInfo,binding,callback,rcallback)

        parameters:
        | idp <IdentityProvider>  Declare the target entity
        | binding <string>        Define the binding used to send login request, 'post' or 'redirect'
        | callback <function>     Function with parameters rendered in a form post
          - callback(url)         url is the logout request redirect URL (Redirect binding)
          - callback(obj)         parameters rendered in a form post (Post binding)
        | rcallback <function|o>  Function with loginRequestTemplate defined in setting object (#1)

        Generates the login request and callback to developers to design their own method

	+ sp.parseLoginResponse(idp,binding,req,callback)

        parameters:
        | idp <IdentityProvider>  Declare the target entity
        | binding <string>        Define the binding used to send login response, only support 'post'
        | req <object>            req object in express
        | callback <function>     Function with parameter

        Validation and callback parsed the URL parameters (#2)

	+ sp.sendLogoutResponse(idp,requestInfo,binding,user,relayState,callback,rcallback)

        parameters:
        | idp <IdentityProvider>  Declare the target entity
		| requestInfo <object>    Callback parameter from parseLogoutRequest
        | binding <string>        Define the binding used to send logout response, 'post' or 'redirect'
        | user <object>           User information in your session (e.g. req.user)
        | relayState <string>     URL to which to redirect the user when logout is complete
        | req <object>            req object in express
        | callback <function>     Function with parameter
          - callback(url)         url is the logout response redirect URL (Redirect binding)
          - callback(obj)         parameters rendered in a form post (Post binding)
		| rcallback <function|o>  Function with logoutResponseTemplate defined in setting object (#1)

        Generates the logout response and callback to developers to design their own method

	+ sp.parseLogoutRequest(idp,binding,req,callback)

        parameters:
        | idp <IdentityProvider>  Declare the target entity
        | binding <string>        Define the binding of logout request is received, 'post' or 'redirect'
        | req <object>            req object in express
        | callback <function>     Function with parameters

        Validation and callback parsed the URL parameters

remarks:

  #1: User can replace the tags in their custom logout response template in this rCallback
  #2: We provide basic checking, user can continue their checking in callback function
```

##Use cases & knowledge base
For those who may be interested, there are three express application simulating one identity provider and service provider.

Please install all dependencies before start those three servers:
```bash
$ cd example/
$ npm install
$ nodemon app
```

* localhost:3001 idp
* localhost:4002 sp1
* localhost:4003 sp2

###Implementation 1 - Basic login
Access the above three homepage, you are able to login all three portals without using any single-sign-on strategies, the login credentials are as follow:
```
username<EMAIL_ADDRESS>(idp)/<EMAIL_ADDRESS>(sp1)/<EMAIL_ADDRESS>(sp2)
password: admin123
```
###Implementation 2 - IdP-initiated Single Sign On (SSO)
1. Login `http://localhost:3001` first which is our `idp`.
2. Under the list of services, select one of those services and click login. (e.g. localhost:4002)
3. A SAML response message w/o signature will send back to the assertion consumer service in `sp1`.
4. `sp1` will validate and parse the response message to confirm the user is authenticated.
5. Login to sp1 and redirect to the main page of sp1.
6. Login user with email<EMAIL_ADDRESS>is shown on screen.
7. Steps (1-6) can be repeated to login `sp2`

####Backend code:
In our basic solution, email is assumed to be an unique field and used to identify each user. There is a one-to-many user email mapping in identity provider. When SAML response message is sent, the associated email is included in <saml:NameID> field. In our example, we hard coded the association but better use database to do it in practical.
```javascript
/*
  example/idp/routes/sso.js
*/
  var epn = {
<EMAIL_ADDRESS>: {
          assoHash: '$2a$10$/0lqAmz.r6trTurxW3qMJuFHyicUWsV3GKF94KcgN42eVR8y5c25S',
          app: {
              '369550': {
                  assoSpEmail<EMAIL_ADDRESS>              },
              '369551': {
                  assoSpEmail<EMAIL_ADDRESS>              }
          }
      }
  };
```
###Implementation 3 - SP-initiated Single Sign On (SSO) (Redirect binding)
1. Access `http://localhost/4002/login` which is the login page of `sp1`.
2. Click the login link next to "SP-initiated Single Sign On (Redirect binding)".
3. `sp1` issues a request w/o signature embeded in URL (GET), to `idp` endpoint of single sign on service.
4. If you don't have security context in our `idp`, it will redirect to the login portal of `idp`.
5. If user credentials are correct, `idp` validates request sends a SAML response with associated email to `sp1`.
6. `sp1` will validate and parse the response message to confirm the user is authenticated.
7. Login user with email<EMAIL_ADDRESS>is shown on screen.
8. Steps (1-7) can be repeated to login `sp2`

####Backend code:
We implement Redirect binding using URL redirect. The redirect URL has the format  `http://localhost:3001/sso/SingleSignOnService?SAMLRequest=@SAMLRequest&SigAlg=@SigAlg&RelayState=@RelayState&Signature=@Signature`. Notice that `RelayState`, `SigAlg` and `Signature` are optional depending on the perference of `idp`. `SigAlg` and `Signature` will be issued only when `WantAuthnRequestsSigned` is set to true in idp metadata.
```javascript
/*
    sp1/routes/sso.js
    /sso/spinitsso-redirect is the link to initiate redirect-binding sso from sp
*/
router.get('/spinitsso-redirect',function(req,res){
    sp.sendLoginRequest(idp,'redirect',function(url){
        // url is a string, e.g. http://localhost:3001/sso/SingleSignOnService?SAMLRequest=...
        res.redirect(url);
    });
});
```
###Implementation 4 - SP-initiated Single Sign On (SSO) (POST binding)
1. Access `http://localhost/4002/login` which is the login page of `sp1`.
2. Click the login link next to "SP-initiated Single Sign On (Post binding)".
3. `sp1` issues a SAML request w/o signature in a form post to `idp` endpoint of single sign on service (POST).
4. If you don't have security context in our `idp`, it will redirect to the login portal of `idp`.
5. If user credentials are correct, `idp` validates request sends a SAML response with associated email to `sp1`.
6. `sp1` will validate and parse the response message to confirm the user is authenticated.
7. Login user with email<EMAIL_ADDRESS>is shown on screen.
8. Steps (1-7) can be repeated to login `sp2`

####Backend code:
We implement POST binding using an automatic form submit. Once the `idp` validates and parses the SAML request from `sp1` succcessfully, it will render the parse result to a new page defined in `views/actions.handlebars` as follow:
```javascript
/*
    idp/routes/sso.js
*/
router.post('/SingleSignOnService/:id',function(req,res){
    // ...
    assoIdp.parseLoginRequest(targetSP,'post',req,function(parseResult){
        // ...
        assoIdp.sendLoginResponse(targetSP,parseResult,'post',req.user,function(response){
            res.render('actions',response);
        });
    });
});
/*
  parseResult is an object with parameters as follow:

  + entityEndpoint:   endpoint of the form
  + actionType:       declares the type of actions (SAMLRequest/SAMLResponse/LogoutRequest/LogoutResponse)
  + actionValue:      base64 encoded value
  + relayState:       used for deeper link
*/
```
```html
<form id="saml-form" method="post" action="{{entityEndpoint}}">
    <input type="hidden" name="{{actionType}}" id="{{actionType}}" value="{{actionValue}}" />
    {{#if relayState}}
        <input type="hidden" name="RelayState" id="relayState" value="{{relayState}}" />
    {{/if}}
</form>
<script type="text/javascript">
    (function(){
        document.forms[0].submit();
    })();
</script>
```

###Implementation 5 - Basic Logout
Access the above three homepage after login, you are able to logout all three portals independently without using any single-sign-on strategies.

###Implementation 6 - IdP-initiated Single Logout (SLO)
1. Login `sp1` and `sp2`.
2. Login `idp` and access its management console. http://localhost:3001.
3. Under the list of services, click the login next to `Logout all services`.
4. `idp` issues a logout request w/o signature to the `sp1`.
5. `sp1` validates the logout request and logout the user.
6. `sp1` sends a logout response w/o signature to the `idp`.
7. There exists a field called `relayState` which is used to specified the redirect destination after user logout.
8. `idp` issues another logout request w/o signature to the `sp2`.
9. `sp2` validates the logout request and logout the user.
10. `sp2` sends a logout response w/o signature to the `idp`.
11. Since no more participating service providers, therefore user is also logged out from `idp`.
12. Redirect to the `idp` login portal http://localhost:3001/login.
13. When accessing `sp1` and `sp2`, the browser will redirect you to the corresponding login page.

####Backend code:
We have set `relayState` to go through all participating service providers. When user is logged out from `idp`, also indicated that logged out from `sp1` and `sp2` in our example.

## Customization
### Custom template for login/logout
Developer can design their own request and response template for login and logout respectively. There are optional parameters in entity setting. For example, add `loginResponseTemplate`, `logoutRequestTemplate` in the setting object when `idp` is constructed, and `loginRequestTemplate`, `logoutResponseTemplate` in the setting object when `
```javascript
// Load the template every time before each request/response is sent
var idp = saml.IdentityProvider({
    //...
    loginResponseTemplate: './loginResponseTemplate.xml',
    logoutRequestTemplate: './logoutRequestTemplate.xml'
    //...
},'./metadata_idp.xml');
// or load the template once the application is cached
var idp = saml.IdentityProvider({
    //...
    loginResponseTemplate: '<saml:...>',
    logoutRequestTemplate: '<saml:...>'
    //...
},'./metadata_idp.xml');
```
There is a callback function `rcallback` in each sending action. It will only be called before sending the request/response when custom template is specified. Otherwise, it uses the default template specfied in `SamlLib.js`. The following section is an example using the custom template.
```javascript
// Access http://localhost:4002/sso/spinitsso-redirect to initiate single sign on service
router.get('/spinitsso-redirect',function(req,res){
    sp.sendLoginRequest(idp,'redirect',function(url){
        res.redirect(url);
    },function(loginRequestTemplate){
        // Here is the callback function for custom template
        // the input parameter is the value of loginRequestTemplate
        // The following is the input parameter of rcallback in different actions
        // sp.sendLoginRequest -> loginRequestTemplate
        // sp.sendLogoutResponse -> logoutResponseTemplate
        // idp.sendLoginResponse -> loginResponseTemplate
        // idp.sendLogoutRequest -> logoutRequestTemplate
        return replaceTagFromTemplate(loginRequestTemplate);
        // replaceTagFromTemplate is a function to do dynamically substitution of tags
    });
});
```
Developers may want to use our default tag replacement `SamlLib.replaceTagsByValue(rawXML,tagValues)` instead of writing their own `replaceTagFromTemplate`. It replaces all defined tags in the input xml string.
```javascript
var requestTags = require('./urn').tags.request;
/**
  * @desc Repalce the tag (e.g. {tag}) inside the raw XML
  * @param  {string} rawXML      raw XML string used to do keyword replacement
  * @param  {array} tagValues    tag values
  * @return {string}
  */
replaceTagsByValue: function replaceTagsByValue(rawXML,tagValues){
    Object.keys(requestTags).forEach(function(t){
        rawXML = rawXML.replace(new RegExp(requestTags[t],'g'),tagValues[t]);
    });
    return rawXML;
}
```
###Release metadata in public
Developer can decide to release the entity metadata publicly.
```javascript
router.get('/metadata',function(req, res, next){
    res.header('Content-Type','text/xml').send(idp.getMetadata());
});
```
###Additional validation
There is a callback function in each sending action. It only checks the signature (if any), the issuer name and timestamp, but developers may want to validate the request/response more than that. Here is the example:
```javascript
/*
* sp1/routes/sso.js
* http://localhost:4002/sso/acs is the endpoint of assertion consumer service in sp1
*/
router.post('/acs',function(req,res,next){
    sp.parseLoginResponse(idp,'post',req,function(parseResult){
        // Your code will be here
        // parseResult is an object consists of
        // + samlContent <string>   plain-text version of request
        // + extract <object>       object including values of NameID, Audience, Attributes
    });
});
```

## More developers and Todo

There is plenty of room for improvement and more features will be added. Please feel free to contribute. Some features and supports are planning to be added in the next release as follow:

+ More test cases !
+ Embrace ES6 !
+ UI improvement of the express applications
+ A GUI for SAML tools
+ Encryption in SAML messages
+ Example of SP-initiated Single Logout Service
+ Example of using MongoDB to handle accounts
+ Asynchronous single logout strategy
+ Support for Artifact Binding
+ Support for rsa-sha256 signing algorithm
+ Support for more certificate format

## License

[MIT](LICENSE)

## Copyright

Copyright (C) 2015 Tony Ngan, released under the MIT License.


text:
# [Flight Check](http://alexa.amazon.com/#skills/amzn1.ask.skill.d7b520cc-5f45-4eae-bec6-efc216c9401d)
![1 stars](../../images/ic_star_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png)![1 stars](../../images/ic_star_border_black_18dp_1x.png) 3

To use the Flight Check skill, try saying...

* *Alexa ask Flight Check what is the status of Emirates flight 208*

Alexa skill to check real time flight status and announce the estimated arrival time of a flight. It uses the FlightAware REST API to obtain the required information.

***

### Skill Details

* **Invocation Name:** flight check
* **Category:** null
* **ID:** amzn1.ask.skill.d7b520cc-5f45-4eae-bec6-efc216c9401d
* **ASIN:** B01N2X243K
* **Author:** Ashwin Swaroop
* **Release Date:** December 29, 2016 @ 02:49:46
* **In-App Purchasing:** No


text:
[![Build Status](https://travis-ci.org/olekstomek/PERT.svg?branch=master)](https://travis-ci.org/olekstomek/PERT)
# PERT
Program Evaluation and Review Technique

You can estimate the time according to PERT by entering an optimistic, normal and pessimistic time to complete the task.

![PERT_android](https://user-images.githubusercontent.com/26818304/63643447-8cd86580-c6d0-11e9-9f1e-4859b4ba8785.png)

App idea from the book "The Clean Coder" (polish version "Mistrz czystego kodu") Robert C. Martin.

You can only add numbers in the input field. The program will not allow you to enter, for example, an optimistic performance value greater than for a normal or pessimistic assumption, similarly for other fields, i.e. a field with a pessimistic value must have the highest value.
The program allows tasks to be saved and the time is calculated for them. You can always delete the last task from the list or you can delete all tasks from the list.

How it works: [YouTube](https://www.youtube.com/watch?v=_EP-miF6iFY)

[Download from Google Play](https://play.google.com/store/apps/details?id=pl.olekstomek.pert)

repository: olekstomek/PERT

gha_language: Kotlin

repo_name: olekstomek/PERT


text:
---
layout: post
title:  "Automatic backups"
permalink: Automatic
---
The automatic feature of RsyncOSX is triggered by `⌘B` shortcut or by select the **double arrow**. RsyncOSX executes a `--dry-run` task for all configurations and execute a backup run for all tasks with data to be transferred or files to be deleted.

![](/images/RsyncOSX/master/intro/menu4.png)

The automatic backup can be aborted at any time. The tasks to be executed is equal to tasks selected by [quick backup](/Quickbackup).

Before using this feature check it out by using the quick backup. The `Select` button in quick backup selects the tasks which is automatically selected and executed.

gha_language: CSS


text:
---
title: swagger-jsdoc v6
date: '2020-12-23T00:00:00+02:00'
template: 'post'
draft: false
slug: swagger-jsdoc-6
category: 'Code'
tags:
  - JavaScript
  - Tools
description: 'Short overview of a new major version.'
---

## Introduction

[`swagger-jsdoc`](https://github.com/Surnet/swagger-jsdoc) is an open source project I've been trying to maintain in the last couple of years. [My first commit](https://github.com/Surnet/swagger-jsdoc/pull/27) was a suggestion for adding a CLI. As a full-time PHP developer in 2016 it was a struggle to wrap my head around Node.js-specific concepts, but my free time spent on the project paid off well later.

More than 4 years later, a lot of things have changed. I use JavaScript full-time and Node.js has been introducing new concepts, functionalities and tools, etc. It's been crazy. Or rather - normal for the JavaScript community :)

At any case, since I started maintaining `swagger-jsdoc` little after my first commit, the library was mostly in maintenance mode. Several improvements were introduced by community-driven pull requests and dozens of bug fixes were merged. Still, I think the real feature-milestone until 2020 was the added [support for OpenAPI specification](https://github.com/Surnet/swagger-jsdoc/pull/122). I'm assuming basing on the raise of [0-~64k monthly downloads in the first period](https://npm-stat.com/charts.html?package=swagger-jsdoc&from=2016-02-08&to=2018-01-08) compared to [~60k to ~820k](https://npm-stat.com/charts.html?package=swagger-jsdoc&from=2018-01-08&to=2020-12-23) in the second period after v3.

`swagger-jsdoc` is getting close to 1m (like million) monthly downloads and 1k (like thousand) github starts in the end of 2020. For me, as a maintainer of the project, this means a lot. In order to say "thank you" back to the people putting their trust in the project, I've been doing some refactoring since October 2020 for which I'll share more in the following sections.

## For users

The following section is targeted for people downloading and using `swagger-jsdoc`.

- added support for coffeescript style jsDoc comments
- added support for yaml anchors and references between separate documents
- added support for custom encoding which is not utf8 in input files
- added support for `x-webhooks` extension

## For maintainers

If you are a maintainer of the project, or you maintain a project closely related to `swagger-jsdoc`, have in mind the following changes:

- `lts/erbium` is now used instead of `lts/dubnium`
- Continuation-passing style (using callbacks) have been replaced by sync functions for consistency.
- Promises and async/await has been used whenever possible.
- [eemeli/yaml](https://github.com/eemeli/yaml) is now used instead of [nodeca/yaml](https://github.com/nodeca/js-yaml) as `eemeli/yaml` provides low-level APIs which were necessary for handling yaml references between separate documents.
- CLI has been simplified and commander has become a bit reduntant
- Tests have been reorganized to match their corresponding module under test or an application.
- Jest is now used instead of Mocha.
- Github actions running tests instead of Circle CI.
- Changelog has been autogenerated to facilitate tracking changes in history.
- Many helpers have been moved inline in order to make specific functions more domain-focused.
- JsDoc annotations have been updated.
- Documentation has been updated.

## Breaking changes

Here are a few scenarios in which you should pay extra attention.

Regarding previously exposed helper functions `createSpecification()`, `parseApiFileContent()`, `updateSpecificationObject()`, `finalizeSpecificationObject()`, which have been exported from the main module until v5 - the following changes have been applied:

- none of them will be exported from the main module anymore
- `createSpecification()` has been renamed to `prepare()` and is part of `src/specification.js`. Can be swapped without any changes in the input data structure. In short, change to `const { build } = require('swagger-jsdoc/src/specification');` and invoke in the same way as before.
- `parseApiFileContent()` has been renamed to `extractAnnotations()` and is part of `src/utils.js`. It has a new signature `function extractAnnotations(filePath, encoding = 'utf8') {}` which makes it more useful directly passing a `filePath` rather than a `fileConents`. Returns the same data structure.
- `updateSpecificationObject()` has been removed in favor of `src/specification/build` function which prepares and corrects all annotations before they get organized in a specification.
- `finalizeSpecificationObject()` has been renamed to `finalize()`. See migration notes for `prepare()` from above.

With regards to working with yaml: keep in mind that the parser has been changed to [eemeli/yaml](https://github.com/eemeli/yaml) instead of [nodeca/yaml](https://github.com/nodeca/js-yaml). That was necessary in order to be able to handle "yaml copy/paste" anchors/references between separate documents. As a result of this change in parsing library, no errors will be thrown from v6 on, as they will be only reported in the end of the specifiction creation. Basing on existing tests in `swagger-jsdoc` it's unlikely that new errors appear due to parser change, but if there are: please [report them](https://github.com/Surnet/swagger-jsdoc/issues).

The way CLI is used can also cause breaking changes when `apis` information has been added in the `swaggerDefinition`. This object has been wrongly accepting information from the `apis` property which you might have been warned about if inheriting types from OpenAPI definitions. The solution: take the value of `apis` and pass it to the CLI as arguments. Here's [an example](https://github.com/Surnet/swagger-jsdoc/releases/tag/v6.0.0-rc.4).

## Conclusions

Many thanks to all contributors helping with issue reports, documentation, code changes and suggestions in overall! I hope the new version 6 will mark a new more accessible and more maintainable version of `swagger-jsdoc` which has proven to be a useful tool for so many people!

branch_name: refs/heads/blog