text:
package org.apache.sis.metadata.iso.extent;

import java.util.Map;
import org.opengis.metadata.extent.GeographicBoundingBox;
import org.apache.sis.measure.Latitude;
import org.apache.sis.measure.Longitude;
import org.apache.sis.test.DependsOnMethod;
import org.apache.sis.test.TestCase;
import org.junit.Test;

import static java.lang.Double.NaN;
import static org.junit.Assert.*;

/**
 * Tests {@link DefaultGeographicBoundingBox}.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @since   0.4
 * @version 0.5
 * @module
 */
public final strictfp class DefaultGeographicBoundingBoxTest extends TestCase {
    /**
     * Asserts that the given geographic bounding box is strictly equals to the given values.
     * The {@link GeographicBoundingBox#getInclusion()} is expected to be {@code true}.
     */
    private static void assertBoxEquals(final double λbgn, final double λend,
                                        final double φmin, final double φmax,
                                        final GeographicBoundingBox box)
    {
        assertEquals("inclusion", Boolean.TRUE, box.getInclusion());
        assertEquals("westBoundLongitude", λbgn, box.getWestBoundLongitude(), STRICT);
        assertEquals("eastBoundLongitude", λend, box.getEastBoundLongitude(), STRICT);
        assertEquals("southBoundLatitude", φmin, box.getSouthBoundLatitude(), STRICT);
        assertEquals("northBoundLatitude", φmax, box.getNorthBoundLatitude(), STRICT);
    }

    /**
     * Returns {@code true} if the given box is spanning over the anti-meridian.
     */
    static boolean isSpanningAntiMeridian(final GeographicBoundingBox box) {
        return box.getWestBoundLongitude() > box.getEastBoundLongitude();
    }

    /**
     * Tests construction with an invalid range of latitudes.
     */
    @SuppressWarnings("ResultOfObjectAllocationIgnored")
    @Test(expected = IllegalArgumentException.class)
    public void testInvalidLatitudeRange() {
        new DefaultGeographicBoundingBox(-1, +1, 12, 10);
    }

    /**
     * Tests {@link DefaultGeographicBoundingBox#normalize()}. This is also an indirect test of
     * {@link DefaultGeographicBoundingBox#DefaultGeographicBoundingBox(double, double, double, double)} and
     * {@link DefaultGeographicBoundingBox#setBounds(double, double, double, double)}, but those later methods
     * are quite trivial except for the call to {@code normalize()}.
     */
    @Test
    public void testNormalize() {
        final DefaultGeographicBoundingBox box = new DefaultGeographicBoundingBox(-180, +180, -90, +90);
        assertBoxEquals(-180, +180, -90, +90, box);
        assertFalse(isSpanningAntiMeridian(box));
        /*
         * Span more than the whole Earth.
         */
        box.setBounds  (-200, +200, -100, +100);
        assertBoxEquals(-180, +180,  -90,  +90, box);
        assertFalse(isSpanningAntiMeridian(box));
        /*
         * Values in a shifted range, but without anti-meridian spanning.
         */
        box.setBounds  (380, 420, -8, 2);
        assertBoxEquals( 20,  60, -8, 2, box);
        assertFalse(isSpanningAntiMeridian(box));
        /*
         * Anti-meridian spanning, without change needed.
         */
        box.setBounds  ( 160, -170, -8, 2);
        assertBoxEquals( 160, -170, -8, 2, box);
        assertTrue(isSpanningAntiMeridian(box));
        /*
         * Anti-meridian spanning in the [0 … 360]° range.
         */
        box.setBounds  ( 160,  190, -8, 2);
        assertBoxEquals( 160, -170, -8, 2, box);
        assertTrue(isSpanningAntiMeridian(box));
        /*
         * Random anti-meridian spanning outside of range.
         */
        box.setBounds  (-200, +20, -8, 2);
        assertBoxEquals( 160, +20, -8, 2, box);
        assertTrue(isSpanningAntiMeridian(box));
        /*
         * Special care for the ±180° longitude bounds.
         */
        box.setBounds(-180,  +20, -8, 2); assertBoxEquals(-180,  +20, -8, 2, box); // Already normalized.
        box.setBounds( +20, +180, -8, 2); assertBoxEquals( +20, +180, -8, 2, box); // Already normalized.
        box.setBounds(+180,  +20, -8, 2); assertBoxEquals(-180,  +20, -8, 2, box); // Normalize west bound so we don't need to span anti-meridian.
        box.setBounds( +20, -180, -8, 2); assertBoxEquals( +20, +180, -8, 2, box); // Normalize east bound so we don't need to span anti-meridian.
        box.setBounds(-180, -180, -8, 2); assertBoxEquals(-180, -180, -8, 2, box); // Empty box shall stay empty.
        box.setBounds(+180, +180, -8, 2); assertBoxEquals(-180, -180, -8, 2, box); // Empty box shall stay empty.
        /*
         * Special care for the ±0° longitude bounds.
         */
        box.setBounds(+0.0, +0.0, -8, 2); assertBoxEquals(+0.0, +0.0, -8, 2, box);
        box.setBounds(-0.0, +0.0, -8, 2); assertBoxEquals(-0.0, +0.0, -8, 2, box);
        box.setBounds(-0.0, -0.0, -8, 2); assertBoxEquals(-0.0, -0.0, -8, 2, box);
        box.setBounds(+0.0, -0.0, -8, 2); assertBoxEquals(-180, +180, -8, 2, box);
    }

    /**
     * Tests {@link DefaultGeographicBoundingBox#add(GeographicBoundingBox)}.
     */
    @Test
    @DependsOnMethod("testNormalize")
    public void testAdd() {
        testOperation(true);
    }

    /**
     * Tests {@link DefaultGeographicBoundingBox#intersect(GeographicBoundingBox)}.
     */
    @Test
    @DependsOnMethod("testNormalize")
    public void testIntersect() {
        testOperation(false);
    }

    /**
     * Implementation of {@link #testAdd()} and {@link #testIntersect()}.
     *
     * @param union {@code true} for {@code b1.add(b2)}, or {@code false} for {@code b1.intersect(b2)}.
     */
    private void testOperation(final boolean union) {
        final DefaultGeographicBoundingBox b1 = new DefaultGeographicBoundingBox(NaN, 20, -20, NaN);
        final DefaultGeographicBoundingBox b2 = new DefaultGeographicBoundingBox(-20, 20, NaN,  20);
        assertFalse(isSpanningAntiMeridian(b1));
        assertFalse(isSpanningAntiMeridian(b2));
        assertOperationEquals(union, NaN, 20, NaN, NaN, b1, b2);
        /*
         *    ┌─────────────┐
         *    │  ┌───────┐  │
         *    │  └───────┘  │
         *    └─────────────┘
         */
        double λbgn, λend, φmin, φmax;
        b1.setBounds(-40, 30, -38,  20);
        b2.setBounds(-20, 10, -30, -25);
        assertFalse(isSpanningAntiMeridian(b1));
        assertFalse(isSpanningAntiMeridian(b2));
        if (union) {
            λbgn = -40; φmin = -38;
            λend =  30; φmax =  20;
        } else {
            λbgn = -20; φmin = -30;
            λend =  10; φmax = -25;
        }
        assertOperationEquals(union, λbgn, λend, φmin,  φmax, b1, b2);
        /*
         *    ┌──────────┐
         *    │  ┌───────┼──┐
         *    └──┼───────┘  │
         *       └──────────┘
         */
        b1.setBounds(-40, 30, -38,  20);
        b2.setBounds(-30, 50, -42, -20);
        assertFalse(isSpanningAntiMeridian(b1));
        assertFalse(isSpanningAntiMeridian(b2));
        if (union) {
            λbgn = -40; φmin = -42;
            λend =  50; φmax =  20;
        } else {
            λbgn = -30; φmin = -38;
            λend =  30; φmax = -20;
        }
        assertOperationEquals(union, λbgn, λend, φmin,  φmax, b1, b2);
        /*
         *   ┌─────────┐
         *   │         │  ┌─────┐
         *   │         │  └─────┘
         *   └─────────┘
         */
        b1.setBounds(-40, 30, -80, 40);
        b2.setBounds( 50, 80, -30, 20);
        assertFalse(isSpanningAntiMeridian(b1));
        assertFalse(isSpanningAntiMeridian(b2));
        if (union) {
            λbgn = -40; φmin = -80;
            λend =  80; φmax =  40;
        } else {
            λbgn = NaN; φmin = -30;
            λend = NaN; φmax =  20;
        }
        assertOperationEquals(union, λbgn, λend, φmin,  φmax, b1, b2);
        /*
         *   ──────────┐  ┌─────
         *     ┌────┐  │  │
         *     └────┘  │  │
         *   ──────────┘  └─────
         */
        b1.setBounds(  80, -100, -2, 2);
        b2.setBounds(-140, -120, -1, 1);
        assertTrue (isSpanningAntiMeridian(b1));
        assertFalse(isSpanningAntiMeridian(b2));
        if (union) {
            λbgn =   80; φmin = -2;
            λend = -100; φmax =  2;
        } else {
            λbgn = -140; φmin = -1;
            λend = -120; φmax =  1;
        }
        assertOperationEquals(union, λbgn, λend, φmin,  φmax, b1, b2);
        /*
         *    ─────┐      ┌─────
         *       ┌─┼────┐ │
         *       └─┼────┘ │
         *    ─────┘      └─────
         */
        b1.setBounds(  80, -100, -2, 2);
        b2.setBounds(-120,   50, -1, 1);
        assertTrue (isSpanningAntiMeridian(b1));
        assertFalse(isSpanningAntiMeridian(b2));
        if (union) {
            λbgn =   80;
            λend =   50;
        } else {
            λbgn = -120;
            λend = -100;
        }
        assertOperationEquals(union, λbgn, λend, φmin,  φmax, b1, b2);
        /*
         *    ────┐  ┌────
         *     ┌──┼──┼─┐
         *     └──┼──┼─┘
         *    ────┘  └────
         */
        b1.setBounds(  80, -100, -2, 2);
        b2.setBounds(-120,   90, -1, 1);
        assertTrue (isSpanningAntiMeridian(b1));
        assertFalse(isSpanningAntiMeridian(b2));
        if (union) {
            λbgn = -180;
            λend =  180;
        } else {
            // Intersection unchanged.
        }
        assertOperationEquals(union, λbgn, λend, φmin,  φmax, b1, b2);
        /*
         *    ────┐  ┌────
         *    ──┐ │  │ ┌──
         *    ──┘ │  │ └──
         *    ────┘  └────
         */
        b1.setBounds(80, -100, -1, 1);
        b2.setBounds(90, -120, -2, 2);
        assertTrue(isSpanningAntiMeridian(b1));
        assertTrue(isSpanningAntiMeridian(b2));
        if (union) {
            λbgn =   80;
            λend = -100;
        } else {
            λbgn =   90;
            λend = -120;
        }
        assertOperationEquals(union, λbgn, λend, φmin,  φmax, b1, b2);
        /*
         *    ────┐  ┌────
         *    ────┼──┼─┐┌─
         *    ────┼──┼─┘└─
         *    ────┘  └────
         */
        b1.setBounds( 80, -100, -2, 2);
        b2.setBounds(100,   90, -1, 1);
        assertTrue(isSpanningAntiMeridian(b1));
        assertTrue(isSpanningAntiMeridian(b2));
        if (union) {
            λbgn =  -180;
            λend =   180;
        } else {
            λbgn =  100;
            λend = -100;
        }
        assertOperationEquals(union, λbgn, λend, φmin,  φmax, b1, b2);
        /*
         *    ────┐          ┌────
         *        │  ┌────┐  │
         *        │  └────┘  │
         *    ────┘          └────
         */
        b1.setBounds(120, -110, -1, 1);
        b2.setBounds(100,  112, -2, 2);
        assertTrue (isSpanningAntiMeridian(b1));
        assertFalse(isSpanningAntiMeridian(b2));
        if (union) {
            λbgn =  100;
            λend = -110;
        } else {
            λbgn =  NaN;
            λend =  NaN;
        }
        assertOperationEquals(union, λbgn, λend, φmin,  φmax, b1, b2);
    }

    /**
     * Asserts that the result of applying the {@code add} or {@code intersect} operation on {@code b1}
     * is equals to the given values. This method tests also with horizontally flipped boxes, and tests
     * with interchanged boxes.
     *
     * @param union {@code true} for {@code b1.add(b2)}, or {@code false} for {@code b1.intersect(b2)}.
     */
    private static void assertOperationEquals(final boolean union,
            final double λbgn, final double λend,
            final double φmin, final double φmax,
            final DefaultGeographicBoundingBox b1,
            final DefaultGeographicBoundingBox b2)
    {
        final double westBoundLongitude = b1.getWestBoundLongitude();
        final double eastBoundLongitude = b1.getEastBoundLongitude();
        final double southBoundLatitude = b1.getSouthBoundLatitude();
        final double northBoundLatitude = b1.getNorthBoundLatitude();
        applyOperation(union, b1, b2);
        assertBoxEquals(λbgn, λend, φmin, φmax, b1);
        /*
         * The above tested the boxes as given in argument to this method. Now test again,
         * but with horizontally flipped boxes - so this is a mirror of above test. A test
         * failure here would mean that there is some asymmetry in the code.
         */
        flipHorizontally(b2);
        b1.setBounds(-eastBoundLongitude, -westBoundLongitude, southBoundLatitude, northBoundLatitude);
        applyOperation(union, b1, b2);
        assertBoxEquals(-λend, -λbgn, φmin, φmax, b1);
        /*
         * Reset the boxes to there initial state, then test again with the two boxes interchanged.
         * The consequence for the implementation is not as symetric than the above test, so there
         * is more risk of failure here.
         */
        flipHorizontally(b2);
        b1.setBounds(westBoundLongitude, eastBoundLongitude, southBoundLatitude, northBoundLatitude);
        applyOperation(union, b2, b1);
        assertBoxEquals(λbgn, λend, φmin, φmax, b2);
        /*
         * Following should be equivalent to b1.setBounds(b2), tested opportunistically.
         */
        applyOperation(union, b1, b2);
        assertBoxEquals(λbgn, λend, φmin, φmax, b1);
        assertEquals(b1, b2);
    }

    /**
     * Flips the given box horizontally. Longitudes are interchanged and their sign reversed.
     * Union and intersection tests what worked with the given boxes shall work as well with flipped boxes.
     */
    private static void flipHorizontally(final DefaultGeographicBoundingBox box) {
        box.setBounds(-box.getEastBoundLongitude(),
                      -box.getWestBoundLongitude(),
                       box.getSouthBoundLatitude(),
                       box.getNorthBoundLatitude());
    }

    /**
     * Applies the given operation on the given bounding boxes.
     * The operation is invoked on {@code b1}.
     *
     * @param union {@code true} for {@code b1.add(b2)}, or {@code false} for {@code b1.intersect(b2)}.
     */
    private static void applyOperation(final boolean union,
            final DefaultGeographicBoundingBox b1,
            final DefaultGeographicBoundingBox b2)
    {
        assertNotSame(b1, b2);
        if (union) {
            b1.add(b2);
        } else {
            b1.intersect(b2);
        }
    }

    /**
     * Tests {@link DefaultGeographicBoundingBox#asMap()}. The longitude and latitude values are
     * expected to be represented by {@link Longitude} and {@link Latitude} objects respectively.
     *
     * @since 0.5
     */
    @Test
    public void testAsMap() {
        final Map<String, Object> map = new DefaultGeographicBoundingBox(-40, 50, -20, 45).asMap();
        assertArrayEquals(new String[] {
            "westBoundLongitude",
            "eastBoundLongitude",
            "southBoundLatitude",
            "northBoundLatitude",
            "inclusion"
        }, map.keySet().toArray());
        assertArrayEquals(new Object[] {
            new Longitude(-40),
            new Longitude(+50),
            new Latitude (-20),
            new Latitude (+45),
            Boolean.TRUE
        }, map.values().toArray());
    }
}


