text:
# How To Create and Run Beaker Test Cases

#### Table of Contents

* [Overview](#overview)
* [Pre-Install Tasks](#pre-install)
* [Beaker Configuration](#beaker-config)
* [Running a Beaker Test](#beaker-run)
* [Basic Example: feature tunnel](#basic-example-feature-tunnel)
  * [Step 1. Create the beaker test script](#s1-basic)
  * [Step 2. Run the script](#s2-basic)
* [Complex Example: router eigrp](#complex-example-router-eigrp)
  * [Step 1. Create the beaker test script](#s1-comp)
  * [Step 2. Run the script](#s2-comp)
* [Static Analysis](#sa)
* [Next Steps](#next)
* [**ADDENDUM**: Test Script Variable Reference (** NEW **)](#addendum)

## Overview

This document describes the process for writing and executing [Beaker](https://github.com/puppetlabs/beaker/blob/master/README.md) Test Cases for cisco puppet providers.

## Pre-Install Tasks

Refer to [README-beaker-prerequisites](README-beaker-prerequisites.md) for required setup steps for Beaker and the node(s) to be tested.

Install and set up the Puppet agent and `cisco_node_utils` gem as described in [README-agent-install.md](README-agent-install.md).

## Beaker Server Configuration

The following commands should be run on your Beaker workstation.

~~~
$ git clone https://github.com/cisco/cisco-network-puppet-module.git
$ cd cisco-network-puppet-module/tests/beaker_tests/
~~~

### Create `host.cfg` File

Under the `beaker_tests` directory, create file named `host.cfg` and add the following content.

Note: If running puppet on IOS XR, specify the gRPC port number configured on the switch.

Replace the `< >` markers with specific information.

```bash
HOSTS:
    <IOS XR agent>:
        roles:
            - agent
        platform: cisco_ios_xr-6-x86_64
        ip: <fully qualified domain name>
        ssh:
          auth_methods: ["password"]
          # SSHd for third-party network namespace (TPNNS) uses port 57722
          port: 57722
          user: <configured admin username>
          password: <configured admin password>

    <Nexus bash-shell or guestshell agent>:
        roles:
            - agent
        platform: cisco_nexus-7-x86_64
        ip: <fully qualified domain name>
        vrf: <vrf used for beaker workstation and puppet master ip reachability>
        ssh:
          auth_methods: ["password"]
          user: <configured bash-shell username>
          password: <configured bash-shell password>
        #Uncomment the following line to install into the guestshell
        #target: guestshell

    <Nexus open agent container (OAC) agent>:
        roles:
            - agent
        platform: cisco_nexus-oac-i386
        ip: <fully qualified domain name>
        vrf: <vrf used for beaker workstation and puppet master ip reachability>
        ssh:
          auth_methods: ["password"]
          user: <configured bash-shell username>
          password: <configured bash-shell password>
          # SSHd for OAC uses port 2222
          port: 2222

    #<agent3>:
    #  <...>

    #<agent4>:
    #  <...>

    <master>:
        # Note: Only one master configuration block allowed
        roles:
            - master
        platform: <server os-version-architecture>
        ip: <fully qualifed domain name>
        ssh:
          # Root user/password must be configured for master.
          auth_methods: ["password"]
          user: root
          password: <configured root password>
```

Here is a sample `host.cfg` file where `< >` markers have been replaced with actual data.

```bash
HOSTS:
    nx-agent:
        roles:
            - agent
        platform: cisco_nexus-5-x86_64
        ip: nx-agent.domain.com
        vrf: management
        #target: guestshell
        ssh:
          auth_methods: ["password"]
          user: devops
          password: devopspassword

    xr-agent:
        roles:
            - agent
        platform: cisco_ios_xr-6-x86_64
        ip: xr-agent.domain.com
        ssh:
          auth_methods: ["password"]
          port: 57722
          user: admin
          password: adminpassword

    puppetmaster1:
        roles:
            - master
        platform: ubuntu-1404-x86_64
        ip: puppetmaster1.domain.com
        ssh:
          auth_methods: ["password"]
          user: root
          password: rootpassword
```

## Running a Beaker Test

To run a beaker test from the `beaker_tests` directory, use the following command.

```bash
beaker --hosts hosts.cfg --pre-suite presuite/presuite-certcheck.rb \
--no-validate --no-configure \
--test vtp/vtp-provider-defaults.rb
```

**NOTE:** This runs a vtp test, but any other tests under the `beaker_tests` directory can be run in the same manner.

## Basic Example: feature tunnel

This example is a continuation of the examples used in other developer guides: [README-develop-node-utils-APIs.md](https://github.com/cisco/cisco-network-node-utils/blob/develop/docs/README-develop-node-utils-APIs.md) and [README-develop-types-providers.md](docs/README-develop-types-providers.md).

* To review, the NX-OS CLI for `feature tunnel` is a simple on / off style configuration:

`[no] feature tunnel`

This resource has no other properties so it will have limited testing.

## Step 1. Create the beaker test script: tunnel

* First, create a `tunnel` directory in the `beaker_tests` directory:

~~~bash
mkdir tests/beaker_tests/tunnel
~~~

* There are template files in `/docs` that may help guide development of new beaker test scripts. These templates provide most of the necessary code with a few customizations required for a new resource. Copy the `template-beaker-feature.rb` file to use as the basis for our new `test_tunnel.rb` beaker file:

~~~bash
cp docs/template-beaker-feature.rb  tests/beaker_tests/tunnel/test_tunnel.rb
~~~

* Edit `test_tunnel.rb` and substitute the placeholder text as shown here:

~~~bash
/X__RESOURCE_NAME__X/tunnel/
~~~

#### Example: test_tunnel.rb test script

This is the completed beaker script for the tunnel resource, based on `template-beaker-feature.rb`:

```ruby
###############################################################################
# Copyright (c) 2015 Cisco and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
# TestCase Name:
# -------------
# test-tunnel.rb
#
# TestCase Prerequisites:
# -----------------------
# This is a Puppet tunnel resource testcase for Puppet Agent on
# Nexus devices.
# The test case assumes the following prerequisites are already satisfied:
#   - Host configuration file contains agent and master information.
#   - SSH is enabled on the N9K Agent.
#   - Puppet master/server is started.
#   - Puppet agent certificate has been signed on the Puppet master/server.
#
# TestCase:
# ---------
# This tunnel resource test verifies default values for all properties.
#
# The following exit_codes are validated for Puppet, Vegas shell and
# Bash shell commands.
#
# Vegas and Bash Shell Commands:
# 0   - successful command execution
# > 0 - failed command execution.
#
# Puppet Commands:
# 0 - no changes have occurred
# 1 - errors have occurred,
# 2 - changes have occurred
# 4 - failures have occurred and
# 6 - changes and failures have occurred.
#
# NOTE: 0 is the default exit_code checked in Beaker::DSL::Helpers::on() method.
#
# The test cases use RegExp pattern matching on stdout or output IO
# instance attributes to verify resource properties.
#
###############################################################################

require File.expand_path('../../lib/utilitylib.rb', __FILE__)

# -----------------------------
# Common settings and variables
# -----------------------------
testheader = 'Resource cisco_tunnel'

# Define PUPPETMASTER_MANIFESTPATH.
UtilityLib.set_manifest_path(master, self)

# The 'tests' hash is used to define all of the test data values and expected
# results. It is also used to pass optional flags to the test methods when
# necessary.

# 'tests' hash
# Top-level keys set by caller:
# tests[:master] - the master object
# tests[:agent] - the agent object
# tests[:show_cmd] - the common show command to use for test_show_run
#
tests = {
  :master => master,
  :agent => agent,
  :show_cmd => 'show run section tunnel',
}

# tests[id] keys set by caller and used by test_harness_common:
#
# tests[id] keys set by caller:
# tests[id][:desc] - a string to use with logs & debugs
# tests[id][:manifest] - the complete manifest, as used by test_harness_common
# tests[id][:resource] - a hash of expected states, used by test_resource
# tests[id][:resource_cmd] - 'puppet resource' command to use with test_resource
# tests[id][:show_pattern] - array of regexp patterns to use with test_show_cmd
# tests[id][:ensure] - (Optional) set to :present or :absent before calling
# tests[id][:code] - (Optional) override the default exit code in some tests.
#
# These keys are local use only and not used by test_harness_common:
#
# tests[id][:manifest_props] - This is essentially a master list of properties
#   that permits re-use of the properties for both :present and :absent testing
#   without destroying the list
# tests[id][:resource_props] - This is essentially a master hash of properties
#   that permits re-use of the properties for both :present and :absent testing
#   without destroying the hash
# tests[id][:title_pattern] - (Optional) defines the manifest title.
#   Can be used with :af for mixed title/af testing. If mixing, :af values will
#   be merged with title values and override any duplicates. If omitted,
#   :title_pattern will be set to 'id'.
#
tests['default_properties'] = {
  :manifest_props => "
    # PLEASE NOTE: The feature template has no additional properties so these
    # hash entries are intentionally commented out and included here solely
    # as an example of where properties would be defined.

    # bar                            => 'default',
  ",
  :resource_props => {
    # 'bar'                          => 'default',
  },
}

tests['non_default_properties'] = {
  :manifest_props => "
    # bar                            => true,
  ",
  :resource_props => {
    # 'bar'                          => 'true',
  }
}

#################################################################
# HELPER FUNCTIONS
#################################################################

# Full command string for puppet resource command
def puppet_resource_cmd
  UtilityLib::PUPPET_BINPATH + 'resource cisco_tunnel'
end

def build_manifest_tunnel(tests, id)
  if tests[id][:ensure] == :absent
    state = 'ensure => absent,'
    manifest = ''
    tests[id][:resource] = { 'ensure' => 'absent' }
  else
    state = 'ensure => present,'
    manifest = tests[id][:manifest_props]
    tests[id][:resource] = tests[id][:resource_props]
  end

  tests[id][:title_pattern] = id if tests[id][:title_pattern].nil?
  logger.debug("build_manifest_tunnel :: title_pattern:\n" +
               tests[id][:title_pattern])
  tests[id][:manifest] = "cat <<EOF >#{UtilityLib::PUPPETMASTER_MANIFESTPATH}
  node 'default' {
    cisco_tunnel { '#{tests[id][:title_pattern]}':
      #{state}
      #{manifest}
    }
  }
EOF"
end

def test_harness_tunnel(tests, id)
  tests[id][:ensure] = :present if tests[id][:ensure].nil?
  tests[id][:resource_cmd] = puppet_resource_cmd
  tests[id][:desc] += " [ensure => #{tests[id][:ensure]}]"

  # Build the manifest for this test
  build_manifest_tunnel(tests, id)

  # For full test support of properties use test_harness_common; as an
  # alternative use direct calls to individual test_* wrapper methods:
  # test_harness_common(tests, id)
  test_manifest(tests, id)
  test_idempotence(tests, id)

  tests[id][:ensure] = nil
end

#################################################################
# TEST CASE EXECUTION
#################################################################
test_name "TestCase :: #{testheader}" do
  # -------------------------------------------------------------------
  logger.info("\n#{'-' * 60}\nSection 1. Default Property Testing")
  node_feature_cleanup(agent, 'tunnel', 'disable feature', false)

  # -----------------------------------
  id = 'default_properties'
  tests[id][:desc] = '1.1 Default Properties'
  test_harness_tunnel(tests, id)

  tests[id][:desc] = '1.2 Default Properties'
  tests[id][:ensure] = :absent
  test_harness_tunnel(tests, id)

  # -------------------------------------------------------------------
  # FUTURE:
  # logger.info("\n#{'-' * 60}\nSection 2. Non Default Property Testing")
  # node_feature_cleanup(agent, 'tunnel', 'disable feature', false)
  # tests[id][:desc] = "2.1 Non Default Properties"
  # test_harness_tunnel(tests, 'non_default_properties')
end

logger.info("TestCase :: #{testheader} :: End")
```

## Step 2. Run the script: tunnel

The beaker tool must have access to the `beaker_tests` directory. This could mean running beaker directly from your development workspace or from an entirely different server. For example, some developers prefer to use a dedicated beaker workstation in which case sshfs can be used to softlink the `beaker_tests` directory from the beaker workstation.

Run the beaker tool against the `test_tunnel` script:

_(Some output truncated for brevity)_

```bash
beaker --host hosts.cfg --no-validate --no-configure --test beaker_tests/tunnel/test_tunnel.rb

Beaker!
      wWWWw
      |o o|
      | O |  2.18.3!
      |(")|
     / \X/ \
    |   V   |
    |   |   |
{
         ...text removed for brevity...
}
Beaker::Hypervisor, found some none boxes to create
No tests to run for suite 'pre_suite'
Begin beaker_tests/tunnel/test_tunnel.rb

TestCase :: Resource cisco_tunnel

------------------------------------------------------------
Section 1. Default Property Testing

  * TestStep :: disable feature

  * TestStep :: 1.1 Default Properties [ensure => present] :: MANIFEST
1.1 Default Properties [ensure => present] :: MANIFEST     :: PASS

  * TestStep :: 1.1 Default Properties [ensure => present] :: IDEMPOTENCE
1.1 Default Properties [ensure => present] :: IDEMPOTENCE  :: PASS

  * TestStep :: 1.2 Default Properties [ensure => absent] :: MANIFEST
1.2 Default Properties [ensure => absent] :: MANIFEST     :: PASS

  * TestStep :: 1.2 Default Properties [ensure => absent] :: IDEMPOTENCE
1.2 Default Properties [ensure => absent] :: IDEMPOTENCE  :: PASS
TestCase :: Resource cisco_tunnel :: End
beaker_tests/tunnel/test_tunnel.rb passed in 37.28 seconds
      Test Suite: tests @ 2015-10-02 10:55:55 -0400

      - Host Configuration Summary -

              - Test Case Summary for suite 'tests' -
       Total Suite Time: 37.28 seconds
      Average Test Time: 37.28 seconds
              Attempted: 1
                 Passed: 1
                 Failed: 0
                Errored: 0
                Skipped: 0
                Pending: 0
                  Total: 1

      - Specific Test Case Status -

Failed Tests Cases:
Errored Tests Cases:
Skipped Tests Cases:
Pending Tests Cases:

No tests to run for suite 'post_suite'
Cleanup: cleaning up after successful run
Warning: ssh connection to <IP_ADDRESS> has been terminated
Warning: ssh connection to <IP_ADDRESS> has been terminated
Beaker completed successfully, thanks.
```

## Complex Example: router eigrp

This example is a continuation of the examples used in other developer guides: [README-develop-node-utils-APIs.md](https://github.com/cisco/cisco-network-node-utils/blob/develop/docs/README-develop-node-utils-APIs.md) and [README-develop-types-providers.md](docs/README-develop-types-providers.md).

* To review, the NX-OS CLI for `router eigrp` is a multi-level, multiple instance configuration. For the purposes of this example the test will focus on testing a single router instance and just two properties:

~~~
[no] feature eigrp
[no] router eigrp [name]    (string)
       maximum-paths [n]    (integer)
  [no] shutdown             (boolean)
~~~

Note that the `router eigrp` provider doesn't require any knowledge of `feature eigrp` because the feature configuration is controlled automatically by the `router eigrp` node_utils API.

## Step 1. Create the beaker test script: eigrp

* First, create an `eigrp` directory in the `beaker_tests` directory:

~~~bash
mkdir tests/beaker_tests/eigrp
~~~

* There are template files in `/docs` that may help guide development of new beaker test scripts. These templates provide most of the necessary code with a few customizations required for a new resource. Copy the `template-beaker-router.rb` file to use as the basis for our new `test_eigrp.rb` beaker file:

~~~bash
cp docs/template-beaker-router.rb  tests/beaker_tests/tunnel/test_eigrp.rb
~~~

* Edit `test_eigrp.rb` and substitute the placeholder text as shown here:

~~~bash
/X__RESOURCE_NAME__X/eigrp/
~~~

#### Example: test_eigrp.rb test script

This is the completed beaker script for the `router eigrp` resource, based on `template-beaker-router.rb`:

```ruby
###############################################################################
# Copyright (c) 2015 Cisco and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
# TestCase Name:
# -------------
# test-eigrp.rb
#
# TestCase Prerequisites:
# -----------------------
# This is a Puppet eigrp resource testcase for Puppet Agent on
# Nexus devices.
# The test case assumes the following prerequisites are already satisfied:
#   - Host configuration file contains agent and master information.
#   - SSH is enabled on the N9K Agent.
#   - Puppet master/server is started.
#   - Puppet agent certificate has been signed on the Puppet master/server.
#
# TestCase:
# ---------
# This Tunnel resource test verifies default values for all properties.
#
# The following exit_codes are validated for Puppet, Vegas shell and
# Bash shell commands.
#
# Vegas and Bash Shell Commands:
# 0   - successful command execution
# > 0 - failed command execution.
#
# Puppet Commands:
# 0 - no changes have occurred
# 1 - errors have occurred,
# 2 - changes have occurred
# 4 - failures have occurred and
# 6 - changes and failures have occurred.
#
# NOTE: 0 is the default exit_code checked in Beaker::DSL::Helpers::on() method.
#
# The test cases use RegExp pattern matching on stdout or output IO
# instance attributes to verify resource properties.
#
###############################################################################

require File.expand_path('../../lib/utilitylib.rb', __FILE__)

# -----------------------------
# Common settings and variables
# -----------------------------
testheader = 'Resource cisco_router_eigrp'

# Define PUPPETMASTER_MANIFESTPATH.
UtilityLib.set_manifest_path(master, self)

# The 'tests' hash is used to define all of the test data values and expected
# results. It is also used to pass optional flags to the test methods when
# necessary.

# 'tests' hash
# Top-level keys set by caller:
# tests[:master] - the master object
# tests[:agent] - the agent object
# tests[:show_cmd] - the common show command to use for test_show_run
#
tests = {
  :master => master,
  :agent => agent,
  :show_cmd => 'show run section eigrp',
}

# tests[id] keys set by caller and used by test_harness_common:
#
# tests[id] keys set by caller:
# tests[id][:desc] - a string to use with logs & debugs
# tests[id][:manifest] - the complete manifest, as used by test_harness_common
# tests[id][:resource] - a hash of expected states, used by test_resource
# tests[id][:resource_cmd] - 'puppet resource' command to use with test_resource
# tests[id][:show_pattern] - array of regexp patterns to use with test_show_cmd
# tests[id][:ensure] - (Optional) set to :present or :absent before calling
# tests[id][:code] - (Optional) override the default exit code in some tests.
#
# These keys are local use only and not used by test_harness_common:
#
# tests[id][:manifest_props] - This is essentially a master list of properties
#   that permits re-use of the properties for both :present and :absent testing
#   without destroying the list
# tests[id][:resource_props] - This is essentially a master hash of properties
#   that permits re-use of the properties for both :present and :absent testing
#   without destroying the hash
# tests[id][:title_pattern] - (Optional) defines the manifest title.
#   Can be used with :af for mixed title/af testing. If mixing, :af values will
#   be merged with title values and override any duplicates. If omitted,
#   :title_pattern will be set to 'id'.
# tests[id][:af] - (Optional) defines the address-family values.
#   Must use :title_pattern if :af is not specified. Useful for testing mixed
#   title/af manifests
#
tests['default_properties'] = {
  :title_pattern => '1',
  :manifest_props => "
    maximum_paths                  => 'default',
    shutdown                       => 'default',
  ",
  :resource_props => {
    'maximum_paths'                => '8',
    'shutdown'                     => 'false',
  },
}

tests['non_default_properties_M'] = {
  :desc => "2.1 Non Default Properties 'M' commands",
  :title_pattern => '1',
  :manifest_props => "
    maximum_paths                  => '5',
  ",
  :resource_props => {
    'maximum_paths'                => '5',
  }
}

tests['non_default_properties_S'] = {
  :desc => "2.2 Non Default Properties 'S' commands",
  :title_pattern => '1',
  :manifest_props => "
    shutdown                       => 'true',
  ",
  :resource_props => {
    'shutdown'                     => 'true',
  }
}

#################################################################
# HELPER FUNCTIONS
#################################################################

# Full command string for puppet resource command
def puppet_resource_cmd
  UtilityLib::PUPPET_BINPATH + 'resource cisco_router_eigrp'
end

def build_manifest_eigrp(tests, id)
  if tests[id][:ensure] == :absent
    state = 'ensure => absent,'
    tests[id][:resource] = {}
  else
    state = 'ensure => present,'
    manifest = tests[id][:manifest_props]
    tests[id][:resource] = tests[id][:resource_props]
  end

  tests[id][:title_pattern] = id if tests[id][:title_pattern].nil?
  logger.debug("build_manifest_eigrp :: title_pattern:\n" +
               tests[id][:title_pattern])
  tests[id][:manifest] = "cat <<EOF >#{UtilityLib::PUPPETMASTER_MANIFESTPATH}
  node 'default' {
    cisco_router_eigrp { '#{tests[id][:title_pattern]}':
      #{state}
      #{manifest}
    }
  }
EOF"
end

def test_harness_eigrp(tests, id)
  tests[id][:ensure] = :present if tests[id][:ensure].nil?
  tests[id][:resource_cmd] = puppet_resource_cmd
  tests[id][:desc] += " [ensure => #{tests[id][:ensure]}]"

  # Build the manifest for this test
  build_manifest_eigrp(tests, id)

  # FUTURE
  # test_harness_common(tests, id)

  test_manifest(tests, id)
  test_resource(tests, id)
  test_idempotence(tests, id)

  tests[id][:ensure] = nil
end

#################################################################
# TEST CASE EXECUTION
#################################################################
test_name "TestCase :: #{testheader}" do
  # -------------------------------------------------------------------
  logger.info("\n#{'-' * 60}\nSection 1. Default Property Testing")
  node_feature_cleanup(agent, 'eigrp')

  # -----------------------------------
  id = 'default_properties'
  tests[id][:desc] = '1.1 Default Properties'
  test_harness_eigrp(tests, id)

  tests[id][:desc] = '1.2 Default Properties'
  tests[id][:ensure] = :absent
  test_harness_eigrp(tests, id)

  # -------------------------------------------------------------------
  logger.info("\n#{'-' * 60}\nSection 2. Non Default Property Testing")
  node_feature_cleanup(agent, 'eigrp')

  test_harness_eigrp(tests, 'non_default_properties_M')
  test_harness_eigrp(tests, 'non_default_properties_S')

  # -------------------------------------------------------------------
  # FUTURE
  # logger.info("\n#{'-' * 60}\nSection 3. Title Pattern Testing")
  # node_feature_cleanup(agent, 'eigrp')

  # id = 'title_patterns'
  # tests[id][:desc] = '3.1 Title Patterns'
  # tests[id][:title_pattern] = '2'
  # tests[id][:af] = { :vrf => 'default', :afi => 'ipv4', :safi => 'unicast' }
  # test_harness_eigrp(tests, id)

  # id = 'title_patterns'
  # tests[id][:desc] = '3.2 Title Patterns'
  # tests[id][:title_pattern] = '2 blue'
  # tests[id][:af] = { :afi => 'ipv4', :safi => 'unicast' }
  # test_harness_eigrp(tests, id)
end

logger.info("TestCase :: #{testheader} :: End")
```

## Step 2. Run the script: eigrp

As noted earlier, the beaker tool must have access to the `beaker_tests` directory.

Run the beaker tool against the `test_eigrp` script:

_(Some output truncated for brevity)_

```bash
beaker --host hosts.cfg --no-validate --no-configure --test beaker_tests/tunnel/test_tunnel.rb

Beaker!
      wWWWw
      |o o|
      | O |  2.18.3!
      |(")|
     / \X/ \
    |   V   |
    |   |   |
{
         ...text removed for brevity...
}
Beaker::Hypervisor, found some none boxes to create
No tests to run for suite 'pre_suite'
Begin beaker_tests/eigrp/test_eigrp.rb

TestCase :: Resource cisco_eigrp

------------------------------------------------------------
Section 1. Default Property Testing

  * TestStep :: feature cleanup

  * TestStep :: 1.1 Default Properties [ensure => present] :: MANIFEST
1.1 Default Properties [ensure => present] :: MANIFEST     :: PASS

  * TestStep :: 1.1 Default Properties [ensure => present] :: RESOURCE
1.1 Default Properties [ensure => present] :: RESOURCE     :: PASS

  * TestStep :: 1.1 Default Properties [ensure => present] :: IDEMPOTENCE
1.1 Default Properties [ensure => present] :: IDEMPOTENCE  :: PASS

  * TestStep :: 1.2 Default Properties [ensure => absent] :: MANIFEST
1.2 Default Properties [ensure => absent] :: MANIFEST     :: PASS

  * TestStep :: 1.2 Default Properties [ensure => absent] :: RESOURCE
1.2 Default Properties [ensure => absent] :: RESOURCE     :: PASS

  * TestStep :: 1.2 Default Properties [ensure => absent] :: IDEMPOTENCE
1.2 Default Properties [ensure => absent] :: IDEMPOTENCE  :: PASS

------------------------------------------------------------
Section 2. Non Default Property Testing

  * TestStep :: feature cleanup

  * TestStep :: 2.1 Non Default Properties 'M' commands [ensure => present] :: MANIFEST
2.1 Non Default Properties 'M' commands [ensure => present] :: MANIFEST     :: PASS

  * TestStep :: 2.1 Non Default Properties 'M' commands [ensure => present] :: RESOURCE
2.1 Non Default Properties 'M' commands [ensure => present] :: RESOURCE     :: PASS

  * TestStep :: 2.1 Non Default Properties 'M' commands [ensure => present] :: IDEMPOTENCE
2.1 Non Default Properties 'M' commands [ensure => present] :: IDEMPOTENCE  :: PASS

  * TestStep :: 2.2 Non Default Properties 'S' commands [ensure => present] :: MANIFEST
2.2 Non Default Properties 'S' commands [ensure => present] :: MANIFEST     :: PASS

  * TestStep :: 2.2 Non Default Properties 'S' commands [ensure => present] :: RESOURCE
2.2 Non Default Properties 'S' commands [ensure => present] :: RESOURCE     :: PASS

  * TestStep :: 2.2 Non Default Properties 'S' commands [ensure => present] :: IDEMPOTENCE
2.2 Non Default Properties 'S' commands [ensure => present] :: IDEMPOTENCE  :: PASS
TestCase :: Resource cisco_eigrp :: End
beaker_tests/eigrp/test_eigrp.rb passed in 85.15 seconds
      Test Suite: tests @ 2015-10-02 11:17:26 -0400

      - Host Configuration Summary -

              - Test Case Summary for suite 'tests' -
       Total Suite Time: 85.15 seconds
      Average Test Time: 85.15 seconds
              Attempted: 1
                 Passed: 1
                 Failed: 0
                Errored: 0
                Skipped: 0
                Pending: 0
                  Total: 1

      - Specific Test Case Status -

Failed Tests Cases:
Errored Tests Cases:
Skipped Tests Cases:
Pending Tests Cases:

No tests to run for suite 'post_suite'
Cleanup: cleaning up after successful run
Warning: ssh connection to <IP_ADDRESS> has been terminated
Warning: ssh connection to <IP_ADDRESS> has been terminated
Beaker completed successfully, thanks.
```

## Static Analysis

As noted in the other developer documents, you will need to run [rubocop](https://rubygems.org/gems/rubocop) prior to committing your new code:

~~~bash
% rubocop tunnel/test_tunnel.rb eigrp/test_eigrp.rb
Inspecting 2 files
..

2 files inspected, no offenses detected
~~~

## Next Steps

Please see the [CONTRIBUTING](../CONTRIBUTING.md) document for workflow instructions.

--
## **ADDENDUM**: Test Script Variable Reference

*-- This ADDENDUM is here temporarily until the entire document is rewritten.--*

--

# Beaker: Test Script Variable Reference

#### Table of Contents

* [Overview](#overview)
* [Test Prerequisites](#tp)
* [Return Codes](#rc)
* [The `tests` Hash](#tests)
 * [Top-level Keys](#tlk)
 * [Test Case Keys](#tck)
* [Title Pattern Testing](#tpt)

## Overview

The beaker test scripts have gone through a number of rewrites in an effort to reduce the time required to develop new test scripts. The current revision uses a `tests` hash as a container for all of the inputs required to fully run each test case. This document is a common reference for the `tests` hash and other required test variables.

## Test Prerequisites

Each test case in each test file makes basic assumptions about the state of the test environment:

* The beaker host configuration file is set up with proper access credentials for agent and master
* The Puppet Master daemon is running
* SSH is enabled in the agent environment
* The agent SSL certificate has been generated and signed by the Puppet Master

## Return Codes

The beaker tests will validate tests using return codes from bash and puppet commands:

#### Bash Command Return Codes

* `0` = successful command execution
* `> 0` = unsuccessful command execution

#### Puppet Command Return Codes

* `0` = No Changes have occurred (idempotence tests)
* `1` = An Error has been raised
* `2` = Changes have occurred (manifest tests)
* `4` = A Failure has occurred
* `6` = A Change and Failure has occurred

*Note: The beaker `on()` method has an optional `options` parameter, which allows the caller to specify `:acceptable_exit_codes`. If this is not specified it will default to `0`.*

## The `tests` hash

The `tests` hash is a convenient container for common and custom test variables. Common variables that are used by all test cases are defined as top-level keys, while each test case is a top-level key with the test case variables defined as the key-value; for example:

```ruby
# A top-level key for common variables
tests = {
  resource_name: 'cisco_bgp_neighbor_af',
}

# A test-case key with test variables within
tests[:bgp_weight] = {
  manifest_props: { weight: '30' },
}
```

Custom keys may be added for various unique test requirements but they should be documented in this guide.

### Top-level Keys

##### Required Top-level keys

| Key Name         | Value and Usage
|:-----------------|:---------------
| `:agent`         | The `agent` object variable name. It is used for accessing the agent environment.
| `:master`        | The `master` object variable name. It is used for accessing the puppet master environment.
| `:resource_name` | The resource name used in the test. This is primarily used with the `puppet resource` command.

##### Optional Top-level keys

| Key Name         | Value and Usage
|:-----------------|:---------------
| `:asn`           | An Autonomous-System number. Used in some routing protocol tests.
| `:encap_prof_global` | The global encapsulation profile configuration. This configuration is a dependency for testing with `cisco_interface_service_vni`.
| `:ensurable`     | True/False. Defines whether a provider supports ensurable; typically only used to specify false, which prevents the test_harness from inserting an ensure value into the manifest. Also see Test Case key `:ensure`.
| `:intf_type`     | The interface type string, e.g. `ethernet`. Used in tests that require an interface, in which case the test will discover the first interface of that type to use for the tests.
| `:platform`      | A regexp pattern to match against the agent's product-id value. This is used to skip tests that don't support a feature or parameter. This key can be specified as a common top-level key or on a test-by-test basis.
| `:preclean`      | The resource name used to remove a configuration as part of testbed pre-cleanup. The resource does not have to be the same as the one being tested; for example, the `'cisco_bgp_af'` test might use `'cisco_bgp'` for `:preclean` if a full bgp cleanup is needed instead of just removing the `'cisco_bgp_af'` configuration. This key can be specified as a common top-level key or on a test-by-test basis.
| `:sid`           | The service ID (Integer). Used in `cisco_interface_service_vni` tests.

##### Example: Top-level Keys

```ruby
tests = {
  master:        master,
  agent:         agent,
  platform:      'n(3|9)k',          # Restrict testing to N3k & N9k
  resource_name: 'cisco_interface',
  intf_type:     'ethernet',
}
```

### Test Case Keys

The keys are all optional. Most test cases will typically only use `:desc` and `:manifest_props`.

| Key Name    | Value and Usage
|:------------|:---------------
| `:desc`           | A text description for the test case. This is used for logging and debugs.
| `:manifest_props` | A hash of property names and their values. The script will generate a manifest from this hash and create it as a file on the puppet master. If the `:resource` key is not specified then this hash will also be used to generate a hash of expected values for use by the `puppet resource` command validation test.
| `:platform`       | A regexp pattern to match against the agent's product-id value. This is used to skip tests that don't support a feature or parameter. This key can be specified as a common top-level key or on a test-by-test basis.
| `:preclean`       | The resource name used to remove a configuration as part of testbed pre-cleanup. The resource does not have to be the same as the one being tested; for example, the `'cisco_bgp_af'` test might use `'cisco_bgp'` for `:preclean` if a full bgp cleanup is needed instead of just removing the `'cisco_bgp_af'` configuration. This key can be specified as a common top-level key or on a test-by-test basis.
| `:resource`       | A hash of expected values from the `puppet resource` command. This is only needed when the expected values differ from the values defined by `:manifest_props`; for example: default testing may specify a value of `'default'` in the manifest but an expected value of `'true'` for the `puppet resource` command.
| `:ensure`         | The ensure value: `'present'` or `'absent'`. If not specified the test case will default to `'present'`. Also see Top-level key `:ensurable`.
| `:code`           | An array of acceptable return codes; e.g. `[0, 2]`. This is used to override the default return codes expected by the common test harness. It is rarely needed but some platforms / properties require this override.
| `:title_pattern`  | The title string to use in the manifest. Most providers use simple title patterns, in which case this is a simple string value. Providers like bgp_neighbor_af use complex title patterns, in which case they will use this key by itself for general property testing, then use it in combination with the `:title_params` key to perform complex title pattern testing.
| `:remote_as`      | An Autonomous-System number. Used in BGP tests to set up an eBGP configuraton to test eBGP-only properties.
| `:title_params` | A hash of title parameters. See [Title Pattern Testing](#tpt) below.

##### Example: Test Case: basic

```ruby
tests[:basic_1] = {
  manifest_props: {
    'allowas_in' => 'false',
  }
}
```

This simple test case definition tells the test harness to:

* set `:title_pattern` and `:desc` to key name (`'basic_1'`)
* ignore any platform checks (`:platform` is not specified)
* skip pre cleaning (`:preclean` is not specified)
* create a `:resource` expected values hash from `:manifest_props` since the expect values from `puppet resource` will be the same as those in the manifest

This test case can be called with the following syntax:

```ruby
test_harness_run(tests, :basic_1)
```

##### Example: Test Case: bgp_neighbor_af (defaults)

```ruby
tests[:default] = {
  desc:           'Default Properties',
  preclean:       'cisco_bgp',
  title_pattern:  '2 default <IP_ADDRESS> ipv4 unicast',
  manifest_props: {
    allowas_in:  'default',
  }
  resource:
    'allowas_in' => 'false',
  }
}
```

This test requires extra keys:

* An explicit `:desc` string is desired though not required
* bgp_neighbor_af has complex title patterns so using the test case key name won't work
* precleaning is required because it's the first test of many and the testbed state will be unknown
* `:manifest_props` is using `'default'` values so a `:resource` hash is needed to defined different expect values for `puppet resource`

This test case can be called with the following syntax:

```ruby
test_harness_run(tests, :default)
```

##### Example: Test Case: bgp_neighbor_af (non defaults)

```ruby
tests[:non_def_M] = {
  desc:           'Non Default: (M) max-prefix',
  manifest_props: {
    'allowas_in' => 'false',
  }
}
```

This tests the same property as the 'defaults' test before it but in this case it's just explicitly setting the property value so it just needs `:manifest_props` defined. The `:desc` is helpful but not required.

This test case can be called with the following syntax:

```ruby
test_harness_run(tests, :non_def_M)
```

### Title Pattern Testing

Some providers support complex title patterns, in which case parameters (*these are the `newparameter()` methods found in the resource type files*) can obtain their values from
 either explicit assignments or from the title pattern itself; e.g.

```ruby
# Example A. parameters from the title string only

cisco_bgp { '55 red': }

# Example B. parameters from both the title string and explicit assignment

cisco_bgp { '55':
  vrf => 'red'
}
```

The `puppet resource` command requires a full title string that contains all of the required parameters, so the title string in Example A will not work by itself and the string must be merged appropriately with the explicit parameters to use it with `puppet resource`.

General property testing will not need this special title pattern munging but there should be additional testing for just the title patterns. This can be accomplished by using the `:title_params` key to define explicit title parameters to munge with a less explicit `:title_pattern`, resulting in a complete title string for puppet resource.

##### Example: bgp_neighbor_af `title_pattern` test cases

```ruby
tests[:title_patterns_1] = {
  desc:          'T.1 Title Pattern',
  preclean:      'cisco_vrf',
  title_pattern: 'new_york',
  title_params:  { vrf: 'red', afi: 'ipv4', safi: 'unicast' },
  resource:      { 'ensure' => 'present' },
  # This test will result in a manifest title string: 'new_york'
  # and a puppet resource title string: 'red ipv4 unicast'
}

tests[:title_patterns_2] = {
  desc:          'T.2 Title Pattern',
  title_pattern: 'blue',
  title_params:  { afi: 'ipv4', safi: 'unicast' },
  resource:      { 'ensure' => 'present' },
  # This test will result in a manifest title string: 'blue'
  # and a puppet resource title string: 'blue ipv4 unicast'
}

tests[:title_patterns_3] = {
  desc:          'T.3 Title Pattern',
  title_pattern: 'cyan ipv4',
  title_params:  { safi: 'unicast' },
  resource:      { 'ensure' => 'present' },
  # This test will result in a manifest title string: 'cyan ipv4'
  # and a puppet resource title string: 'cyan ipv4 unicast'
}
```
The title pattern tests can now be called with this syntax:

```ruby
  test_harness_run(tests, :title_patterns_1)
  test_harness_run(tests, :title_patterns_2)
  test_harness_run(tests, :title_patterns_3)
```

repository: cisco/cisco-network-puppet-module

gha_language: Ruby

repo_name: cisco/cisco-network-puppet-module


text:
## Nek5000 + libCEED examples

### Prerequisites

Nek5000 v18.0 or greater must be [installed](https://nek5000.mcs.anl.gov/getstarted/) to run
these examples.  It is assumed to exist at `../../../Nek5000` (a sibling to the
libCEED directory) or at a path defined in the environment variable `NEK5K_DIR`.
For example, you could set
```sh
    export NEK5K_DIR=/scratch/Nek5000
```
if that is where it is located.

### Generate meshes (boxes)

You can generate box geometries using `generate-boxes.sh` script:
```sh
  ./generate-boxes.sh log_2(<min_elem>) log_2(<max_elem>)."
```
For example:
```sh
  ./generate-boxes.sh 2 4
```
will generate three boxes with 4(=2^2), 8 and 16(=2^4) elements inside the
`boxes/b*` directories.

The `generate-boxes.sh` script depends on the Nek5000 tools: `genbox`, `genmap`,
and `reatore2`. They can be built using
```sh
   ( cd $NEK5K_DIR/tools && ./maketools genbox genmap reatore2 )
```
See also the [Nek5000 documentation](https://nek5000.mcs.anl.gov/getstarted/).

### Building the Nek5000 examples

You can build the Nek5000 libCEED examples by invoking `make-nek-examples.sh` script.
```sh
  ./make-nek-examples.sh
```

### Running Nek5000 examples

You can run the Nek5000 libCEED examples by invoking `run-nek-examples.sh`
script. The syntax is:
```sh
  ./run-nek-example.sh -c <ceed_backend> -e <example_name> \
                                            -n <mpi_ranks> -b <box_geometry>
```
The different options that can be used for the script are listed below:
```
options:
   -h|-help     Print this usage information and exit
   -c|-ceed     Ceed backend to be used for the run (optional, default: /cpu/self)
   -e|-example  Example name (optional, default: bp1)
   -n|-np       Specify number of MPI ranks for the run (optional, default: 4)
   -b|-box      Specify the box geometry to be found in ./boxes/ directory (Mandatory)
```
The only mandatory argument is `-b` or `-box` which sets the box geometry to be
used. This geometry should be found in `./boxes` directory.

For example, you can run bp1 as follows:
```sh
  ./run-nek-example.sh -ceed /cpu/self -e bp1 -n 4 -b 3
```
which is the same as running:
```sh
  ./run-nek-example.sh -b 3
```

repository: walterscorpionblade/libCEED

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: walterscorpionblade/libCEED


text:
```
Support for Intel DDP
=====================

Introduction
------------
This story is part of the performance initiative that is undertaken from the
beginning of 2020 to improve the performance of DPDK vRouter.

Background
----------
Contrail dataplane runs on general purpose x86 servers called compute nodes.
In contrail, all the overlay MPLS or VXLAN tunnels terminate at the compute
node instead of hardware switch like QFX. They terminate at a software switch-
cum-router called vRouter which is running in all the computes and it is the
main dataplane component of contrail. vRouter can either run as a kernel module
or a DPDK application. The most common use-case is DPDK mode. It is the
workhorse of the contrail system. Each and every packet in the contrail system
flows through vRouter. It essentially forwards packets between VMs and physical
interface. It is a multi-core, multi-threaded component since it needs to be
highly performant.

Packet process in DPDK vRouter
------------------------------
Step 1 - Packets arrive at the physical interface or NIC card of the server and
the NIC hardware load balances them and distributes them into different interna
hardware queues based on the 5-tuple hash of the packets.

Step 2 - For each hardware queue which is configured, the vRouter allocates a
dedicated CPU core to poll the packets and dequeue it for further processing.

Step 3 - For certain types of packets, the NIC card cannot load balance the
packets properly. In vRouter software, we can figure this out. If NIC has
load balanced it properly, the same CPU core which dequeued the packet will do
the packet processing also. If not, the receiving CPU core performs software
load-balancing by distributing the packets to other CPU cores which will do the
processing.

Step 4 - The final step is the CPU cores, after processing, puts them into one
of the virtual machine Tx queues from where the VM gets the packets

Problem statement
-----------------
Packets having the encapsulation type as MPLSoGRE does not have enough entropy.
Entropy means it does not have enough information for load-balancing. In
specific, they lack port information. Compare it with MPLSoUDP where we have the
full 5 tuples Source IP, Destination IP, Source Port, Destination Port, Protocol.
But in MPLSoGRE, we only have Source IP, Destination IP and protocol. So NIC
cannot properly load balance the packets. All packets between a pair of computes
land up in the same Rx Queue of the NIC. Due to this, the CPU core which polls
that Rx queue becomes bottleneck for the whole compute and the performance
suffers.

Solution
--------
We introduce a new capability to contrail dataplane which removes the bottleneck
for MPLSoGRE packets so that performance is proportional to the number of CPU
cores. That is, no single CPU core can be a bottleneck and packets are
distributed evenly across different hardware Rx queues. We use Intel dynamic
device personalization technology or DDP in short to achieve this. With Intel
700 series, the fortville family, Intel moved to programmable pipeline model
from a fixed pipeline model which existed in the earlier Niantic family. They
added this new capability. DDP allows dynamic re-configuration of packet
processing pipeline in the NIC at runtime without server reboot. Software can
apply custom profiles to the NIC so that it can classify new packet types inline,
and distribute these packets to specified Rx queues

Parsed fields before enabling NIC with DDP
------------------------------------------
DA | SA | IPv4 | GRE | MPLS | DA | SA | IPv4 | UDP | PAYLOAD
\____________________/

In the above, MPLSoGRE is unknown flow type, so no RSS and other filters
possible. The NIC is able to parse only till the GRE header where in it does
not get the port information which is present in the UDP header present in the
inner packet. So it does not have enough information to distribute the packets
properly. RSS is nothing but the way in which the NIC determines the hash and
put it into the corresponding hardware queue.

Parsed fields after enabling NIC with DDP
-----------------------------------------
DA | SA | IPv4 | GRE | MPLS | DA | SA | IPv4 | UDP | PAYLOAD
\__________________________________________________/

In the above, MPLSoGRE is known flow type, so all filters like RSS possible
based on inner IP and inner UDP headers. The NIC can start recognizing the
inner packet header including the inner IPv4 and inner UDP headers and the
entropy increases because it can start using the UDP port information to compute
the RSS hash.

DDP toolchain
-------------
For DDP, the end-user need to create a custom profile for their packet type.
This can be created by using a tool-chain from Intel, called profile editor.
Intel has published some standard profiles too which can be directly downloaded
from intel website and used.

Step 1 - This profile editor can be used to create new entries or modify
existing entries for the NIC analyzer or parser

Step 2 - Create a new profile for MPLSoGRE packets which defines the structure
of packet headers for this encapsulation

Step 3 - Compile and create a binary package (.pkgo) which can be applied to
the NIC

Step 4 - Now the NIC is enabled to recognize MPLSoGRE packets

Code changes
------------
DDP feature applicable only for forville NIC family. When DPDK bootup with
command-line argument as --ddp and NIC driver as "net_i40e", vrouter programs
DDP profile stored in "/var/lib/ddp/mplsogreudp.pkg" for all ports.

Suppose, contrail-vrouter-dpdk passed with command line argument as --ddp and
NIC is not fortville(X710 series), vrouter silently ignores loading DDP profile
and bootup asusual.

Performance measurements
------------------------
MPPS   | Without DDP | With DDP | % Gain
1 core | 2           | 2        | 0.00
2 core | 3.8         | 3.8      | 0.00
3 core | 5.61        | 5.61     | 0.00
4 core | 6.48        | 7.48     | 15.43
6 core | 6.58        | 11.22    | 73.15

Latency (us) | Without DDP | With DDP | % Gain
Avg Latency  | 311         | 181      | 41.80
Max Latency  | 4154        | 768      | 81.51

Deployments supported
----------------------
- RHOSP
- Juju
- Kolla

CLI changes
-----------
dpdkinfo tool will display the status of DDP
New CLI added dpdkconf to add/delete DDP profile image.
dpdkinfo --ddp list -> To display the DDP profile.
dpdkconf --ddp add -> Add DDP profile, if NIC is fortville.
dpdkconf --ddp delete -> Delete already loaded DDP profile.

Default configuration
---------------------
By default DDP is not enabled, use the new command-line option --ddp to enable
DDP for fortville NIC.

Command-line options
--------------------
New command-line option --ddp to enable DDP only for fortville NIC family.

UI changes
-----------
None

Upgrade changes
----------------
None

Test cases
-----------
TBD
```

repository: tungstenfabric/tf-specs

repo_name: tungstenfabric/tf-specs


text:
## Synopsis

![Possumwood UI](doc/screenshot.png?raw=true)

Possumwood (named after [Sandbox Tree](https://en.wikipedia.org/wiki/Hura_crepitans)) is a **graph-based procedural sandbox**, implementing concepts of graph-based [visual programming](https://en.wikipedia.org/wiki/Visual_programming_language) in a simple interface. It is intended to provide a user-friendly and accessible UI for experimenting with common computer graphics algorithms and libraries (e.g., [OpenGL](https://www.opengl.org/), [CGAL](http://www.cgal.org/), [WildMagic](https://www.geometrictools.com/), [OpenCV](http://opencv.org/)).

Possumwood is built on top of a simple graph-evaluation engine and a Qt-based node graph editor, with an OpenGL viewport. Its main strength is its extensibility - it is trivial to implement new plugins supporting new libraries and data types, which allows free and user-friendly experimentation with parameters of each algorithm.

**Possumwood is a sandbox, not a production tool.** As a sandbox, it is quite open to radical changes and redesign, and for the time being it does not guarantee any form of backwards compatibility.

[![Build Status](https://travis-ci.org/martin-pr/possumwood.svg?branch=master)](https://travis-ci.org/martin-pr/possumwood) [![Snap Status](https://build.snapcraft.io/badge/martin-pr/possumwood.svg)](https://build.snapcraft.io/user/martin-pr/possumwood) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/85803e0b79d64c749038696d4e4512ad)](https://www.codacy.com/app/martin.prazak/possumwood?utm_source=github.com&utm_medium=referral&utm_content=martin-pr/possumwood&utm_campaign=Badge_Grade)

## Installation

Possumwood has been tested only on Linux (several distributions). While it should work on Windows, it has not been compiled or tested there. No support for MacOS is planned for the time being due to heavy dependency on OpenGL.

### Launchpad PPA for Ubuntu 18.04+

On Ubuntu, the easiest way to install Possumwood is to use the [snapshots PPA](https://code.launchpad.net/~martin-prazak/+archive/ubuntu/possumwood), which is built against daily builds of common CGI libraries in the [cg-daily PPA](https://code.launchpad.net/~cgi-daily-devs/+archive/ubuntu/cgi-daily):

```
sudo add-apt-repository ppa:martin-prazak/possumwood
sudo add-apt-repository ppa:cgi-daily-devs/cgi-daily
sudo apt-get update
sudo apt-get install possumwood
```

This will install Possumwood to your system, enabling to simply run `possumwood` command from any terminal.

Daily build of Possumwood is built against a number of packages that are newer than most distros provide out of the box. These are contained in the [`ppa:martin-prazak/cgi-daily`](https://launchpad.net/~martin-prazak/+archive/ubuntu/cgi-daily) PPA. Some packages might conflict with the system versions (OpenImageIO, OpenCV), requiring the original system packages to be uninstalled first.

### Installation using [Snap](https://snapcraft.io/)

Currently, Possumwood is released in Snap as a development/testing package only. The latest build and its status can be accessed [here](https://build.snapcraft.io/user/martin-pr/possumwood).

To install a testing version, please run:

```
sudo snap install --edge possumwood --devmode
```

This will download and install the latest successful build of Possumwood with its dependencies. To start the application, run `possumwood` from the command line. As a dev build, snap will not automatically update this installation. Moreover, snap skin support is currently rather rudimentary, making Possumwood not inherit the system look correctly.

### Building from source

The project is structured as a standard CMake-built project. To build, just run these in the directory of the repository on any Linux distro:

```
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=./install && make -j
```

This will build Possumwood and all its plugins, and install the result inside `./install` directory. Installation is necessary to make sure Possumwood is able to find its plugins and its dependencies. After that, you can run the build via:

```
./install/bin/possumwood
```

## Tutorials

### Basics

Tutorials are intended to introduce the concepts in Possumwood, and help a user navigate its UIs. They are still work-in-progress, and more will be added over time.

#### [Lua integration](https://github.com/martin-pr/possumwood/wiki/Lua-Basics)

This tutorial introduces the [Lua](https://en.wikipedia.org/wiki/Lua_(programming_language)) integration of Possumwood, using a simple example of an addition node.

### OpenGL / GLSL

#### [GLSL Turntable](https://github.com/martin-pr/possumwood/wiki/Basics-of-GLSL-in-Possumwood)

Introduces basic concepts of GLSL shaders in Possumwood, via a simple setup displaying a rotating car. Its model is loaded from an `.obj` file, converted to an OpenGL Vertex Buffer Object and displayed using a combination of a vertex and a fragment shader.

#### [Skybox](https://github.com/martin-pr/possumwood/wiki/Skybox)

A simple GLSL skybox setup, using fragment shader and the `background` node (based on [gluUnProject](https://www.khronos.org/registry/OpenGL-Refpages)) to render a background quad with spherically-mapped texture.

#### [Environment mapping](https://github.com/martin-pr/possumwood/wiki/Environment-mapping)

Environment map is a simple technique to approximate reflective surfaces in GLSL, without the need of actual raytracing. This tutorial builds on the previous Skybox tutorial, and extends it to make a teapot's material tool like polished metal.

#### [Wireframe using a geometry shader](https://github.com/martin-pr/possumwood/wiki/Wireframe-using-a-Geometry-Shader)

Most implementation of OpenGL 4 remove the ability to influence the width of lines using the classical `glLineWidth` call. This tutorial describes in detail how to achieve a similar effect (and much more) using a geometry shader, by rendering each line as a camera-facing polygon strip.

#### [PN Triangles Tesselation using a geometry shader](https://github.com/martin-pr/possumwood/wiki/Geometry-Shader-Tessellation-using-PN-Triangles)

Implementation of [Curved PN Triangles](https://alex.vlachos.com/graphics/CurvedPNTriangles.pdf) tessellation technique, presented by Alex Vlachos on GDC 2011. This method tessellates input triangles using solely their vertex positions and normals (independently of the mesh topology) in a geometry shader.

#### [Infinite Ground Plane using GLSL Shaders](https://github.com/martin-pr/possumwood/wiki/Infinite-ground-plane-using-GLSL-shaders)

Infinite ground plane, implemented using a single polygon and simple fragment shader "raytracing" against a plane with _Y=0_.

#### [Phong reflectance and shading models](https://github.com/martin-pr/possumwood/wiki/Phong-Lighting-Model)

The [Phong reflectance model](https://en.wikipedia.org/wiki/Phong_reflection_model), and [Phong shading](https://en.wikipedia.org/wiki/Phong_shading) are two basic models of light behaviour in computer graphics. This tutorial explains their function, and provides a step-by-step implementation in GLSL, using a single orbiting light as the lightsource.

### Image manipulation

#### [Image loading and display](https://github.com/martin-pr/possumwood/wiki/Images-Loading-and-Display)

This tutorial introduces basic concepts of image manipulation in Possumwood, and a simple shader-based OpenGL setup to display a texture in the scene.

#### [Image expressions](https://github.com/martin-pr/possumwood/wiki/Image-Generation-by-Expression)

Apart from [rendering existing images loaded from a file](Images-Loading-and-Display), Possumwood can also generate and edit images using [Lua scripting](https://en.wikipedia.org/wiki/Lua_(programming_language)). In this tutorial, we explore a very simple setup which uses Lua and per-pixel expressions to generate an image.

## Code Example

Possumwood is designed to be easily extensible. A simple addition node, using float attributes, can be implemented in a few lines of code:

```cpp
#include <possumwood_sdk/node_implementation.h>

namespace {

// strongly-typed attributes
dependency_graph::InAttr<float> input1, input2;
dependency_graph::OutAttr<float> output;

// main compute function
dependency_graph::State compute(dependency_graph::Values& data) {
	// maintains attribute types
	const float a = data.get(input1);
	const float b = data.get(input2);

	data.set(output, a + b);

	// empty status = no error (both dependency_graph::State and exceptions are supported)
	return dependency_graph::State();
}

void init(possumwood::Metadata& meta) {
	// attribute registration
	meta.addAttribute(input1, "a");
	meta.addAttribute(input2, "b");
	meta.addAttribute(output, "out");

	// attribute dependencies
	meta.addInfluence(input1, output);
	meta.addInfluence(input2, output);

	// and setting up a compute method
	meta.setCompute(compute);
}

// static registration of a new node type
possumwood::NodeImplementation s_impl("maths/add", init);

}
```

## API Reference

An auto-generated Doxygen reference can be found [here](https://martin-pr.github.io/possumwood/annotated.html)

## Contributors

Please feel free to contribute! I would welcome any form of feedback, opinions, bugs, code, or description of projects you are planning to use my code in!

At the moment, the project is in its **prototype stage**, and any feedback or help is welcome. In particular, it is in dire need of **a MS Windows build**, preferably using **AppVeyor**. Any help in that area would be greatly appreciated!

## License

The code is released under the [MIT license](https://en.wikipedia.org/wiki/MIT_License).

license: MIT

repository: happydpc/possumwood

repo_name: happydpc/possumwood


text:
DeDuplicated Queue (DDQ)
========================

[![npm version][npm-badge]][npm-link]
[![Build Status][travis-badge]][travis-link]
[![Dependencies][dependencies-badge]][dependencies-link]
[![Dev Dependencies][devdependencies-badge]][devdependencies-link]
[![codecov.io][codecov-badge]][codecov-link]

About
-----

This module was created because of a need for a system which acts like a queue for tasks but doesn't allow for duplication. DDQ uses an `async` methodology to complete certain tasks, sending and receiving messages, then indicating the message has been fully processed. We used `callbacks` instead of `Promises` to make the process faster and easier to integrate with other libraries.

DDQ also extends the Event Emitter module so it's very easy to use events for when there is a message or an error has occured and inform the software of these events.

DDQ is split into this core library and a backend. The core exposes the public interface, initializes the backend, then encapsulates some of the logic (such as message heartbeats) so the backends have less duplicated code. The backend is responsible for implementation-level details, such as how to store and retrieve messages and the queue cleanup jobs. The backend is specific to a data source, such as MySQL. Also, when a message is emitted to be processed, the backend should lock the message so no other instance may pick it up to be processed simultaneously.

Setting Up
----------

Setting up DDQ is pretty straight forward. It does require some configuration to get everything working together. Your project would need to include DDQ in it's `package.json` and also include a `backend` module or write one yourself. In the `config` value for `backend` this will set what module you're using. In the code this looks for `ddq-backend-whatYouHaveInConfigValueForBackend`. This should also be in your `node_modules/` directory, so it's easily found.

Another config value is the `heartbeatDelayMs`. DDQ uses a method on the wrapped message, which we'll get to later. A heartbeat routine is called every so often to update the task/job in the queue currently being processed. The `heartbeatDelayMs` is configured in milliseconds, so a value of "1000" would have the heartbeat execute every second.

Also, servers might not be able to handle a certain number of processes, or you might only want to handle a few at a time, so setting the `maxProcessingMessages` to a number will make it so only up to that number of processes are created. DDQ will automatically tell the backend to pause the polling when this limit is reached. It will resume polling once the number of processing messages is lower than the max.

Other config values would be more specific for what your backend needs, like table name, how often to poll the storage mechanism and so on. These are passed to the backend using the `backendConfig` values.

    var DeDuplicatedQueue, instance;

    DeDuplicatedQueue = require("ddq");

    /* Pass in the config, including which backend to use and DDQ will find it
     * and use it.
     */
    instance = new DeDuplicatedQueue({
        backend: "mock",
        backendConfig: {
            host: "localhost",
            password: "someReallyNiceLongSecurePassword",
            pollingDelayMs: 5000,
            port: 3306,
            table: "query",
            user: "hopefullyNotRoot"
        },
        heartbeatDelayMs: 1000,
        maxProcessingMessages: 10
    });

Sending a Message
-----------------

To send a message into the queue, use `instance.sendMessage()`. You pass in the message and an optional callback which be executed once the message has been sent. The message can be anything you want as the backend will be the one to process it and put it into its storage mechanism.

    instance.sendMessage("sample message", (err) => {
        if (err) {
            // Take action if there is an error.
        }
    });

Listening
---------

In order to receive messages from the queue, call `instance.listen()` and the instance will start to emit messages as they are found. DDQ will send two types of events: `data` and `error`. When `data` is emitted, you'll receive a message from the queue and a `callback` from DDQ. Once the process is complete you'll need to call the `callback` with an argument whether there was an error when processing.

When the `data` event is triggered from the backend, DDQ will use methods on the data received from the `backend`. These methods include: `heartbeat`, `requeue`, and `remove`. The only piece of information the software running DDQ will receive is the message and the callback from DDQ in order to say whether the processing of the message was successful or not. When the message is being processed, DDQ will call the `heartbeat` method on the `wrappedMessage` using `heartbeatDelayMs` from the config to tell the `backend` to update the heartbeat at that interval.

    // Starts listening for events.
    instance.listen();

    /* DDQ uses event emitters and you'll need to listen for them so your
     * applications can take actions.
     */
    instance.on("data", (message, callback) => {
        // Take action on the data.
        if (somethingBadHappened) {

            // Requeued for later processing.
            callback(new Error("Something bad happened"));
        } else {

            // Removed as message is no longer needed.
            callback();
        }
    });

The other event DDQ will emit is `error`. This alerts the code listening there was an error either coming from DDQ or passed back from the backend.

    instance.on("error", () => {
        // Take action on the error.
    });

Pausing and Resuming Polling
----------------------------

At some point your consumer might want to pause the polling of messages so it can do a task without having messages coming at it. You can do this by simply calling the DDQ method `instance.pausePolling()`. This doesn't use a `callback`, for if there is an error it should be emitted and picked up by the listener.

    // Tells the backend to stop polling.
    instance.pausePolling();

Once you feel you should resume polling you can call the `instance.resumePolling()` method. We don't want to resume polling if the limit has been reached. This also doesn't use a `callback`, for if there is an error it should be emitted and picked up by the listener.

    // Tells the backend to resume polling.
    instance.resumePolling();

Closing
-------

At some time you'll want to stop listening to DDQ which you will call `close`. This will call the backend to close its connections, stop polling for messages and stop emitting messages..

    // Stop listening to events and close the connection to the database.
    instance.close((err) => {
        if (err) {
            // Take action if there is an error.
        }
    });

[codecov-badge]: https://img.shields.io/codecov/c/github/tests-always-included/ddq/master.svg
[codecov-link]: https://codecov.io/github/tests-always-included/ddq?branch=master
[dependencies-badge]: https://img.shields.io/david/tests-always-included/ddq.svg
[dependencies-link]: https://david-dm.org/tests-always-included/ddq
[devdependencies-badge]: https://img.shields.io/david/dev/tests-always-included/ddq.svg
[devdependencies-link]: https://david-dm.org/tests-always-included/ddq#info=devDependencies
[npm-badge]: https://img.shields.io/npm/v/ddq.svg
[npm-link]: https://npmjs.org/package/ddq
[travis-badge]: https://img.shields.io/travis/tests-always-included/ddq/master.svg
[travis-link]: http://travis-ci.org/tests-always-included/ddq

repository: tests-always-included/ddq

gha_language: JavaScript

repo_name: tests-always-included/ddq


text:
---
external help file: ILAssembler-help.xml
online version: https://docs.microsoft.com/en-us/dotnet/api/system.reflection.emit.opcodes.stloc_2
schema: 2.0.0
---

# stloc.2

## SYNOPSIS

Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.

## SYNTAX

```powershell
stloc.2
```

## DESCRIPTION

The following table lists the instruction's hexadecimal and Microsoft Intermediate Language (MSIL) assembly format, along with a brief reference summary:

| Format | Assembly Format |
| ------ | --------------- |
| 0C     | stloc.2         |

 The stack transitional behavior, in sequential order, is:

1.  A value is popped off of the stack and placed in the local variable indexed by 2.

 The `stloc.2` instruction pops the top value off the evaluation stack and moves it into the local variable indexed by 2. The type of the value must match the type of the local variable as specified in the current method's local signature.

 `stloc.2` is an especially efficient encoding for storing values in local variable 2.

 Storing into locals that hold an integer value smaller than 4 bytes long truncates the value as it moves from the stack to the local variable. Floating-point values are rounded from their native size (type `F`) to the size associated with the argument.

## INPUTS

### None

This function cannot be used with the pipeline.

## OUTPUTS

### None

This function cannot be used with the pipeline.

## NOTES

## RELATED LINKS

repository: SeeminglyScience/ILAssembler

repo_name: SeeminglyScience/ILAssembler


text:
---
templateKey: about-page
title: Apply to Trade
subtitle: Strawberry Fair is back in 2023
heroData:
  heroImages: []
  isActive: true
strawberryTiles:
  - strawberryTile:
      isPublic: false
    tile: Strawberry Tile
notes: >-
  TEXT OF PAGE TO REPLACE WHEN REOPENING NEXT YEAR

  # Applications are open to trade at Strawberry Fair on 6th June 2020

  We are looking for traders and organisations offering as many different
  flavours and tastes, products and produce, weird and wonderful hobbies and
  interesting people to amuse and entertain our visitors. Our market is one of
  the most important features of the Fair - bringing a diverse range of stalls
  right to the heart of Cambridge.

  ## Why Trade at Strawberry Fair?

  * We regularly attract 35,000-40,000 visitors throughout the one day event

  * We are a free event, but many punters tell us they come specifically to buy
  from our market.

  * We reach an eclectic mix of people of all ages including residents, visitors
  and tourists.

  * We do our best to limit the number of similar stalls to ensure that our
  traders are offering different things.

  * We offer a range of pitch fees and types to suit all needs, including food
  stalls, craft stalls, blanket pitches, mobile sellers and charity stands.

  ## Bars / Alcohol

  Bar pitches for 2020 have already been allocated. No new applications are
  being accepted.

  ## Non-food traders

  Please complete the non-food trader application form here:

  [Non-food Trader Application Form](/forms/non-food-trader-application)

  If you have any queries, please see [Trader
  FAQ](https://docs.google.com/document/d/1VK62GAmE1bzmHqwnoVzksYNBo0hmcGAaqFn3pZUGEgY/edit?usp=sharing)
  or email<EMAIL_ADDRESS>if you can't find the answer.

  ## Food Traders

  Please complete the food trader application form here:

  [Food Trader Application Form](/forms/food-trader-application)

  Applications for food trader pitches at the 2020 fair are open until 29th
  February 2020.

  Food pitches are not allocated on a first come first served basis, as we have
  a limited number of food pitches available. To ensure we can offer a variety
  of cuisines to visitors of the Fair, we will consider all of the applications
  we have received in early spring and make pitch offers to traders at that
  point.

  If you have any questions about selling food or non-alcoholic drinks at
  Strawberry Fair, please see [Trader
  FAQ](https://docs.google.com/document/d/1VK62GAmE1bzmHqwnoVzksYNBo0hmcGAaqFn3pZUGEgY/edit?usp=sharing)
  or email<EMAIL_ADDRESS>if you can't find the answer.
---
## **Non-Food applications**

Please complete the following form and we will then contact you with a quote for your stall.

[Non-Food Trader Application Form](https://docs.google.com/forms/d/e/1FAIpQLSeXcPsh1vtYM1h3KYXjw2gH8oSQVq2VG6HsKZNl5EwEBibU_A/viewform?embedded=true)

## **Food applications**

Complete the following form and we will consider food applications and let you know in the third week of February whether we have been able to allocate you a space for 2023.

[Food Trader Application Form](https://docs.google.com/forms/d/e/1FAIpQLSf069Lcr8vfia2ZNbfZIDeHP3A_QIzOjHkEB9QDrq0NTF5ghA/viewform?embedded=true)

If you have any questions, check the [Trader FAQ](https://docs.google.com/document/d/1VK62GAmE1bzmHqwnoVzksYNBo0hmcGAaqFn3pZUGEgY/edit?usp=sharing) section for more information about the fair. If you need more help email us at<EMAIL_ADDRESS>
# Trading at Strawberry Fair

Strawberry Fair 2023 will be on Saturday 3rd June. The Faeries are so happy to be back and so looking forward to seeing you again. Let’s all celebrate by making this the best Strawberry Fair ever!

The theme this year will be **REVOLUTION**.

We are looking for traders and organisations offering as many different flavours and tastes, products and produce, weird and wonderful hobbies and interesting people to amuse and entertain our visitors. Our market is one of the most important features of the Fair - bringing a diverse range of stalls right to the heart of Cambridge.

## Why Trade at Strawberry Fair?

* We regularly attract 35,000-40,000 visitors throughout the one day event
* We are a free event, but many punters tell us they come specifically to buy from our market.
* We reach an eclectic mix of people of all ages including residents, visitors and tourists.
* We do our best to limit the number of similar stalls to ensure that our traders are offering different things.
* We offer a range of pitch fees and types to suit all needs, including food stalls, craft stalls, blanket pitches, mobile sellers and charity stands.

## Bars / Alcohol

Bar pitches for 2023 have already been allocated. No new applications are being accepted.

repository: Softwire/strawberry-fair

repo_name: Softwire/strawberry-fair


text:
# Sapper + Github Actions + S3

Read how to create this repository from strach [here](https://swerdlowben.medium.com/automate-sapper-deployments-with-github-actions-d858e154dfb6)

This is a template repo that allows you to automatically deploy your **Sapper** app to S3 whenever there is a push to master with Github Actions.

# Setup

Add the following secrets to your repository:

1. The first secret will be your Access key ID, which you should name **AWS_ACCESS_KEY_ID**
2. Your second secret will be your Secret access key, which you should name **AWS_SECRET_ACCESS_KEY**
3. Your third secret will be your S3 location, which you should name **S3**. It should be formatted like **s3://yourbucket/**

branch_name: refs/heads/main


text:
Virtual Pronunciation Coach developed in React

[![Status](https://img.shields.io/badge/status-active-success.svg)]()
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](/LICENSE)

---

## ⛏ Built Using

- [React](https://reactjs.org//) - Framework to build iOS and Android App.
- [Redux](https://redux.js.org//) - Library for managing application state.
- [Redux-Saga](https://redux-saga.js.org/) - Saga middleware for Redux to handle Side Effects.
- [i18next](https://www.i18next.com/) - Internationalization framework (react-native-localize was used to identify the device language).

## Available Scripts

In the project directory, you can run:

### `yarn start`

Runs the app in the development mode.

Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.

You will also see any lint errors in the console.

### `yarn test`

Launches the test runner in the interactive watch mode.

See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `yarn build`

Builds the app for production to the `build` folder.

It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.

Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

repository: marciomarquessouza/repeat-please-web

repo_name: marciomarquessouza/repeat-please-web


text:
# airflow-azure-hdinsight-plugin
Airflow plugin to create/delete Azure HDInsight cluster

## Usage
Put this plugin into your Airflow plugin folder, in your DAG file, use the following code to import operators

```py
from airflow.operators.hdinsight_plugin import HDInsightCreateClusterOperator, HDInsightDeleteClusterOperator
```

Please find more examples in `sample_dag.py`


text:
---
title: 'Simple calculator using TDD in F# (part-4)'
author: Zp Bappi
layout: post
permalink: /simple-calculator-using-tdd-in-fsharp-part-4/
categories:
  - 'F#'
tags:
  - calculator
  - fsharp
  - rpn
  - tdd
  - unquote
---
Just as a (very) quick recap, I started from a simple Stack in [part-1](http://zpbappi.com/simple-calculator-using-tdd-in-fsharp-part-1/) and ended up creating a fully functioning RpnCalculator in [part-2](http://zpbappi.com/simple-calculator-using-tdd-in-fsharp-part-2/) and [part-3](http://zpbappi.com/simple-calculator-using-tdd-in-fsharp-part-3/). In this part, I will try to focus on two things-

  1. Ability to add mathematical operations from outside.
  2. Ability to handle unary operations.

But, I will first clean up the module and namespace declaration a little. It got messy as I was not paying attention to it at all. I decided to have a single namespace for a single project (Stack, RpnCalculator, etc.). Within these namespaces, there will be types declared that I want to expose automatically when I use the namespaces. Also, the namespaces will contain relevant module declaration within themselves. So, *Stack* namespace will have a type *Stack<'a>* defined inside along with the module *Stack*. That will ensure some consistency in the module and namespace names. Also, I have to write *Stack.push* and *Stack.pop* now, which is looks more meaningful. Finally, I have to fix the tests to compile with this new form. The changes I made for Stack and Stack.Tests projects can be found [here][4].

Since the re-arranging of namespace and module for Stack makes it looks cool, I want to do the same for RpnCalculator too. I placed *RpnCalculator* and *RpnResult* type declarations in the RpnTypes.fs file, outside any module declaration. I also made the *RpnBinaryOperation* module internal inside the *RpnCalculator* namespace. Needless to say, I have to add proper prefix in test codes too to compile them and run. Exact detail of the changes I made can be found in [this commit detail][5].

Lets get down to business and create something awesome. It is about time I start using *RpnCalculator* type that I have defined since forever! Looking at it, looks like I don't need any stack within the calculator. Because, I will be passing the stack as a parameter to the *calculate* method. So, after removing the stack, the *RpnCalculator* type looks like:

[][6]

I also realize that all the operations I have defined so far takes two decimal numbers as input and returns a decimal as output. So, let's change the type definition for *Operation* to match that. Here is how the whole *RpnTypes* module looks like:

[][7]

Much meaningful now and I feel like I can use it pretty soon. I am adding a new method in RpnCalculator.fs file, right before calculate method, to get a new instance of RPN calculator. Here it is:

[][8]

Looks pretty simple. I haven't actually changed anything to affect the calculate method so far. But, it is good a idea to run the tests often. With all the tests green, now I want to pass a calculator object to the calculate function. The reason behind this would be to access the list of operations I have in the calculator object. For this reason, I definitely need the object passed into the *getOperation* method. Let's change the signature (not the implementation) like:

[][9]

*getOperation* is only called from *evaluateRpnExpr*. The requirement of passing the calculator object immediately forces the change in implementation of evaluateRpnExpr to include *calculator*stack* as the first parameter, instead of simply *stack*. It looks like:

[][10]

Important thing to note that, I also need change return type from the function to *calculator*stack* to make it suitable for *List.fold*. Now, I changed the *calculate* method a bit to match the signature of the list folder (i.e. *evaluateRpnExpr* method) and passed *null* as a calculator. Here is how:

[][11]

I have the projects compiling now. First thing is to run the tests. Phew! they are all green. With the confidence of the tests I have, I am now going to use an actual calculator now to figure our the operation for a symbol, instead of previous static mapping. So, my modified *getOperation* method looks like:

[][12]

Now, I have to pass in the real calculator from *calculate* method. So, fixing a small mistake in *createInstance* method, the new *calculate* method looks like (changes are highlighted in yellow):

[][13]

Amazingly, all tests are green. :)

Now, I am ready to pass in calculator from outside world to the calculate method. So, I changed the signature of the method as:

[][14]

This will make all the tests fail to compile. So, I am going to cheat a little with TDD and pass in *RpnCalculator.createInstance()* as the newly introduced parameter. The changes I made can be found in [this commit detail][15]. It immediately makes the tests pass. How cool is that!

Now, I am going to rock the world (of RpnCalculator). I am adding a new method of, called *registerBinaryOperation*, with the expectation that it will take an operator symbol, operation definition for the symbol and a calculator. In return, it will give the calculator back where the new operator/operation is known. A simplest dummy-compiler-friendly implementation of such method would be:

[][16]

I placed this method in the RpnCalculator.fs file, right above the *calculate* method. I added a new test file to define the behavior of this method in a new file named RegisterBinaryOperationTest.fs in the RpnCalculator.Tests project. And, the test cases look like:

[][17]

Well, the test helper method *getCalculatorWithPow( )* may look a bit scary. That is not my fault (!). Math.Pow can take float inputs and return float output. But, I need decimal. So, lot of explicit type conversions are in place, that's all. Important thing is, I am passing a symbol and an operation to register in the calculator as a known operation. Tests look fine, except they all fail. *Unknown operator: ^*.  Well, that is the exception message that I throw from calculator when an unknown operator is found. So, it is obvious that the new operator registration is not working with the dummy implementation I have. Let's change it to a proper implementation as:

[][18]

When I run my tests now, all are passing. Amazing. That marks the end of first part.

In the next part, I will try to add the ability to handle unary operators like *neg*, *sqr*, *sqrt*, etc. So, as before, I add a method like:

[][19]

This lets me write tests I want. So, I add a new file named RegisterUnaryOperationTests.fs with the following tests:

[][20]

Tests looks nice, but, as expected, they all fail. Because, I haven't really implemented the *registerUnaryOperation* method properly. To do that, first I will need to introduce a new type of operation in my discriminated union type *Operation*. Obviously it looks like:

[][21]

After looking at the code which is currently responsible for doing "operation", I came up with the following implementation that can support both unary and binary operators. Here is the new implementation of "operation" section of the module:

[][22]

Here, *applyBinaryOperands* and *applyUnaryOperand* methods are returning decimal now. The *applyOperation* method is taking care of proper method to call, stack manipulation and conversion of result type. I think it will be easier to understand the changes if we can see what has changed from previous version. [This commit detail][23] will help with understanding the changes. I have also implemented the *registerUnaryOperation* method properly, replacing the previous dummy implementation. It looks like:

[][24]

Now, when I run the tests, all passes except one particular test that tries to state that, *ln(e^x) == x*. Well, in my test case, I have used *x = 42*. Looking detail inside test failure message, I found that it is actually failing to convert a very large number from decimal to integer inside *operandConversion* method. And, the very large decimal being *e^42*. It indicates that I need to add some checks in this method to stop overflow or underflow errors like this. So, the improved method definition looks like:

[][25]

And, all my tests are shining green. :)

That's all for this part. In the next part, I will either spend some time on optimization or will step into the implementation of a calculator for [infix][26] notation (how people write mathematical expressions).

***Useful links***

  * GitHub repository: [fsharp-tdd-calculator][27]
  * Link to other parts: README section of the [repository][27]

 [1]: http://zpbappi.com/simple-calculator-using-tdd-in-fsharp-part-1/
 [2]: http://zpbappi.com/simple-calculator-using-tdd-in-fsharp-part-2/
 [3]: http://zpbappi.com/simple-calculator-using-tdd-in-fsharp-part-3/
 [4]: https://github.com/zpbappi/fsharp-tdd-calculator/commit/d6a9c5d0a71dcc9ea37c99df4e874d828585d77d
 [5]: https://github.com/zpbappi/fsharp-tdd-calculator/commit/6b5deeb791067c34077cf4856ae4afbfd910caf8
 [6]: {{site.url}}{{site.baseurl}}/images/2015/08/04-01.png
 [7]: {{site.url}}{{site.baseurl}}/images/2015/08/04-02.png
 [8]: {{site.url}}{{site.baseurl}}/images/2015/08/04-03.png
 [9]: {{site.url}}{{site.baseurl}}/images/2015/08/04-04.png
 [10]: {{site.url}}{{site.baseurl}}/images/2015/08/04-05.png
 [11]: {{site.url}}{{site.baseurl}}/images/2015/08/04-06.png
 [12]: {{site.url}}{{site.baseurl}}/images/2015/08/04-07.png
 [13]: {{site.url}}{{site.baseurl}}/images/2015/08/04-08.png
 [14]: {{site.url}}{{site.baseurl}}/images/2015/08/04-09.png
 [15]: https://github.com/zpbappi/fsharp-tdd-calculator/commit/0090d199674bd3246d308cdf656b1f105633f9e3
 [16]: {{site.url}}{{site.baseurl}}/images/2015/08/04-10.png
 [17]: {{site.url}}{{site.baseurl}}/images/2015/08/04-11.png
 [18]: {{site.url}}{{site.baseurl}}/images/2015/08/04-12.png
 [19]: {{site.url}}{{site.baseurl}}/images/2015/08/04-13.png
 [20]: {{site.url}}{{site.baseurl}}/images/2015/08/04-14.png
 [21]: {{site.url}}{{site.baseurl}}/images/2015/08/04-15.png
 [22]: {{site.url}}{{site.baseurl}}/images/2015/08/04-16.png
 [23]: https://github.com/zpbappi/fsharp-tdd-calculator/commit/5ace69445303e64aa04a2f547e47fd3ac8b79a38
 [24]: {{site.url}}{{site.baseurl}}/images/2015/08/04-17.png
 [25]: {{site.url}}{{site.baseurl}}/images/2015/08/04-18.png
 [26]: https://en.wikipedia.org/wiki/Infix_notation
 [27]: https://github.com/zpbappi/fsharp-tdd-calculator


text:
# CHANGELOG

## 1.0.0

- fix Rubocop warnings

## 0.9.1

- add default "backupper" user password

  This password is not really used (ssh connection is key- based), but without
  a password, and sshd's `UsePAM` set to `no`, the connection cannot be
  established due to the fact that the password field in the shadow file
  contains "!", which sshd then intrepids as a "locked account":

      User backupper not allowed because account is locked

  If you have a need to know this password, you should override it with your
  own.

## 0.9.0

- initial commit of `backuppc-client`

repository: kabisa-cookbooks/backuppc-client

repo_name: kabisa-cookbooks/backuppc-client


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

### Description

An issue was discovered on Mitsubishi Electric ME-RTU devices through 2.02 and INEA ME-RTU devices through 3.0. An unauthenticated remote OS Command Injection vulnerability allows an attacker to execute arbitrary commands on the RTU due to the passing of unsafe user supplied data to the RTU's system shell. Functionality in mobile.php provides users with the ability to ping sites or IP addresses via Mobile Connection Test. When the Mobile Connection Test is submitted, action.php is called to execute the test. An attacker can use a shell command separator (;) in the host variable to execute operating system commands upon submitting the test data.

### POC

#### Reference
- https://www.mogozobo.com/
- https://www.mogozobo.com/?p=3593

#### Github
- https://github.com/ARPSyndicate/cvemon

repository: trickest/cve

gha_language: HTML

gha_license_id: MIT

repo_name: trickest/cve


text:
# Game of Life Benchmark

Benchmarking different programming languages on Game of Life.

**Warning**: Non-scientific approach. Please look at the code before making any
conclusions.

The goal of this project is to benchmark several programming languages by
implementing Game of Life. Implementations might not be the most efficient in a
given programming language. I'm not experienced in any of those languages except
Ruby.

Also, one of the goals is to check how "nice" a language is for implementing
systems such as Game of Life, so striving for ultimate performance is not the
goal.

## Results

1000 iterations with 100x100 board. VM with 2 cores.

Language | Note | Result (ms)
---------|------|------------
Elixir | Sequential | 169,862
Elixir | Every cell update in a separate process | 2,455,931
Elixir | Every column in a separate process | 158,204
Ruby | | 87,656
JavaScript | Firefox, not in VM | 5,737

repository: strika/gol-benchmark

gha_language: Elixir

repo_name: strika/gol-benchmark


text:
# Typhula culmigena (Mont. & Fr.) Berthier, 1976 SPECIES

#### Status
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. mens. Soc. linn. Lyon 45: 186 (1976)

#### Original name
Pistillaria culmigena Mont. & Fr., 1836

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone


text:
# Trie

> pronouced "trie" as in `reTRIEve`

Trie, a.k.a. a digital tree, is a search tree in which we can store data in a tree-like structure. In the case of this exercise, nodes (letters) will chain upon each other to build out a word. The last node of a word is called a leaf, signifying the end of a valid word.

For example, the word, `cat`, `catch`, and `car`.

```
root
  |
  └── c
      |
      └── a
          |
          ├─- t (leaf)
          |   |
          |   └── c
          |       |
          |       └── h (leaf)
          |
          └── r  (leaf)
```

## Complexity

Access	Search	Insertion	Deletion
O(k)	  O(k)	  O(k)	    O(k)

where k is the word length.

### Usage

Running node on the `index.js` file located in the root of the repository will be your interactive test (in addition to the tests spec'd out in the `tests` directory).

```javascript
let trie = new Trie();
trie.add('cat');
trie.add('dog');

trie.exists('cat'); // returns true
trie.exists('dog'); // returns true
trie.exists('mouse'); //returns false
```

#### References

[Wikipedia: Trie](https://en.wikipedia.org/wiki/Trie)

repository: JoeKarlsson/data-structures

repo_name: JoeKarlsson/data-structures


text:
# google-images-dataset
This repository provides the necessary code to create your own Google Images Dataset in the form of an interactive Jupyter Notebook. Unlike other downloaders, to the best of my knowledge, this method respects [Google's Terms of Service](https://support.google.com/webmasters/answer/66357?hl=en).
To be able to run this tutorial you will need to have the latest version of the fastai library installed.

If using conda:

``` bash
conda update conda
conda install -c fastai fastai
```

If using pip:
```bash
pip install fastai
```

Credits to Jeremy Howard as co-author and Adrian Rosenbrock's [tutorial](https://www.pyimagesearch.com/2017/12/04/how-to-create-a-deep-learning-dataset-using-google-images/) for inspiration.

gha_language: Jupyter Notebook


text:
---
name: Check team permissions for a repository
example: octokit.rest.teams.checkPermissionsForRepoInOrg({ org, team_slug, owner, repo })
route: GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}
scope: teams
type: API method
---

# Check team permissions for a repository

Checks whether a team has `admin`, `push`, `maintain`, `triage`, or `pull` permission for a repository. Repositories inherited through a parent team will also be checked.

You can also get information about the specified repository, including what permissions the team grants on it, by passing the following custom [media type](https://docs.github.com/rest/overview/media-types/) via the `application/vnd.github.v3.repository+json` accept header.

If a team doesn't have permission for the repository, you will receive a `404 Not Found` response status.

**Note:** You can also specify a team by `org_id` and `team_id` using the route `GET /organizations/{org_id}/team/{team_id}/repos/{owner}/{repo}`.

```js
octokit.rest.teams.checkPermissionsForRepoInOrg({
  org,
  team_slug,
  owner,
  repo,
});
```

## Parameters

      name
      required
      description

org	yes

The organization name. The name is not case sensitive.

team_slug	yes

The slug of the team name.

owner	yes

The account owner of the repository. The name is not case sensitive.

repo	yes

The name of the repository without the `.git` extension. The name is not case sensitive.

See also: [GitHub Developer Guide documentation](https://docs.github.com/rest/reference/teams/#check-team-permissions-for-a-repository).

gha_language: TypeScript


text:
# cdi-bundle
`cdi-bundle` is a Dropwizard bundle for adding [CDI](http://weld.cdi-spec.org) functionality to the Dropwizard applications.

### Usage
Add the following to the `build.gradle`

```
repositories {
	jcenter()
}

dependencies {
	compile "com.cognodyne.dw:cdi-bundle:$cdiBundleVersion"
}
```

Then, your `MyApplicationConfiguration.java` should look something like the following:

```
public class MyApplicationConfiguration extends Configuration implements CdiConfigurable {
	@Valid
    @JsonProperty("cdi")
    private Optional<CdiConfiguration> cdiConfig = Optional.empty();

    public CdiConfiguration getCdiConfiguration() {
    		return cdiConfig.orNull();
    }
}
```

Then, your `MyApplication.java` should look something like the following:

```
@ApplicationScoped
public class MyApplication extends Application<MyApplicationConfiguration> {
	@Inject
    private CdiBundle            cdiBundle;

    @Override
    public void initialize(Bootstrap<MyApplicationConfiguration> bootstrap) {
        bootstrap.addBundle(this.cdiBundle);
    }

    @Override
    public void run(ExampleConfiguration configuration, Environment environment) throws Exception {
    }

    public static void main(String... args) {
        try {
            CdiBundle.application(MyApplication.class, args).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

```

The above will perform the following:
- Add all subclass of `io.dropwizard.cli.Command` to the Dropwizard Bootstrap
- Add all subclass of `io.dropwizard.cli.ConfiguredCommand` to the Dropwizard Bootstrap
- Register all subclass of `com.codahale.metrics.health.HealthCheck` with `javax.inject.Named` annotation to the `io.dropwizard.setup.Environment.healthChecks()`
- Register all implementing classes of `io.dropwizard.lifecycle.Managed` interface to `io.dropwizard.setup.Environment.lifecycle().manage()`
- Register all subclass of `io.dropwizard.servlets.tasks.Task` to the `io.dropwizard.setup.Environment.admin().addTask()`
- Register all implementing classes of `javax.ws.rs.container.DynamicFeature` interface to `io.dropwizard.setup.Environment.jersey()`
- Add all implementing classes of `javax.servlet.Filter` interface with with `javax.servlet.annotation.WebFilter` annotation to the `io.dropwizard.setup.Environment.servlets().addFilter()`. Filters will be ordered according to the value of `javax.annotation.Priority`. If `javax.annotation.Priority` annotation is not present, the `java.lang.Integer.MAX_VALUE` will be assigned.
- Add all implementing classes of `javax.servlet.Servlet` interface with with `javax.servlet.annotation.WebServlet` annotation to the `io.dropwizard.setup.Environment.servlets().addServlet()`
- Register all classes with `javax.ws.rs.Path` annotation to the `io.dropwizard.setup.Environment.jersey()`

The above default behavior can be altered with the appropriate configuration.

```
cdi:
  includes:
    - "com/cognodyne/cdi/**"
  excludes:
    - "com/cognodyne/**"
    - "com/some/other/**"
```

The above will exclude all fully qualified class names (after converting all `.` with `/`) matching one of the glob expressions from the `excludes` unless it also matches one of the glob expressions from the `includes`.
All classes are included unless excluded, and `includes` has higher precedent than `excudes`.
See `java.nio.file.FileSystems.getPathMatcher()` for the glob expression syntax (very similar to the 'Ant style' path pattern expression).

If any beans with `javax.inject.Singleton` or `javax.enterprise.context.ApplicationScoped` are also annotated with `com.cognodyne.dw.cdi.annotation.Startup`, then they will be started at the time of application startup.

Any non cdi managed object instances, such as `Bootstrap` or `Configuration`, can be injected via the following mechanism:

```
@ApplicationScoped
public class MyApplication extends Application<MyApplicationConfiguration> {
	@Inject
    private CdiBundle            cdiBundle;
    private ExampleConfiguration configuration;

    @Captured
    @Produces
    public ExampleConfiguration getConfiguration() {
    		return this.configuration;
    }

    @Override
    public void initialize(Bootstrap<MyApplicationConfiguration> bootstrap) {
        bootstrap.addBundle(this.cdiBundle);
    }

    @Override
    public void run(ExampleConfiguration configuration, Environment environment) throws Exception {
    		this.configuration = configuration;
    }

    public static void main(String... args) {
        try {
            CdiBundle.application(MyApplication.class, args).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

Then, `ExampleConfiguration` object can be injected as the following:

```
@Path("/hello")
public class HelloResource implements HelloService {
	@Inject
	@Captured
	private ExampleConfiguration configuration;

	@GET
	public String sayHello() {
		return this.configuration.getHelloMessage();
	}
}

```
`com.cognodyne.dw.cdi.annotation.Captured` is necessary to disambiguate the actual config object from the default constructed bean.

repository: mstoeckel/cdi-bundle

gha_language: Java

repo_name: mstoeckel/cdi-bundle