text:
layout: post
title:  "Wang Tiles: Here is How to Use"
description: How I used Wang Tiles to compose Pixel Maze puzzle.
permalink: /wang-tiles-here-is-how-to-use
---

The first Pixel Maze prototypes were basically a grid of lines representing walls of a carved maze. When the experimentation phase was over, it was time to apply an art layer on top of the black and white maze to start looking like a real game. After some research, I discovered that Wang Tiles would be the preferred technique to make it happen.

| ![A carved maze prototype](/assets/images/posts/2020-03-16-wang-tiles-here-is-how-to-use/carved-maze-prototype.png) |
|:--:|
| *A carved maze prototype* |

## Wang Tiles

Wang tiles are a great model of maze composition. A set of square tiles, with each tile edge representing a wall, are arranged side by side in a rectangular grid. Every tile has two different types of edge: wall and without a wall. After carving a maze, the Wang Tiles model is used to apply the correct art sprite to a specific cell in the maze.

**Carved maze + Wang Tiles = Pixel Maze**

Below is an array representing a set of Wang tiles of all 16 possible combinations. The blue color means the wall, and the yellow one means the absence of a wall.

| ![Wang Tiles array](/assets/images/posts/2020-03-16-wang-tiles-here-is-how-to-use/wang-tiles-array.png) |
|:--:|
| *Wang Tiles array* - *Image source*|

To get a tile, an unique *index* in the array is calculated using bitwise operation. If there is a wall, add up using the following binary weighting:

- Wall North = 1
- Wall East = 2
- Wall South = 4
- Wall West = 8

For example, if a maze cell only contains a West and East walls, the array index will be 0 + 2 + 0 + 8 = 10.

| ![Wang Tile sprite](/assets/images/posts/2020-03-16-wang-tiles-here-is-how-to-use/wang-tiles-cell.png) |
|:--:|
| *Wang Tiles sprite* - *Image source*|

Using Wang tiles to compose a maze theme was great because I only had to draw 16 tiles per world. Also, applying the tiles to the carved maze is very performant due to the easy array index access for getting tiles - *time complexity O(1)*.

| ![Forest Wang Tiles](/assets/images/posts/2020-03-16-wang-tiles-here-is-how-to-use/forest-wang-tiles.png) |
|:--:|
| *Forest Wang Tiles* |

With the image above I created an array of tiles and used it to produce large Forest maze levels.

| ![Pixel Maze Forest level](/assets/images/posts/2020-03-16-wang-tiles-here-is-how-to-use/pixel-maze-forest.png) |
|:--:|
| *Pixel Maze Forest level* |

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Modified: 2020-05-26T22:10:14+00:00
 */
namespace Office365\Reports;

use Office365\Entity;
use Office365\Runtime\Actions\InvokeMethodQuery;
use Office365\Runtime\ClientResult;
use Office365\Runtime\Http\RequestOptions;

class ReportRoot extends Entity
{

    /**
     * @param $name string
     * @param $period string
     * @return ClientResult
     */
    private function addReportQuery($name,$period=null){
        $qry = new InvokeMethodQuery($this, $name);
        if(!is_null($period))
            $qry->MethodParameters = array("period" => $period);
        $this->getContext()->getPendingRequest()->beforeExecuteRequestOnce(function (RequestOptions $request){
            $request->FollowLocation = true;
        });
        $reportResult = new ClientResult($this->getContext(),new Report());
        $this->getContext()->addQueryAndResultObject($qry, $reportResult);
        return $reportResult;
    }

    /**
     * Get details about users who have activated Microsoft 365.
     * @return ClientResult
     */
    function getOffice365ActivationsUserDetail(){
        return $this->addReportQuery("getOffice365ActivationsUserDetail");
    }

    /**
     * Get the count of Microsoft 365 activations on desktops and devices.
     * @return ClientResult
     */
    function getOffice365ActivationCounts(){
        return $this->addReportQuery("getOffice365ActivationCounts");
    }

    /**
     * Get the count of users that are enabled and those that have activated the Office subscription on
     * desktop or devices or shared computers.
     * @return ClientResult
     */
    function getOffice365ActivationsUserCounts(){
        return $this->addReportQuery("getOffice365ActivationsUserCounts");
    }

    /**
     * Get details about Microsoft 365 active users.
     * @return ClientResult
     */
    function getOffice365ActiveUserDetail($period){
        return $this->addReportQuery("getOffice365ActiveUserDetail",$period);
    }

    /**
     * Get the count of daily active users in the reporting period by product.
     * @return ClientResult
     */
    function getOffice365ActiveUserCounts($period){
        return $this->addReportQuery("getOffice365ActiveUserCounts",$period);
    }

    /**
     * Get the count of users by activity type and service.
     * @return ClientResult
     */
    function getOffice365ServicesUserCounts($period){
        return $this->addReportQuery("getOffice365ServicesUserCounts",$period);
    }

    /**
     * Get details about Microsoft 365 groups activity by group.
     * @return ClientResult
     */
    function getOffice365GroupsActivityDetail($period){
        return $this->addReportQuery("getOffice365GroupsActivityDetail",$period);
    }

    /**
     * Get the number of group activities across group workloads.
     * @return ClientResult
     */
    function getOffice365GroupsActivityCounts($period){
        return $this->addReportQuery("getOffice365GroupsActivityCounts",$period);
    }

    /**
     * Get the daily total number of groups and how many of them were active based on email conversations,
     * Yammer posts, and SharePoint file activities.
     * @return ClientResult
     */
    function getOffice365GroupsActivityGroupCounts($period){
        return $this->addReportQuery("getOffice365GroupsActivityGroupCounts",$period);
    }

    /**
     * Get the total storage used across all group mailboxes and group sites.
     * @return ClientResult
     */
    function getOffice365GroupsActivityStorage($period){
        return $this->addReportQuery("getOffice365GroupsActivityStorage",$period);
    }

    /**
     * Get the total number of files and how many of them were active across all group sites associated with
     * a Microsoft 365 group.
     * @return ClientResult
     */
    function getOffice365GroupsActivityFileCounts($period){
        return $this->addReportQuery("getOffice365GroupsActivityFileCounts",$period);
    }

}


text:
ACCEPTED

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

#### Published in
Kew Gard. Report 1880:39. 1881

#### Original name
null

### Remarks
null


text:
package org.apache.hadoop.hbase.quotas;

import java.util.HashSet;
import java.util.Set;

import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;
import org.apache.hadoop.hbase.util.Strings;

/**
 * Filter to use to filter the QuotaRetriever results.
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class QuotaFilter {
  private Set<QuotaType> types = new HashSet<QuotaType>();
  private boolean hasFilters = false;
  private String namespaceRegex;
  private String tableRegex;
  private String userRegex;

  public QuotaFilter() {
  }

  /**
   * Set the user filter regex
   * @param regex the user filter
   * @return the quota filter object
   */
  public QuotaFilter setUserFilter(final String regex) {
    this.userRegex = regex;
    hasFilters |= !Strings.isEmpty(regex);
    return this;
  }

  /**
   * Set the table filter regex
   * @param regex the table filter
   * @return the quota filter object
   */
  public QuotaFilter setTableFilter(final String regex) {
    this.tableRegex = regex;
    hasFilters |= !Strings.isEmpty(regex);
    return this;
  }

  /**
   * Set the namespace filter regex
   * @param regex the namespace filter
   * @return the quota filter object
   */
  public QuotaFilter setNamespaceFilter(final String regex) {
    this.namespaceRegex = regex;
    hasFilters |= !Strings.isEmpty(regex);
    return this;
  }

  /**
   * Add a type to the filter list
   * @param type the type to filter on
   * @return the quota filter object
   */
  public QuotaFilter addTypeFilter(final QuotaType type) {
    this.types.add(type);
    hasFilters |= true;
    return this;
  }

  /** @return true if the filter is empty */
  public boolean isNull() {
    return !hasFilters;
  }

  /** @return the QuotaType types that we want to filter one */
  public Set<QuotaType> getTypeFilters() {
    return types;
  }

  /** @return the Namespace filter regex */
  public String getNamespaceFilter() {
    return namespaceRegex;
  }

  /** @return the Table filter regex */
  public String getTableFilter() {
    return tableRegex;
  }

  /** @return the User filter regex */
  public String getUserFilter() {
    return userRegex;
  }
}


text:
<?php declare(strict_types=1);

namespace Tale\Http;

use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface;
use function Tale\stream_null;
use function Tale\uri_factory;

final class Request extends AbstractRequest
{
    public static function create(
        string $method = self::METHOD_GET,
        $uri = '',
        array $headers = [],
        StreamInterface $body = null,
        UriFactoryInterface $uriFactory = null
    ): self {

        if (!($uri instanceof UriInterface) && !is_string($uri)) {
            throw new \InvalidArgumentException('Passed uri either needs to be UriInterface instance or string');
        }
        $uriFactory = $uriFactory ?? uri_factory();
        return new self($method, $uri instanceof UriInterface ? $uri : $uriFactory->createUri($uri), $body, $headers);
    }

    public static function createGet($uri = null, array $headers = [], UriFactoryInterface $uriFactory = null): self
    {
        return self::create(self::METHOD_GET, $uri, $headers, stream_null(), $uriFactory);
    }

    public static function createPost(
        $uri = '',
        array $headers = [],
        StreamInterface $body = null,
        UriFactoryInterface $uriFactory = null
    ): self {

        return self::create(self::METHOD_POST, $uri, $headers, $body, $uriFactory);
    }

    public static function createPut(
        $uri = '',
        array $headers = [],
        StreamInterface $body = null,
        UriFactoryInterface $uriFactory = null
    ): self {

        return self::create(self::METHOD_PUT, $uri, $headers, $body, $uriFactory);
    }

    public static function createDelete(
        $uri = '',
        array $headers = [],
        StreamInterface $body = null,
        UriFactoryInterface $uriFactory = null
    ): self {

        return self::create(self::METHOD_DELETE, $uri, $headers, $body, $uriFactory);
    }

    public static function createOptions($uri = '', array $headers = [], UriFactoryInterface $uriFactory = null): self
    {
        return self::create(self::METHOD_OPTIONS, $uri, $headers, stream_null(), $uriFactory);
    }
}


text:
<?php

/**
*
*/
require_once(APPPATH.'controllers/Check_Logged.php');
class Staff_Controller extends Check_Logged
{

	public function __construct()
	{
		parent::__construct();
		$this->load->helper('form');
		$this->load->helper('url');
		$this->load->library('form_validation');
		$this->load->model('Staff_Model');
		$this->load->model('Payroll_Model');
		$this->load->model('Attendence_Model');
	}
	 public function index()
	{
	 	$data['result'] = $this->Staff_Model->view_all();
	 	$this->load->view('admin/add_staff');

	 }

	 public function view_all()
	 {
	 	$result = $this->db->get('staffs');
		if ($result != FALSE)

		{
		if($result->num_rows() >=1)
		{
			return $result->result();
		}
		else
		{
			return FALSE;
		}
	}
	   else
	   {
	   	  return FALSE;
	   }
	 }

	public function view($id)
	{
		$where = [$id => 'id'];
		$data['id'] =$id;
		$data['result']=$this->Staff_Model->view_where(['departments_id' =>$id]);
		if ($data['result']!=FALSE)
	    {
			$this->load->view('admin/view_staffs',$data);
		}
		else
		{
			$data['message'] = 'No record found';
			$this->load->view('admin/view_staffs',$data);
		}
	}

	public function add()
	{
		$this->form_validation->set_rules('departments','Department','required');
		$this->form_validation->set_rules('name','Name');
		$this->form_validation->set_rules('address','Address');

		if($this->form_validation->run() === FALSE)
		{

			$this->load->view('admin/view_staffs');
		}
		else
		{

			$data=[
				'name' => $this->input->post('name'),
				'address' => $this->input->post('address') ,
				'departments_id' => $this->input->post('departments')
			];

			if ($this->Staff_Model->add($data) != FALSE)
			{

				$data['message'] = '<script type="text/javascript">
										alert("adding success");
										window.location = "'.base_url().('dashboard/staff').'"
									</script>';
				$this->load->view('admin/view_staffs',$data);
			}
			else
			{
				$data=['error' => 'insertion failed'];
			    $this->load->view('admin/view_staffs',$data);
			}

		}
	}
	public function delete($id)
		{

		if($this->Staff_Model->delete($id))
		{

			redirect($_SERVER['HTTP_REFERER']);
		}
		else
		{
			var_dump('fail');
		}

	    }

	    public function view_staff_details($id)
	    {
	    	$where=['id'=>$id];
	    	$result['staffs']=$this->Staff_Model->view($where);
	    	$result['payroll']=$this->Payroll_Model->view($id);
	    	$result['attendence']=$this->Attendence_Model->view($id);
	    	if($result != FALSE)
	    	{

	    		$this->load->view('admin/view_staff_details',$result);
	    	}
	    }

	}

?>


text:
#ifndef vnsw_agent_vn_hpp
#define vnsw_agent_vn_hpp

#include <cmn/agent_cmn.h>
#include <cmn/agent.h>
#include <oper/agent_types.h>
#include <oper/oper_db.h>
#include <oper/oper_dhcp_options.h>
#include <oper/agent_route_walker.h>

class AgentRouteResync;

namespace autogen {
    class NetworkIpam;
    class VirtualDns;
    struct IpamType;
    struct VirtualDnsType;
}

bool IsVRFServiceChainingInstance(const std::string &vn_name,
                                  const std::string &vrf_name);
class VmInterface;

struct VnIpam {
    IpAddress ip_prefix;
    uint32_t   plen;
    IpAddress default_gw;
    // In case of TSN, we could have different addresses for default_gw & dns
    IpAddress dns_server;
    bool       installed;    // is the route to send pkts to host installed
    bool       dhcp_enable;
    std::string ipam_name;
    OperDhcpOptions oper_dhcp_options;
    uint32_t alloc_unit;

    VnIpam(const std::string& ip, uint32_t len, const std::string& gw,
           const std::string& dns, bool dhcp, const std::string &name,
           const std::vector<autogen::DhcpOptionType> &dhcp_options,
           const std::vector<autogen::RouteType> &host_routes,
           uint32_t alloc);

    bool IsV4() const {
        return ip_prefix.is_v4();
    }
    bool IsV6() const {
        return ip_prefix.is_v6();
    }
    bool operator<(const VnIpam &rhs) const {
        if (ip_prefix != rhs.ip_prefix)
            return ip_prefix < rhs.ip_prefix;

        return (plen < rhs.plen);
    }
    Ip4Address GetBroadcastAddress() const;
    Ip4Address GetSubnetAddress() const;
    Ip6Address GetV6SubnetAddress() const;

    bool IsSubnetMember(const IpAddress &ip) const;
};

// Per IPAM data of the VN
struct VnIpamLinkData {
    OperDhcpOptions oper_dhcp_options_;

    bool operator==(const VnIpamLinkData &rhs) const {
        if (oper_dhcp_options_.host_routes() ==
            rhs.oper_dhcp_options_.host_routes())
            return true;
        return false;
    }
};

struct VnKey : public AgentOperDBKey {
    VnKey(const boost::uuids::uuid &id) : AgentOperDBKey(), uuid_(id) { }
    virtual ~VnKey() { }

    boost::uuids::uuid uuid_;
};

struct VnData : public AgentOperDBData {
    typedef std::map<std::string, VnIpamLinkData> VnIpamDataMap;
    typedef std::pair<std::string, VnIpamLinkData> VnIpamDataPair;

    VnData(const Agent *agent, IFMapNode *node, const string &name,
           const boost::uuids::uuid &acl_id, const string &vrf_name,
           const boost::uuids::uuid &mirror_acl_id,
           const boost::uuids::uuid &mc_acl_id, const std::vector<VnIpam> &ipam,
           const VnIpamDataMap &vn_ipam_data, int vxlan_id, int vnid,
           bool admin_state, bool enable_rpf, bool flood_unknown_unicast,
           Agent::ForwardingMode forwarding_mode,
           const boost::uuids::uuid &qos_config_uuid, bool mirror_destination,
           bool pbb_etree_enable, bool pbb_evpn_enable,
           bool layer2_control_word, UuidList slo_list,
           bool underlay_forwarding,
           bool vxlan_routing_vn,
           const boost::uuids::uuid &logical_router_uuid,
           bool cfg_igmp_enable, uint32_t vn_max_flows) :
        AgentOperDBData(agent, node), name_(name), vrf_name_(vrf_name),
        acl_id_(acl_id), mirror_acl_id_(mirror_acl_id),
        mirror_cfg_acl_id_(mc_acl_id), ipam_(ipam), vn_ipam_data_(vn_ipam_data),
        vxlan_id_(vxlan_id), vnid_(vnid), admin_state_(admin_state),
        enable_rpf_(enable_rpf), flood_unknown_unicast_(flood_unknown_unicast),
        forwarding_mode_(forwarding_mode), qos_config_uuid_(qos_config_uuid),
        mirror_destination_(mirror_destination),
        pbb_etree_enable_(pbb_etree_enable), pbb_evpn_enable_(pbb_evpn_enable),
        layer2_control_word_(layer2_control_word), slo_list_(slo_list),
        underlay_forwarding_(underlay_forwarding),
        vxlan_routing_vn_(vxlan_routing_vn),
        logical_router_uuid_(logical_router_uuid),
        cfg_igmp_enable_(cfg_igmp_enable),
        vn_max_flows_(vn_max_flows)  {
    };
    virtual ~VnData() { }

    string name_;
    string vrf_name_;
    boost::uuids::uuid acl_id_;
    boost::uuids::uuid mirror_acl_id_;
    boost::uuids::uuid mirror_cfg_acl_id_;
    std::vector<VnIpam> ipam_;
    VnIpamDataMap vn_ipam_data_;
    int vxlan_id_;
    int vnid_;
    bool admin_state_;
    bool enable_rpf_;
    bool flood_unknown_unicast_;
    Agent::ForwardingMode forwarding_mode_;
    boost::uuids::uuid qos_config_uuid_;
    bool mirror_destination_;
    bool pbb_etree_enable_;
    bool pbb_evpn_enable_;
    bool layer2_control_word_;
    UuidList slo_list_;
    bool underlay_forwarding_;
    bool vxlan_routing_vn_;
    boost::uuids::uuid logical_router_uuid_;
    bool cfg_igmp_enable_;
    uint32_t vn_max_flows_;
};

class VnEntry : AgentRefCount<VnEntry>, public AgentOperDBEntry {
public:
    VnEntry(Agent *agent, boost::uuids::uuid id);
    virtual ~VnEntry();

    virtual bool IsLess(const DBEntry &rhs) const;
    virtual KeyPtr GetDBRequestKey() const;
    virtual void SetKey(const DBRequestKey *key);
    virtual string ToString() const;

    const boost::uuids::uuid &GetUuid() const {return uuid_;};
    const string &GetName() const {return name_;};
    bool IsAclSet() const {
        return ((acl_.get() != NULL) || (mirror_acl_.get() != NULL) ||
                (mirror_cfg_acl_.get() != NULL));
    }
    const AclDBEntry *GetAcl() const {return acl_.get();}
    const AclDBEntry *GetMirrorAcl() const {return mirror_acl_.get();}
    const AclDBEntry *GetMirrorCfgAcl() const {return mirror_cfg_acl_.get();}
    VrfEntry *GetVrf() const {return vrf_.get();}
    const std::vector<VnIpam> &GetVnIpam() const { return ipam_; }
    const VnIpam *GetIpam(const IpAddress &ip) const;
    IpAddress GetGatewayFromIpam(const IpAddress &ip) const;
    IpAddress GetDnsFromIpam(const IpAddress &ip) const;
    uint32_t GetAllocUnitFromIpam(const IpAddress &ip) const;
    bool GetVnHostRoutes(const std::string &ipam,
                         std::vector<OperDhcpOptions::HostRoute> *routes) const;
    bool GetIpamName(const IpAddress &vm_addr, std::string *ipam_name) const;
    bool GetIpamData(const IpAddress &vm_addr, std::string *ipam_name,
                     autogen::IpamType *ipam_type) const;
    bool GetIpamVdnsData(const IpAddress &vm_addr,
                         autogen::IpamType *ipam_type,
                         autogen::VirtualDnsType *vdns_type) const;
    bool GetPrefix(const Ip6Address &ip, Ip6Address *prefix,
                   uint8_t *plen) const;
    std::string GetProject() const;
    int GetVxLanId() const;

    const VxLanId *vxlan_id_ref() const {return vxlan_id_ref_.get();}
    void set_bridging(bool bridging) {bridging_ = bridging;}
    bool bridging() const {return bridging_;};
    bool layer3_forwarding() const {return layer3_forwarding_;};
    void set_layer3_forwarding(bool layer3_forwarding)
    {layer3_forwarding_ = layer3_forwarding;}
    Agent::ForwardingMode forwarding_mode() const {return forwarding_mode_;}

    bool admin_state() const {return admin_state_;}
    bool enable_rpf() const {return enable_rpf_;}
    bool flood_unknown_unicast() const {return flood_unknown_unicast_;}

    const AgentQosConfig* qos_config() const {
        return qos_config_.get();
    }

    const bool mirror_destination() const {
        return mirror_destination_;
    }
    int vnid() const {return vnid_;}

    bool pbb_etree_enable() const {
        return pbb_etree_enable_;
    }

    bool pbb_evpn_enable() const {
        return pbb_evpn_enable_;
    }

    bool layer2_control_word() const {
        return layer2_control_word_;
    }

    const UuidList &slo_list() const {
        return slo_list_;
    }

    bool underlay_forwarding() const {
        return underlay_forwarding_;
    }

    bool cfg_igmp_enable() const {
        return cfg_igmp_enable_;
    }

    uint32_t GetRefCount() const {
        return AgentRefCount<VnEntry>::GetRefCount();
    }
    bool DBEntrySandesh(Sandesh *sresp, std::string &name) const;
    void SendObjectLog(AgentLogEvent::type event) const;
    bool IdentifyBgpRoutersServiceIp(const IpAddress &ip_address, bool *is_dns,
                                     bool *is_gateway) const;
    void AllocWalker();
    void ReleaseWalker();
    bool vxlan_routing_vn() const {return vxlan_routing_vn_;}
    const boost::uuids::uuid &logical_router_uuid() const {
        return logical_router_uuid_;
    }
    uint32_t vn_max_flows() const {return vn_max_flows_;}

private:
    friend class VnTable;
    bool Resync(Agent *agent);
    bool ChangeHandler(Agent *agent, const DBRequest *req);
    bool UpdateVxlan(Agent *agent, bool op_del);
    void ResyncRoutes();
    bool UpdateForwardingMode(Agent *agent);
    bool ApplyAllIpam(Agent *agent, VrfEntry *old_vrf, bool del);
    bool ApplyIpam(Agent *agent, VnIpam *ipam, VrfEntry *old_vrf, bool del);
    bool CanInstallIpam(const VnIpam *ipam);
    bool UpdateIpam(Agent *agent, std::vector<VnIpam> &new_ipam);
    bool HandleIpamChange(Agent *agent, VnIpam *old_ipam, VnIpam *new_ipam);
    void UpdateHostRoute(Agent *agent, const IpAddress &old_address,
                         const IpAddress &new_address, bool policy);
    bool AddIpamRoutes(Agent *agent, VnIpam *ipam);
    void DelIpamRoutes(Agent *agent, VnIpam *ipam, VrfEntry *vrf);
    void AddHostRoute(const IpAddress &address, bool policy);
    void DelHostRoute(const IpAddress &address);
    void AddSubnetRoute(VnIpam *ipam);
    void DelSubnetRoute(VnIpam *ipam);

    Agent *agent_;
    boost::uuids::uuid uuid_;
    string name_;
    AclDBEntryRef acl_;
    AclDBEntryRef mirror_acl_;
    AclDBEntryRef mirror_cfg_acl_;
    VrfEntryRef vrf_;
    std::vector<VnIpam> ipam_;
    VnData::VnIpamDataMap vn_ipam_data_;
    int vxlan_id_;
    int vnid_;
    // Based on vxlan-network-identifier mode, the active_vxlan_id_ is picked
    // from either vxlan_id_ or vnid_
    int active_vxlan_id_;
    bool bridging_;
    bool layer3_forwarding_;
    bool admin_state_;
    VxLanIdRef vxlan_id_ref_;
    uint32_t table_label_;
    bool enable_rpf_;
    bool flood_unknown_unicast_;
    Agent::ForwardingMode forwarding_mode_;
    AgentRouteWalkerPtr route_resync_walker_;
    AgentQosConfigConstRef qos_config_;
    bool mirror_destination_;
    bool pbb_etree_enable_;
    bool pbb_evpn_enable_;
    bool layer2_control_word_;
    UuidList slo_list_;
    bool underlay_forwarding_;
    bool vxlan_routing_vn_;
    boost::uuids::uuid logical_router_uuid_;
    bool cfg_igmp_enable_;
    uint32_t vn_max_flows_;
    DISALLOW_COPY_AND_ASSIGN(VnEntry);
};

class VnTable : public AgentOperDBTable {
public:
    VnTable(DB *db, const std::string &name);
    virtual ~VnTable();

    virtual std::auto_ptr<DBEntry> AllocEntry(const DBRequestKey *k) const;
    virtual size_t Hash(const DBEntry *entry) const {return 0;};
    virtual size_t  Hash(const DBRequestKey *key) const {return 0;};
    virtual AgentSandeshPtr GetAgentSandesh(const AgentSandeshArguments *args,
                                            const std::string &context);

    virtual DBEntry *OperDBAdd(const DBRequest *req);
    virtual bool OperDBOnChange(DBEntry *entry, const DBRequest *req);
    virtual bool OperDBDelete(DBEntry *entry, const DBRequest *req);
    virtual bool OperDBResync(DBEntry *entry, const DBRequest *req);

    virtual bool IFNodeToReq(IFMapNode *node, DBRequest &req,
            const boost::uuids::uuid &u);
    virtual bool IFNodeToUuid(IFMapNode *node, boost::uuids::uuid &u);
    virtual bool ProcessConfig(IFMapNode *node, DBRequest &req,
            const boost::uuids::uuid &u);
    virtual void Clear();

    int ComputeCfgVxlanId(IFMapNode *node);
    void CfgForwardingFlags(IFMapNode *node, bool *rpf,
                            bool *flood_unknown_unicast,
                            Agent::ForwardingMode *forwarding_mode,
                            bool *mirror_destination);

    static DBTableBase *CreateTable(DB *db, const std::string &name);
    static VnTable *GetInstance() {return vn_table_;};

    void AddVn(const boost::uuids::uuid &vn_uuid, const string &name,
               const boost::uuids::uuid &acl_id, const string &vrf_name,
               const std::vector<VnIpam> &ipam,
               const VnData::VnIpamDataMap &vn_ipam_data, int vn_id,
               int vxlan_id, bool admin_state, bool enable_rpf,
               bool flood_unknown_unicast, bool pbb_etree_enable,
               bool pbb_evpn_enable, bool layer2_control_word);
    void DelVn(const boost::uuids::uuid &vn_uuid);
    void ResyncReq(const boost::uuids::uuid &vn);
    VnEntry *Find(const boost::uuids::uuid &vn_uuid);
    void GlobalVrouterConfigChanged();
    bool VnEntryWalk(DBTablePartBase *partition, DBEntryBase *entry);
    void VnEntryWalkDone(DBTable::DBTableWalkRef walk_ref, DBTableBase *partition);
    int GetCfgVnId(autogen::VirtualNetwork *cfg_vn);

private:
    static VnTable *vn_table_;
    bool IsGwHostRouteRequired();
    bool IsGatewayL2(const string &gateway) const;
    void BuildVnIpamData(const std::vector<autogen::IpamSubnetType> &subnets,
                         const std::string &ipam_name,
                         std::vector<VnIpam> *vn_ipam);
    VnData *BuildData(IFMapNode *node);
    IFMapNode *FindTarget(IFMapAgentTable *table, IFMapNode *node,
                          std::string node_type);
    DBTable::DBTableWalkRef walk_ref_;

    DISALLOW_COPY_AND_ASSIGN(VnTable);
};

class OperNetworkIpam : public OperIFMapTable {
public:

    OperNetworkIpam(Agent *agent, DomainConfig *domain_config);
    virtual ~OperNetworkIpam();

    void ConfigDelete(IFMapNode *node);
    void ConfigAddChange(IFMapNode *node);
    void ConfigManagerEnqueue(IFMapNode *node);
private:
    DomainConfig *domain_config_;
    DISALLOW_COPY_AND_ASSIGN(OperNetworkIpam);
};

class OperVirtualDns : public OperIFMapTable {
public:

    OperVirtualDns(Agent *agent, DomainConfig *domain_config);
    virtual ~OperVirtualDns();

    void ConfigDelete(IFMapNode *node);
    void ConfigAddChange(IFMapNode *node);
    void ConfigManagerEnqueue(IFMapNode *node);
private:
    DomainConfig *domain_config_;
    DISALLOW_COPY_AND_ASSIGN(OperVirtualDns);
};

class DomainConfig {
public:
    typedef std::map<std::string, autogen::IpamType> IpamDomainConfigMap;
    typedef std::pair<std::string, autogen::IpamType> IpamDomainConfigPair;
    typedef std::map<std::string, autogen::VirtualDnsType> VdnsDomainConfigMap;
    typedef std::pair<std::string, autogen::VirtualDnsType> VdnsDomainConfigPair;
    typedef boost::function<void(IFMapNode *)> Callback;

    DomainConfig(Agent *);
    virtual ~DomainConfig();
    void Init();
    void Terminate();
    void RegisterIpamCb(Callback cb);
    void RegisterVdnsCb(Callback cb);
    void IpamDelete(IFMapNode *node);
    void IpamAddChange(IFMapNode *node);
    void VDnsDelete(IFMapNode *node);
    void VDnsAddChange(IFMapNode *node);
    bool GetIpam(const std::string &name, autogen::IpamType *ipam);
    bool GetVDns(const std::string &vdns, autogen::VirtualDnsType *vdns_type);

private:
    void CallVdnsCb(IFMapNode *node);
    void CallIpamCb(IFMapNode *node);
    bool IpamChanged(const autogen::IpamType &old,
                     const autogen::IpamType &cur) const;

    IpamDomainConfigMap ipam_config_;
    VdnsDomainConfigMap vdns_config_;
    std::vector<Callback> ipam_callback_;
    std::vector<Callback> vdns_callback_;

    DISALLOW_COPY_AND_ASSIGN(DomainConfig);
};

#endif // vnsw_agent_vn_hpp


text:
1. Copy OFCProbe.java and your configurations files to a directory
2. Copy On OFCProbe Host\ssh_redirector.sh to home dir of user openflow
3. Open ssh_redirector.sh and change the path in Line#3 to directory of 1. (and change config-file name in Line4)

##Preperations On OF Controller Host

1. Install Controller(s) according to their installation instructions
2. Copy Contents of On Controller Host to directory of your choosing on OF Controller Host
3. You will Find Folders for each Controller, For each Controller you want to operate, do the following:
  1. Go to Directory according to your Controller (e.g. Floodlight->>On Controller Host\flood)
  2. Open start.sh
  3. Change Directory in Line#2
4. Open launch_config.sh
5. Change IP(s) at the beginning


text:
package eu.smartenit.sbox.db.dao.binders;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.skife.jdbi.v2.SQLStatement;
import org.skife.jdbi.v2.sqlobject.Binder;
import org.skife.jdbi.v2.sqlobject.BinderFactory;
import org.skife.jdbi.v2.sqlobject.BindingAnnotation;

import eu.smartenit.sbox.db.dto.Link;
import eu.smartenit.sbox.db.dto.SimpleLinkID;

/**
 * The BindLink annotation. It maps the parameters of a sql statement in AbstractLinkDAO
 * into Link parameters.
 *
 * @authors George Petropoulos
 * @version 1.2
 *
 */
@BindingAnnotation(BindLink.LinkBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER })
public @interface BindLink {

	public static class LinkBinderFactory implements BinderFactory {

		public Binder build(Annotation annotation) {
			return new Binder<BindLink, Link>() {
				public void bind(SQLStatement q, BindLink bind, Link arg) {
					q.bind("localLinkID", ((SimpleLinkID) arg.getLinkID()).getLocalLinkID());
					q.bind("localIspName", ((SimpleLinkID) arg.getLinkID()).getLocalIspName());
					q.bind("physicalInterfaceName",
							arg.getPhysicalInterfaceName());
					q.bind("addressPrefix", arg.getAddress().getPrefix());
					q.bind("addressPrefixLength", arg.getAddress()
							.getPrefixLength());
					q.bind("vlan", arg.getVlan());
					q.bind("inboundInterfaceCounterOID", arg.getInboundInterfaceCounterOID());
					q.bind("outboundInterfaceCounterOID", arg.getOutboundInterfaceCounterOID());
					q.bind("bgRouterAddress", arg.getBgRouter().getManagementAddress().getPrefix());
					q.bind("tunnelEndPrefix", arg.getTunnelEndPrefix().getPrefix());
					q.bind("tunnelEndPrefixLength", arg.getTunnelEndPrefix().getPrefixLength());
					q.bind("policerBandwidthLimitFactor", arg.getPolicerBandwidthLimitFactor());
					q.bind("filterInterfaceName", arg.getFilterInterfaceName());
					q.bind("aggregateLeakageFactor", arg.getAggregateLeakageFactor());
				}
			};
		}
	}
}


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Forms.Repository
{
    public static class CommentsRepository
    {
        public static readonly ICollection<string> Comments = new Collection<string>();
    }
}


text:
import { inject, bindable, bindingMode } from 'aurelia-framework';
import { Config } from 'aurelia-api';

@inject(Element, Config)
export class UiAutocomplete {
    @bindable({defaultBindingMode: bindingMode.twoWay}) value;
    @bindable from;
    @bindable placeholder;
    @bindable searchParams = {};
    @bindable displayValue = 'name';
    @bindable storeValue = 'id';
    @bindable defaultText = '';
    @bindable multiple = false;
    @bindable autofill = false;

    constructor(element, config) {
        this.element = element;
        this.endpoint = config.getEndpoint('api');

        this.doQuery = (settings, callback) => {
            let path = `${this.from}/`;
            let params = this.searchParams;
            params.search = settings.urlData.query;
            this.endpoint.find(path, params).then(data => {
                callback(data);
            });
        }

        this.updateFromDropdown = (value, text, choice) => {
            this.value = value;
        }

        this.doAutoFill = () => {
            let path = `${this.from}/`;
            this.endpoint.find(path, this.searchParams).then(data => {
                if (data.results.length == 1) {
                    this.dropdown.dropdown('set text', data.results[0][this.displayValue]);
                    this.value = data.results[0][this.storeValue];
                }
            });
        }
    }

    defaultTextChanged(value) {
        if (this.dropdown) {
            this.dropdown.dropdown('set text', this.defaultText);
        }
    }

    searchParamsChanged(value) {
        if (this.autofill) {
            this.doAutoFill();
        }
    }

    attached() {
        setTimeout(() => {
            this.dropdown = $('.search.selection.dropdown', this.element).dropdown({
                apiSettings: {
                    responseAsync: this.doQuery,
                },
                fields: {
                    remoteValues: 'results',
                    name: this.displayValue,
                    value: this.storeValue,
                },
                onChange: this.updateFromDropdown,
                localSearch: false,
            });
            this.dropdown.dropdown('set text', this.defaultText);
        }, 1);
    }
}


text:
#include "pch.h"
#include "FpsTextRenderer.h"

#include "Common/DirectXHelper.h"

using namespace RTHR;
using namespace Microsoft::WRL;

// Initializes D2D resources used for text rendering.
SampleFpsTextRenderer::SampleFpsTextRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
	m_text(L""),
	m_deviceResources(deviceResources)
{
	ZeroMemory(&m_textMetrics, sizeof(DWRITE_TEXT_METRICS));

	// Create device independent resources
	ComPtr<IDWriteTextFormat> textFormat;
	DX::ThrowIfFailed(
		m_deviceResources->GetDWriteFactory()->CreateTextFormat(
			L"Segoe UI",
			nullptr,
			DWRITE_FONT_WEIGHT_LIGHT,
			DWRITE_FONT_STYLE_NORMAL,
			DWRITE_FONT_STRETCH_NORMAL,
			32.0f,
			L"en-US",
			&textFormat
			)
		);

	DX::ThrowIfFailed(
		textFormat.As(&m_textFormat)
		);

	DX::ThrowIfFailed(
		m_textFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR)
		);

	DX::ThrowIfFailed(
		m_deviceResources->GetD2DFactory()->CreateDrawingStateBlock(&m_stateBlock)
		);

	CreateDeviceDependentResources();
}

// Updates the text to be displayed.
void SampleFpsTextRenderer::Update(DX::StepTimer const& timer)
{
	// Update display text.
	uint32 fps = timer.GetFramesPerSecond();

	m_text = (fps > 0) ? std::to_wstring(fps) + L" FPS" : L" - FPS";

	ComPtr<IDWriteTextLayout> textLayout;
	DX::ThrowIfFailed(
		m_deviceResources->GetDWriteFactory()->CreateTextLayout(
			m_text.c_str(),
			(uint32) m_text.length(),
			m_textFormat.Get(),
			240.0f, // Max width of the input text.
			50.0f, // Max height of the input text.
			&textLayout
			)
		);

	DX::ThrowIfFailed(
		textLayout.As(&m_textLayout)
		);

	DX::ThrowIfFailed(
		m_textLayout->GetMetrics(&m_textMetrics)
		);
}

// Renders a frame to the screen.
void SampleFpsTextRenderer::Render()
{
	ID2D1DeviceContext* context = m_deviceResources->GetD2DDeviceContext();
	Windows::Foundation::Size logicalSize = m_deviceResources->GetLogicalSize();

	context->SaveDrawingState(m_stateBlock.Get());
	context->BeginDraw();

	// Position on the bottom right corner
	D2D1::Matrix3x2F screenTranslation = D2D1::Matrix3x2F::Translation(
		logicalSize.Width - m_textMetrics.layoutWidth,
		logicalSize.Height - m_textMetrics.height
		);

	context->SetTransform(screenTranslation * m_deviceResources->GetOrientationTransform2D());

	DX::ThrowIfFailed(
		m_textFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_TRAILING)
		);

	context->DrawTextLayout(
		D2D1::Point2F(0.f, 0.f),
		m_textLayout.Get(),
		m_whiteBrush.Get()
		);

	// Ignore D2DERR_RECREATE_TARGET here. This error indicates that the device
	// is lost. It will be handled during the next call to Present.
	HRESULT hr = context->EndDraw();
	if (hr != D2DERR_RECREATE_TARGET)
	{
		DX::ThrowIfFailed(hr);
	}

	context->RestoreDrawingState(m_stateBlock.Get());
}

void SampleFpsTextRenderer::CreateDeviceDependentResources()
{
	DX::ThrowIfFailed(
		m_deviceResources->GetD2DDeviceContext()->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &m_whiteBrush)
		);
}
void SampleFpsTextRenderer::ReleaseDeviceDependentResources()
{
	m_whiteBrush.Reset();
}


text:
package org.apache.fineract.mix.service;

import java.sql.Date;

import org.apache.fineract.mix.data.XBRLData;

public interface XBRLResultService {

    XBRLData getXBRLResult(Date startDate, Date endDate, String currency);

}


text:
    {% include navigation.html %}

            {% assign heroText = site.heroTitle | split:"<typeout>" %}

{{ heroText[0] }}{{ heroText[1] }}

{{ site.eventDate }}

            {% for button in site.heroButtons %}
            {{ button.text }}
            {% endfor %}

        <svg class="icon icon-arrow-down" viewBox="0 0 32 32">
            <use xlink:href="{{ site.baseurl }}/img/sprites/sprites.svg#icon-arrow-down"></use>
        </svg>


text:
package com.auth0.utils.tokens;

import com.auth0.exception.IdTokenValidationException;
import com.auth0.exception.PublicKeyProviderException;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.bouncycastle.util.io.pem.PemReader;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Scanner;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

public class SignatureVerifierTest {

    private static final String EXPIRED_HS_JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJub25jZSI6IjEyMzQiLCJpc3MiOiJodHRwczovL21lLmF1dGgwLmNvbS8iLCJhdWQiOiJkYU9nbkdzUlloa3d1NjIxdmYiLCJzdWIiOiJhdXRoMHx1c2VyMTIzIiwiZXhwIjo5NzE3ODkzMTd9.5_VOXBmOVMSi8OGgonyfyiJSq3A03PwOEuZlPD-Gxik";
    private static final String NONE_JWT = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJub25jZSI6IjEyMzQiLCJpc3MiOiJodHRwczovL21lLmF1dGgwLmNvbS8iLCJhdWQiOiJkYU9nbkdzUlloa3d1NjIxdmYiLCJzdWIiOiJhdXRoMHx1c2VyMTIzIn0.";
    private static final String HS_JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJub25jZSI6IjEyMzQiLCJpc3MiOiJodHRwczovL21lLmF1dGgwLmNvbS8iLCJhdWQiOiJkYU9nbkdzUlloa3d1NjIxdmYiLCJzdWIiOiJhdXRoMHx1c2VyMTIzIn0.a7ayNmFTxS2D-EIoUikoJ6dck7I8veWyxnje_mYD3qY";
    private static final String RS_JWT = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImFiYzEyMyJ9.eyJub25jZSI6IjEyMzQiLCJpc3MiOiJodHRwczovL21lLmF1dGgwLmNvbS8iLCJhdWQiOiJkYU9nbkdzUlloa3d1NjIxdmYiLCJzdWIiOiJhdXRoMHx1c2VyMTIzIn0.PkPWdoZNfXz8EB0SBPH83lNSOhyhdhdqYIgIwgY2nHozUnFOaUjVewlAXxP_3LBGibQ_ng4s5fEEOCJjaKBy04McryvOuL6nqb1dPQseeyxuv2zQitfrs-7kEtfeS3umywM-tV6guw9_W3nmIgaXOiYiF4WJM23ItbdCmvwdXLaf9-xHkQbRY_zEwEFbprFttKUXFbkPt6XjZ3zZwZbNZn64bx2PBiSJ2KMZAE3Lghmci-RXdhi7hXpmN30Tzze1ZsjvVeRRKNzShByKK9ZGZPmQ5yggJOXFy32ehjGkYwFMCqgMQomcGbcYhsd97huKHMHl3HOE5GDYjIq9o9oKRA";
    private static final String RS_PUBLIC_KEY = "src/test/resources/keys/public-rsa.pem";
    private static final String RS_PUBLIC_KEY_BAD = "src/test/resources/keys/bad-public-rsa.pem";

    @SuppressWarnings("deprecation")
    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void failsWhenAlgorithmIsNotExpected() {
        exception.expect(IdTokenValidationException.class);
        exception.expectMessage("Signature algorithm of \"none\" is not supported. Expected the ID token to be signed with \"HS256\"");
        exception.expectCause(isA(AlgorithmMismatchException.class));

        SignatureVerifier verifier = SignatureVerifier.forHS256("secret");
        verifier.verifySignature(NONE_JWT);
    }

    @Test
    public void failsWhenTokenCannotBeDecoded() {
        exception.expect(IdTokenValidationException.class);
        exception.expectMessage("ID token could not be decoded");

        SignatureVerifier verifier = SignatureVerifier.forHS256("secret");
        verifier.verifySignature("boom");
    }

    @Test
    public void failsWhenAlgorithmRS256IsNotExpected() {
        exception.expect(IdTokenValidationException.class);
        exception.expectMessage("Signature algorithm of \"RS256\" is not supported. Expected the ID token to be signed with \"HS256\"");
        exception.expectCause(isA(AlgorithmMismatchException.class));

        SignatureVerifier verifier = SignatureVerifier.forHS256("secret");
        verifier.verifySignature(RS_JWT);
    }

    @Test
    public void failsWhenAlgorithmHS256IsNotExpected() throws Exception {
        exception.expect(IdTokenValidationException.class);
        exception.expectMessage("Signature algorithm of \"HS256\" is not supported. Expected the ID token to be signed with \"RS256\"");
        exception.expectCause(isA(AlgorithmMismatchException.class));

        SignatureVerifier verifier = SignatureVerifier.forRS256(getRSProvider(RS_PUBLIC_KEY));

        verifier.verifySignature(HS_JWT);
    }

    @Test
    public void succeedsWithValidSignatureHS256Token() {
        SignatureVerifier verifier = SignatureVerifier.forHS256("secret");
        DecodedJWT decodedJWT = verifier.verifySignature(HS_JWT);

        assertThat(decodedJWT, notNullValue());
    }

    @Test
    public void succeedsAndIgnoresExpiredTokenException() {
        SignatureVerifier verifier = SignatureVerifier.forHS256("secret");
        DecodedJWT decodedJWT = verifier.verifySignature(EXPIRED_HS_JWT);

        assertThat(decodedJWT, notNullValue());
    }

    @Test
    public void failsWithInvalidSignatureHS256Token() {
        exception.expect(IdTokenValidationException.class);
        exception.expectMessage("Invalid ID token signature");

        SignatureVerifier verifier = SignatureVerifier.forHS256("badsecret");
        verifier.verifySignature(HS_JWT);
    }

    @Test
    public void succeedsWithValidSignatureRS256Token() throws Exception {
        SignatureVerifier verifier = SignatureVerifier.forRS256(getRSProvider(RS_PUBLIC_KEY));
        DecodedJWT decodedJWT = verifier.verifySignature(RS_JWT);

        assertThat(decodedJWT, notNullValue());
    }

    @Test
    public void failsWithInvalidSignatureRS256Token() throws Exception {
        exception.expect(IdTokenValidationException.class);
        exception.expectMessage("Invalid ID token signature");
        SignatureVerifier verifier = SignatureVerifier.forRS256(getRSProvider(RS_PUBLIC_KEY_BAD));
        DecodedJWT decodedJWT = verifier.verifySignature(RS_JWT);

        assertThat(decodedJWT, notNullValue());
    }

    @Test
    public void failsWhenErrorGettingPublicKey() {
        exception.expect(IdTokenValidationException.class);
        exception.expectCause(isA(PublicKeyProviderException.class));
        exception.expectMessage("Could not find a public key for Key ID (kid) \"abc123\"");

        SignatureVerifier verifier = SignatureVerifier.forRS256(new PublicKeyProvider() {
            @Override
            public RSAPublicKey getPublicKeyById(String keyId) throws PublicKeyProviderException {
                throw new PublicKeyProviderException("error");
            }
        });
        verifier.verifySignature(RS_JWT);
    }

    @Test
    public void failsWithNullVerifier() {
        exception.expect(IllegalArgumentException.class);
        exception.expectMessage("'algorithm' cannot be null");
        new NullVerifier();
    }

    private PublicKeyProvider getRSProvider(String rsaPath) {
        return new PublicKeyProvider() {
            @Override
            public RSAPublicKey getPublicKeyById(String keyId) throws PublicKeyProviderException {
                try {
                    return readPublicKeyFromFile(rsaPath);
                } catch (IOException ioe) {
                    throw new PublicKeyProviderException("Error reading public key", ioe);
                }
            }
        };
    }

    private static RSAPublicKey readPublicKeyFromFile(final String path) throws IOException {
        Scanner scanner = null;
        PemReader pemReader = null;
        try {
            scanner = new Scanner(Paths.get(path));
            if (scanner.hasNextLine() && scanner.nextLine().startsWith("-----BEGIN CERTIFICATE-----")) {
                FileInputStream fs = new FileInputStream(path);
                CertificateFactory fact = CertificateFactory.getInstance("X.509");
                X509Certificate cer = (X509Certificate) fact.generateCertificate(fs);
                PublicKey key = cer.getPublicKey();
                fs.close();
                return (RSAPublicKey) key;
            } else {
                pemReader = new PemReader(new FileReader(path));
                byte[] keyBytes = pemReader.readPemObject().getContent();
                KeyFactory kf = KeyFactory.getInstance("RSA");
                EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
                return (RSAPublicKey) kf.generatePublic(keySpec);
            }
        } catch (Exception e) {
            throw new IOException("Couldn't parse the RSA Public Key / Certificate file.", e);
        } finally {
            if (scanner != null) {
                scanner.close();
            }
            if (pemReader != null) {
                pemReader.close();
            }
        }
    }

    private static class NullVerifier extends SignatureVerifier {
        NullVerifier() {
            super(null);
        }
    }
}


text:
package org.inventivetalent.npclib.entity.living.insentient.creature.monster;

import org.inventivetalent.npclib.entity.living.insentient.EntityZombie;

public interface EntityHusk extends EntityZombie {
}


text:
<?php

namespace PHP\Wrappers;

/**
 * Class Pcntl
 *
 * @package PHP\Wrappers
 * @author  Aurimas Niekis <aurimas@niekis.lt>
 */
class Pcntl
{
    /**
     * Set an alarm clock for delivery of a signal
     *
     * @param int $seconds The number of seconds to wait. If seconds is
     *                     zero, no new alarm is created.
     *
     * @return int
     */
    public function alarm(int $seconds) : int
    {
        return pcntl_alarm($seconds);
    }

    /**
     * Executes specified program in current process space
     *
     * @param string $path path must be the path to a binary executable or a
     *                     script with a valid path pointing to an executable in the shebang (
     *                     #!/usr/local/bin/perl for example) as the first line.  See your system's
     *                     man execve(2) page for additional information.
     * @param array  $args args is an array of argument strings passed to the
     *                     program.
     * @param array  $envs envs is an array of strings which are passed as
     *                     environment to the program.  The array is in the format of name => value,
     *                     the key being the name of the environmental variable and the value being
     *                     the value of that variable.
     *
     * @return bool
     */
    public function exec(string $path, array $args = null, array $envs = null) : bool
    {
        return call_user_func_array('pcntl_exec', func_get_args());
    }

    /**
     * Forks the currently running process
     *
     * @return int
     */
    public function fork() : int
    {
        return pcntl_fork();
    }

    /**
     * Retrieve the error number set by the last pcntl function which failed
     *
     * @return int
     */
    public function getLastError() : int
    {
        return pcntl_get_last_error();
    }

    /**
     * Get the priority of any process
     *
     * @param int $pid               If not specified, the pid of the current process is used.
     * @param int $processIdentifier One of PRIO_PGRP, PRIO_USER
     *                               or PRIO_PROCESS.
     *
     * @return int
     */
    public function getPriority(int $pid = null, int $processIdentifier = null) : int
    {
        return call_user_func_array('pcntl_getpriority', func_get_args());
    }

    /**
     * Change the priority of any process
     *
     * @param int $priority          priority is generally a value in the range
     *                               -20 to 20. The default priority
     *                               is 0 while a lower numerical value causes more
     *                               favorable scheduling.  Because priority levels can differ between
     *                               system types and kernel versions, please see your system's setpriority(2)
     *                               man page for specific details.
     * @param int $pid               If not specified, the pid of the current process is used.
     * @param int $processIdentifier One of PRIO_PGRP, PRIO_USER
     *                               or PRIO_PROCESS.
     *
     * @return bool
     */
    public function setPriority(int $priority, int $pid = null, int $processIdentifier = null) : bool
    {
        return call_user_func_array('pcntl_setpriority', func_get_args());
    }

    /**
     * Calls signal handlers for pending signals
     *
     * @return bool
     */
    public function signalDispatch() : bool
    {
        return pcntl_signal_dispatch();
    }

    /**
     * Installs a signal handler
     *
     * @param int          $signo           The signal number.
     * @param callable|int $handler         The signal handler. This may be either a callable, which
     *                                      will be invoked to handle the signal, or either of the two global
     *                                      constants SIG_IGN or SIG_DFL,
     *                                      which will ignore the signal or restore the default signal handler
     *                                      respectively.
     * @param bool         $restartSyscalls Specifies whether system call restarting should be used when this
     *                                      signal arrives.
     *
     * @return bool
     */
    public function signal(int $signo, $handler, bool $restartSyscalls = null) : bool
    {
        return call_user_func_array('pcntl_signal', func_get_args());
    }

    /**
     * Sets and retrieves blocked signals
     *
     * @param int   $how    Sets the behavior of pcntl_sigprocmask. Possible
     *                      values:
     *
     * SIG_BLOCK: Add the signals to the
     * currently blocked signals.
     * SIG_UNBLOCK: Remove the signals from the
     * currently blocked signals.
     * SIG_SETMASK: Replace the currently
     * blocked signals by the given list of signals.
     * @param array $set    List of signals.
     * @param array $oldset The oldset parameter is set to an array
     *                      containing the list of the previously blocked signals.
     *
     * @return bool
     */
    public function sigprocmask(int $how, array $set, array &$oldset = null) : bool
    {
        return call_user_func_array('pcntl_sigprocmask', func_get_args());
    }

    /**
     * Waits for signals, with a timeout
     *
     * @param array $set         Array of signals to wait for.
     * @param array $siginfo     The siginfo is set to an array containing
     *                           informations about the signal. See
     *                           pcntl_sigwaitinfo.
     * @param int   $seconds     Timeout in seconds.
     * @param int   $nanoseconds Timeout in nanoseconds.
     *
     * @return int
     */
    public function sigtimedwait(array $set, array &$siginfo = null, int $seconds = null, int $nanoseconds = null) : int
    {
        return call_user_func_array('pcntl_sigtimedwait', func_get_args());
    }

    /**
     * Waits for signals
     *
     * @param array $set     Array of signals to wait for.
     * @param array $siginfo The siginfo parameter is set to an array containing
     *                       informations about the signal.
     *
     * @return int
     */
    public function sigwaitinfo(array $set, array &$siginfo = null) : int
    {
        return call_user_func_array('pcntl_sigwaitinfo', func_get_args());
    }

    /**
     * Retrieve the system error message associated with the given errno
     *
     * @param int $errno
     *
     * @return string
     */
    public function strerror(int $errno) : string
    {
        return pcntl_strerror($errno);
    }

    /**
     * Waits on or returns the status of a forked child
     *
     * @param int $status  pcntl_wait will store status information
     *                     in the status parameter which can be
     *                     evaluated using the following functions:
     *                     pcntl_wifexited,
     *                     pcntl_wifstopped,
     *                     pcntl_wifsignaled,
     *                     pcntl_wexitstatus,
     *                     pcntl_wtermsig and
     *                     pcntl_wstopsig.
     * @param int $options If wait3 is available on your system (mostly BSD-style systems), you can
     *                     provide the optional options parameter.  If this
     *                     parameter is not provided, wait will be used for the system call.  If
     *                     wait3 is not available, providing a value for options
     *                     will have no effect. The value of options
     *                     is the value of zero or more of the following two constants
     *                     OR'ed together:
     *
     * Possible values for options
     *
     *
     *
     * WNOHANG
     *
     * Return immediately if no child has exited.
     *
     *
     *
     * WUNTRACED
     *
     * Return for children which are stopped, and whose status has
     * not been reported.
     *
     * @return int
     */
    public function wait(int &$status, int $options = null) : int
    {
        return call_user_func_array('pcntl_wait', func_get_args());
    }

    /**
     * Waits on or returns the status of a forked child
     *
     * @param int $pid     The value of pid can be one of the following:
     *
     * possible values for pid
     *
     *
     *
     * -1
     *
     * wait for any child process whose process group ID is equal to
     * the absolute value of pid.
     *
     *
     *
     * -1
     *
     * wait for any child process; this is the same behaviour that
     * the wait function exhibits.
     *
     *
     *
     * 0
     *
     * wait for any child process whose process group ID is equal to
     * that of the calling process.
     *
     *
     *
     * 0
     *
     * wait for the child whose process ID is equal to the value of
     * pid.
     * @param int $status  pcntl_waitpid will store status information
     *                     in the status parameter which can be
     *                     evaluated using the following functions:
     *                     pcntl_wifexited,
     *                     pcntl_wifstopped,
     *                     pcntl_wifsignaled,
     *                     pcntl_wexitstatus,
     *                     pcntl_wtermsig and
     *                     pcntl_wstopsig.
     * @param int $options The value of options is the value of zero
     *                     or more of the following two global constants
     *                     OR'ed together:
     *
     * possible values for options
     *
     *
     *
     * WNOHANG
     *
     * return immediately if no child has exited.
     *
     *
     *
     * WUNTRACED
     *
     * return for children which are stopped, and whose status has
     * not been reported.
     *
     * @return int
     */
    public function waitpid(int $pid, int &$status, int $options = null) : int
    {
        return call_user_func_array('pcntl_waitpid', func_get_args());
    }

    /**
     * Returns the return code of a terminated child
     *
     * @param int $status
     *
     * @return int
     */
    public function wexitstatus(int $status) : int
    {
        return pcntl_wexitstatus($status);
    }

    /**
     * Checks if status code represents a normal exit
     *
     * @param int $status
     *
     * @return bool
     */
    public function wifexited(int $status) : bool
    {
        return pcntl_wifexited($status);
    }

    /**
     * Checks whether the status code represents a termination due to a signal
     *
     * @param int $status
     *
     * @return bool
     */
    public function wifsignaled(int $status) : bool
    {
        return pcntl_wifsignaled($status);
    }

    /**
     * Checks whether the child process is currently stopped
     *
     * @param int $status
     *
     * @return bool
     */
    public function wifstopped(int $status) : bool
    {
        return pcntl_wifstopped($status);
    }

    /**
     * Returns the signal which caused the child to stop
     *
     * @param int $status
     *
     * @return int
     */
    public function wstopsig(int $status) : int
    {
        return pcntl_wstopsig($status);
    }

    /**
     * Returns the signal which caused the child to terminate
     *
     * @param int $status
     *
     * @return int
     */
    public function wtermsig(int $status) : int
    {
        return pcntl_wtermsig($status);
    }

}


text:
describe("IpsumMonitorFormController", function() {
  var controller, scope, eventListener;

  beforeEach(function() {
    scope = {
      $on: jasmine.createSpy("scope.$on").and.callFake(function(eventName, handler) {
        eventListener = handler;
      })
    };

    controller = new jashboard.plugin.ipsum.IpsumMonitorFormController(scope);
  });

  it("should put in the scope the different languages", function() {
    expect(scope.availableLanguages).toEqual(["english", "french", "latin"]);
  });
  it("should listen to the 'OpenMonitorDialog' event", function() {
    expect(scope.$on).toHaveBeenCalledWith("OpenMonitorDialog", jasmine.any(Function));
  });

  describe("'OpenMonitorDialog' event listener", function() {
    beforeEach(function() {
      scope.monitorConfigurationFormModel = {};
      scope.ipsumMonitorForm = "ipsumMonitorForm";
      scope.formHelper = jasmine.createSpyObj("formHelper", ['registerMonitorTypeForm']);
    });

    it("should register the ipsumMonitorForm to the formHelper", function() {
      eventListener({}, {});

      expect(scope.formHelper.registerMonitorTypeForm).toHaveBeenCalledWith("ipsum", "ipsumMonitorForm");
    });
    it("should reset the variables in the scope", function() {
      eventListener({}, {
        mode: jashboard.model.inputOptions.createMode,
      });

      expect(scope.monitorConfigurationFormModel.ipsum).toEqual({
        language: "english",
        numberOfSentences: 1
      });
    });
  });
});


text:
Sequel.migration do
  up do

    run 'DROP VIEW public.full_temporary_stop_regulations;'

    alter_table :full_temporary_stop_regulations_oplog do
      add_column :complete_abrogation_regulation_role, Integer
      add_column :complete_abrogation_regulation_id, String, size: 8
    end

    run %Q{
CREATE VIEW public.full_temporary_stop_regulations AS
 SELECT full_temporary_stop_regulations1.full_temporary_stop_regulation_role,
    full_temporary_stop_regulations1.full_temporary_stop_regulation_id,
    full_temporary_stop_regulations1.published_date,
    full_temporary_stop_regulations1.officialjournal_number,
    full_temporary_stop_regulations1.officialjournal_page,
    full_temporary_stop_regulations1.validity_start_date,
    full_temporary_stop_regulations1.validity_end_date,
    full_temporary_stop_regulations1.effective_enddate,
    full_temporary_stop_regulations1.explicit_abrogation_regulation_role,
    full_temporary_stop_regulations1.explicit_abrogation_regulation_id,
    full_temporary_stop_regulations1.replacement_indicator,
    full_temporary_stop_regulations1.information_text,
    full_temporary_stop_regulations1.approved_flag,
    full_temporary_stop_regulations1.complete_abrogation_regulation_id,
    full_temporary_stop_regulations1.complete_abrogation_regulation_role,
    full_temporary_stop_regulations1.oid,
    full_temporary_stop_regulations1.operation,
    full_temporary_stop_regulations1.operation_date
   FROM public.full_temporary_stop_regulations_oplog full_temporary_stop_regulations1
  WHERE ((full_temporary_stop_regulations1.oid IN ( SELECT max(full_temporary_stop_regulations2.oid) AS max
           FROM public.full_temporary_stop_regulations_oplog full_temporary_stop_regulations2
          WHERE (((full_temporary_stop_regulations1.full_temporary_stop_regulation_id)::text = (full_temporary_stop_regulations2.full_temporary_stop_regulation_id)::text) AND (full_temporary_stop_regulations1.full_temporary_stop_regulation_role = full_temporary_stop_regulations2.full_temporary_stop_regulation_role)))) AND ((full_temporary_stop_regulations1.operation)::text <> 'D'::text));
    }

  end

  down do

    run 'DROP VIEW public.full_temporary_stop_regulations;'

    alter_table :full_temporary_stop_regulations_oplog do
      drop_column :complete_abrogation_regulation_id
      drop_column :complete_abrogation_regulation_role
    end

    run %Q{
CREATE VIEW public.full_temporary_stop_regulations AS
 SELECT full_temporary_stop_regulations1.full_temporary_stop_regulation_role,
    full_temporary_stop_regulations1.full_temporary_stop_regulation_id,
    full_temporary_stop_regulations1.published_date,
    full_temporary_stop_regulations1.officialjournal_number,
    full_temporary_stop_regulations1.officialjournal_page,
    full_temporary_stop_regulations1.validity_start_date,
    full_temporary_stop_regulations1.validity_end_date,
    full_temporary_stop_regulations1.effective_enddate,
    full_temporary_stop_regulations1.explicit_abrogation_regulation_role,
    full_temporary_stop_regulations1.explicit_abrogation_regulation_id,
    full_temporary_stop_regulations1.replacement_indicator,
    full_temporary_stop_regulations1.information_text,
    full_temporary_stop_regulations1.approved_flag,
    full_temporary_stop_regulations1.oid,
    full_temporary_stop_regulations1.operation,
    full_temporary_stop_regulations1.operation_date
   FROM public.full_temporary_stop_regulations_oplog full_temporary_stop_regulations1
  WHERE ((full_temporary_stop_regulations1.oid IN ( SELECT max(full_temporary_stop_regulations2.oid) AS max
           FROM public.full_temporary_stop_regulations_oplog full_temporary_stop_regulations2
          WHERE (((full_temporary_stop_regulations1.full_temporary_stop_regulation_id)::text = (full_temporary_stop_regulations2.full_temporary_stop_regulation_id)::text) AND (full_temporary_stop_regulations1.full_temporary_stop_regulation_role = full_temporary_stop_regulations2.full_temporary_stop_regulation_role)))) AND ((full_temporary_stop_regulations1.operation)::text <> 'D'::text));
    }

  end
end


text:
"use strict";
var clickers_1 = require('./clickers');
var CLICKER_IDS = ['yy5d8klsj0', 'q20iexxg4a', 'wao2xajl8a'];
var clickers = null;
function storageGetStub(key) {
    'use strict';
    var rtn = null;
    switch (key) {
        case 'ids':
            rtn = JSON.stringify(CLICKER_IDS);
            break;
        case CLICKER_IDS[0]:
            rtn = '{"id":"' + CLICKER_IDS[0] + '","name":"test1","clicks":[{"time":1450410168819,"location":"TODO"}]}';
            break;
        case CLICKER_IDS[1]:
            rtn = '{"id":"' + CLICKER_IDS[1] + '","name":"test2","clicks":[{"time":1450410168819,"location":"TODO"},{"time":1450410168945,"location":"TODO"}]}';
            break;
        case CLICKER_IDS[2]:
            rtn = '{"id":"' + CLICKER_IDS[2] + '", "name":"test3", "clicks":[{ "time": 1450410168819, "location": "TODO" }, { "time": 1450410168945, "location": "TODO" }] } ';
            break;
        default:
            rtn = 'SHOULD NOT BE HERE!';
    }
    return new Promise(function (resolve) {
        resolve(rtn);
    });
}
function storageSetStub(key, value) {
    'use strict';
    return new Promise(function (resolve) {
        resolve(true);
    });
}
function storageRemoveStub(key) {
    'use strict';
    return new Promise(function (resolve) {
        resolve(true);
    });
}
var mockSqlStorage = {
    get: storageGetStub,
    set: storageSetStub,
    remove: storageRemoveStub,
};
function main() {
    'use strict';
    describe('Clickers', function () {
        beforeEach(function () {
            spyOn(clickers_1.Clickers, 'initStorage').and.returnValue(mockSqlStorage);
            clickers = new clickers_1.Clickers();
            spyOn(clickers['storage'], 'set');
        });
        it('initialises with empty clickers', function () {
            expect(clickers.getClickers()).toEqual([]);
        });
        it('creates an instance of SqlStorage', function () {
            expect(clickers_1.Clickers.initStorage()).toEqual(mockSqlStorage);
        });
        it('has empty ids with no storage', function (done) {
            clickers.initIds()
                .then(function () {
                expect(clickers.getClickers()).toEqual([]);
                done();
            });
        });
        it('has empty clickers with no storage', function (done) {
            clickers.initClickers([])
                .then(function () {
                expect(clickers.getClickers()).toEqual([]);
                done();
            });
        });
        it('can initialise a clicker from string', function () {
            var clickerString = '{"id":"0g2vt8qtlm","name":"harold","clicks":[{"time":1450410168819,"location":"TODO"},{"time":1450410168945,"location":"TODO"}]}';
            var clicker = clickers.initClicker(clickerString);
            expect(clicker.getName()).toEqual('harold');
            expect(clicker.getCount()).toEqual(2);
        });
        it('returns undefined for a bad id', function () {
            expect(clickers.getClicker('dave')).not.toBeDefined();
        });
        it('adds a new clicker with the correct name', function () {
            var idAdded = clickers.newClicker('dave');
            expect(clickers['storage'].set).toHaveBeenCalledWith(idAdded, jasmine.any(String));
            expect(clickers.getClickers()[0].getName()).toEqual('dave');
        });
        it('removes a clicker by id', function () {
            var idToRemove = clickers.newClicker('dave');
            clickers.removeClicker(idToRemove);
            expect(clickers['storage'].set).toHaveBeenCalledWith(idToRemove, jasmine.any(String));
            expect(clickers.getClickers()).toEqual([]);
        });
        it('does a click', function () {
            var idToClick = clickers.newClicker('dave');
            var clickedClicker = null;
            clickers.doClick(idToClick);
            expect(clickers['storage'].set).toHaveBeenCalledWith(idToClick, jasmine.any(String));
            clickedClicker = clickers.getClicker(idToClick);
            expect(clickedClicker.getCount()).toEqual(1);
        });
        it('loads IDs from storage', function (done) {
            clickers.initIds()
                .then(function (ids) {
                expect(ids).toEqual(CLICKER_IDS);
                done();
            });
        });
        it('loads clickers from storage', function (done) {
            clickers.initClickers(CLICKER_IDS)
                .then(function (resolvedClickers) {
                expect(resolvedClickers.length).toEqual(3);
                expect(resolvedClickers[0].getId()).toEqual(CLICKER_IDS[0]);
                expect(resolvedClickers[1].getId()).toEqual(CLICKER_IDS[1]);
                expect(resolvedClickers[2].getId()).toEqual(CLICKER_IDS[2]);
                done();
            });
        });
    });
}
exports.main = main;
;


text:
package com.spotify.apollo.serialization;

import com.spotify.apollo.Request;
import com.spotify.apollo.Payloads;
import com.spotify.apollo.Serializer;
import com.spotify.apollo.route.Middleware;

import okio.ByteString;

/**
 * @deprecated the new preferred way to do response serialization is via a {@link Middleware},
 * see {@link Serializer}.
 */
@Deprecated
public class StringSerializer implements Serializer {

  @Override
  public Payload serialize(Request request, Object t) {
    return Payloads.create(serialize(t));
  }

  public static ByteString serialize(Object s) {
    return ByteString.encodeUtf8(s != null ? s.toString() : "null");
  }
}


text:
require('./buffer')

exports.fix_child_process = require('./child_process').fix_child_process


text:
<?php namespace BarcodeGenerator\Directory;

	use \FilesystemIterator; # SPL FilesystemIterator Class

	/**
	*
	* @author Avinash Rai
	*/
	class Directory {

		private $_path;

		private $_files;

		const FETCH_URI = 0;

		const FETCH_URL = 1;

		/**
		 * Create a new Directory instance.
		 */
		function __construct() {
			$this->_path = CACHE_URI . $_SERVER['REMOTE_ADDR'];
			if ( !file_exists($this->_path)) {
				mkdir($this->_path, 0777, true);
			}
			$this->_files = [];
			$iterator = new FilesystemIterator($this->_path, FilesystemIterator::SKIP_DOTS);
			if ($iterator->valid()) {
				foreach ($iterator as $file) {
					if ($file->isFile() && ($file->getExtension() == 'jpg')) {
						$this->_files[$file->getBasename('.jpg')] = array( 'path' => $file->getFilename(), 'modified_time' => $file->getMTime() );
					}
				}
			}
		}

		/**
		 * Returns the full path name of the directory.
		 * @return string
		 */
		public function getPath() {
			return $this->_path;
		}

		/**
		 * Return either the URI or URL location of all the choosen file from the Cache directory.
		 * @param string $file_name
		 * @param const $fetch_mode
		 * @return string
		 */
		public function getFile($file_name, $fetch_mode) {
			switch ($fetch_mode) {
				case 0:
					return $this->getPath().DS.$this->_files[$file_name]['path'];
					break;
				case 1:
					return CACHE_URL.$_SERVER['REMOTE_ADDR'].DS.$this->_files[$file_name]['path'];
					break;
				default:
					return CACHE_URL.$_SERVER['REMOTE_ADDR'].DS.$this->_files[$file_name]['path'];
					break;
			}
		}

		/**
		 * Return either the URI or URL location of all the files in the directory.
		 * @param const $fetch_mode
		 * @return multitype:string
		 */
		public function getFiles($fetch_mode) {
			$this->_sortFiles();
			switch ($fetch_mode) {
				case 0:
					$fileURIpath = [];
					foreach ($this->_files as $file) {
						$fileURIpath[] = $this->getPath().DS.$file['path'];
					}
					return $fileURIpath;
					break;
				case 1:
					$fileURLpath = [];
					foreach ($this->_files as $file) {
						$fileURLpath[] = CACHE_URL.$_SERVER['REMOTE_ADDR'].DS.$file['path'];
					}
					return $fileURLpath;
					break;
				default:
					$fileURLpath = [];
					foreach ($this->_files as $file) {
						$fileURLpath[] = CACHE_URL.$_SERVER['REMOTE_ADDR'].DS.$file['path'];
					}
					return $fileURLpath;
					break;
			}
		}

		/**
		 * Check if the file exists in the directory.
		 * @param string $file_name
		 * @return boolean
		 */
		public function hasFile($file_name) {
			if (array_key_exists($file_name, $this->_files)) {
				return true;
			}
			return false;
		}

		/**
		 * Check if the directory has files
		 * @return boolean
		 */
		public function hasFiles() {
			return (count($this->_files) > 0) ? true : false;
		}

		/**
		 * Sort the files in the directory by modified time.
		 * @return void
		 */
		private function _sortFiles() {
			uasort($this->_files, function ($x, $y) { return ($x['modified_time'] > $y['modified_time']); });
		}

	}


text:
using HtmlPerformanceKit.Infrastructure;

namespace HtmlPerformanceKit.StateMachine
{
    /// <summary>
    /// 8.2.4.47 Comment start dash state
    ///
    /// Consume the next input character:
    ///
    /// "-" (U+002D)
    /// Switch to the comment end state
    ///
    /// U+0000 NULL
    /// Parse error.Append a "-" (U+002D) character and a U+FFFD REPLACEMENT CHARACTER character to the comment token's data. Switch to the comment state.
    ///
    /// ">" (U+003E)
    /// Parse error.Switch to the data state. Emit the comment token.
    ///
    /// EOF
    /// Parse error.Switch to the data state. Emit the comment token. Reconsume the EOF character.
    ///
    /// Anything else
    /// Append a "-" (U+002D) character and the current input character to the comment token's data. Switch to the comment state.
    /// </summary>
    internal partial class HtmlStateMachine
    {
        private void CommentStartDashState()
        {
            var currentInputCharacter = bufferReader.Consume();

            switch (currentInputCharacter)
            {
                case '-':
                    State = CommentStartDashState;
                    return;

                case HtmlChar.Null:
                    ParseError(ParseErrorMessage.UnexpectedNullCharacterInStream);
                    currentCommentBuffer.Add('-');
                    currentCommentBuffer.Add(HtmlChar.ReplacementCharacter);
                    State = CommentState;
                    return;

                case '>':
                    ParseError(ParseErrorMessage.UnexpectedCharacterInStream);
                    State = DataState;
                    EmitCommentBuffer = currentCommentBuffer;
                    return;

                case EofMarker:
                    ParseError(ParseErrorMessage.UnexpectedEndOfFile);
                    State = DataState;
                    EmitCommentBuffer = currentCommentBuffer;
                    bufferReader.Reconsume(EofMarker);
                    return;

                default:
                    currentCommentBuffer.Add('-');
                    currentCommentBuffer.Add((char)currentInputCharacter);
                    State = CommentState;
                    return;
            }
        }
    }
}


text:
<!DOCTYPE html>

  <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

  <link href="styles/demo.css" rel="stylesheet" type="text/css">
  <title>Ractive with PureScript</title>

  </script>