text:
<?php
namespace TYPO3\CMS\Install\FolderStructure;

/**
 * Interface implemented by root node
 */
interface RootNodeInterface extends NodeInterface
{
}

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/kzahedi/Shannon.jl.svg?branch=master)](https://travis-ci.org/kzahedi/Shannon.jl)
# Shannon.jl
A collection of quantifications related to Shannon's information theory and methods to discretise data.

## Example

    using Shannon
    xy = hcat([sin(x) + randn() * .1 for x=0:0.01:2pi], [cos(x) + randn() * .1 for x=0:0.01:2pi])
    bxy = bin_matrix(xy, -1.0, 1.0, 10)
    c=combine_binned_matrix(bxy)
    c=relabel(c)
    H = entropy(c)
    I = MI(bxy)

A faster way is to call

    unary_of_matrix(xy, -1.0, 1.0, 10)

which is a short cut for the lines below

    bxy = bin_matrix(xy, -1.0, 1.0, 10)
    c=combine_binned_matrix(bxy)
    c=relabel(c)

## Entropy estimators
The estimators are implemented from the following list of publications:

[1] A. Chao and T.-J. Shen. Nonparametric estimation of shannon's index of diversity when there are unseen species in sample. Environmental and Ecological Statistics, 10(4):429–443, 2003.

and the function call is

    entropy(data, base=2, mode="ML")

where

  **data** 	  is the discrete data (*Vector{Int64}*)

  **mode** 	  determines which estimator should be used (see below). It is *not* case-sensitive

  **base** 	   determines the base of the logarithm

###Maximum Likelihood Estimator
This is the default estimator.

    entropy(data)
    entropy(data, mode="ML")
    entropy(data, mode="Maximum Likelihood")

###Maximum Likelihood Estimator with Bias Correction (implemented from [1])

    entropy(data, mode="MLBC")
    entropy(data, mode="Maximum Likelihood with Bias Compensation")

###Horovitz-Thompson Estimator (implemented from [1])

    entropy(data, mode="HT")
    entropy(data, mode="Horovitz-Thompson")

###Chao-Shen Estimator (implemented from [1])

    entropy(data, mode="CS")
    entropy(data, mode="Chao-Shen")
    entropy(data, mode="ChaoShen")

#### Setting the base

    entropy(data, base=2) [ this is the default ]
    entropy(data, mode="HT", base=10)

## Mutual Information estimators
Currently, only the _maximum likelihood estimator_ is implemented. It can be used with different bases:

    MI(xy, base=2) [ this is the default ]
    MI(xy, base=10)

**xy** is a two-dimensional matrix with **n** rows and two columns.

## Predictive Information
This in an implementation of the one-step predictive information, which is given by the mutual information of consecutive data points. If x is the data vector, then:

    PI(x) = MI(hcat(x[1:end-1], x[2:end]))
    PI(x,[base],[mode]) = MI(x[1:end-1], x[2:end], base, mode)

## Kullback-Leibler Divergence
This function calculates the KL-Divergence on two probability distributions, and is essentially given by:

    KL(p,q)=  sum([(p[i] != 0 && q[i] != 0)? p[i] * log(base, p[i]/q[i]) : 0 for i=1:length(p)])

**p**,**q** must be valid probability distributions, i.e.

    x >= 0 for x in p
    y >= 0 for y in q
    sum(p) == sum(q) == 1.0


text:
>>> from os.path import expanduser
>>> expanduser('~')
'/Users/miki'


text:
var isMac = navigator.platform.toUpperCase().indexOf('MAC')>=0;

var game = new Phaser.Game(800 , 600, Phaser.CANVAS, '', { preload: preload, create: create, update: update });

var cardArray = [{term:"The Constructionist Perspective",definition:"Argues that identification, coding and counting of crime is an inherently social process. How we identify, code and count crime says as much about our society and our justice system as it does about the amount of crime. Police "produce" crime statistics by choosing which calls they think are important enough to warrant police response, and also through exercise of police discretion—i.e., dealing with situations formally (by charge) or informally (by resolving problem without charges)."},
                 {term:"The Dark Figure of Recording",definition:"Not the same as the "dark figure of crime," which refers to two-thirds of crime that is not reported to police. "Dark figure of recording" refers to crime that is reported to the police, but is not recorded by the police. Once a crime is reported to police, it goes through process of assessment, classification and (perhaps) recording. Police decision-making may be influenced by relationship between offender and victim, policing style of individual officer, characteristics of the suspect, and preferences of the complainant. If a reported crime is not recorded by police, then it is not reflected in the UCR."},
                 {term:"Proactive Policing",definition:"Policing styles can have impact on the number and type of crimes reported in the UCR. "Proactive policing" is where police actively go out and look for crime (or opportunities to prevent crime) through enhanced surveillance measures, more interaction with community, or conducting more foot, bike or police car patrols. If police are engaged in proactive policing, then there is higher likelihood of crime being detected and recorded."},
                 {term:"Reactive Policing",definition:"Policing styles can have impact on number and type of crimes reported in the UCR. "Reactive policing" is where police don't do anything unless they receive a call for help or somebody reports a crime. They "react" to calls or reports of crime, or to criminal events they actually witness in the course of their duties. If police are engaged in reactive policing, there is lower likelihood of crime being detected and recorded."},
                 {term:"The Crime Swap",definition:"Questions whether there has been a "crime drop" or a "crime swap." E.g., homicide (murder) rates have been going down, while serious assault rates have been going up (people may be just as violent as before, but improvements in emergency medical care may have improved survival rates). While police-reported break and enters and motor vehicle thefts are going down, Internet-related crimes—credit fraud, identity theft, child-luring—are going up. Many Internet crimes not reported to the police, because victims do not realize they have been victimized, or because police cannot resolve crimes due to jurisdictional issues."},
                 {term:"The Security Hypothesis",definition:"According to UCR, motor vehicle thefts in Canada have declined by 43% over past 10 years. Security hypothesis proposes that decline in motor vehicle thefts is not due to fewer offenders, or to declining interest in stealing cars. Rather, decline may be attributable to greater use of speed bumps and other traffic calming measures, making joyriding less attractive. Alarm systems, better door locks, central locking systems and electronic immobilizers have made motor vehicle theft more difficult. "},
                 {term:"Routine Activities Theory",definition:"By Cohen and Felson, 1979. For a predatory criminal event to occur, you need: \n\n\t\t\t\t1) a motivated offender, \n\t\t\t\t2) a suitable target (a victim), and \n\t\t\t\t3) absence of capable guardianship.\n\nRoutine activities theory says that majority of crimes will occur when victims and offenders intersect in three major social domains where people spend most of their time—i.e., family domain, work domain, and leisure domain. Like lifestyle exposure theory, routine activities theory benefitted from new information being revealed by victimization surveys."},
                 {term:"Lifestyle Exposure Theory",definition:"By Hindelang, Gottfredson and Garofalo, 1978. Like routine activities theory, lifestyle exposure theory benefitted from new information being revealed by victimization surveys. Lifestyle exposure theory says that lifestyles of individuals and groups follow certain patterns, in terms of where they go, when they go there, who they go with (or who they meet there), what they do when they get there. Offenders do not select victims at random; instead, they follow similar lifestyle patterns to those of victims, and often resemble victims in terms of age, gender, social class and ethnic origin. The more time you spend—especially at night—in public places, the more likely you are to become a victim. Lifestyle choices influence likelihood that you will spend more or less time in public."},
                 {term:"Homicide as a Situated Transaction",definition:"1977 study by Luckenbill of 70 homicides (murders) in one Californian county over 10 year period. Found that all these crimes took place away from workplace, mostly on evenings or weekends, in "permissive environs"—informal environments, e.g., parties, bars, street corners, or at home, where individuals would be drinking and partying. Driving force behind transactions was "loss of face," real or imagined; somebody felt insulted, or thought their honour was at stake. Also found that majority of murder victims (63%) initiated transactions themselves, by insulting or threatening "the offender," and in another 29% of cases, the status of offender and victim could only be determined by who lived, and who died."},
                 {term:"Individual Deviance, the Deviant Exchange, and Deviant Exploitation",definition:"From Best and Luckenbill's 1994 book, Organizing Deviance. With first two typologies—individual deviance and the deviant exchange—it's not clear whether there's a "true victim." "Individual deviance" (e.g., drug use or suicide) can be committed by single person in privacy of his/her own home, i.e., offender and victim are the same person. "Deviant exchange" is voluntary transaction in which two or more individuals exchange illicit goods or services. e.g., buying and selling illegal drugs or paying for the services of prostitute. Again, there's no "clear" victim. "Deviant exploitation" is illicit transaction in which deviant uses stealth, trickery or physical force to compel another person to surrender goods or services; the "deviant" is clearly the offender, while the target is most likely a "true victim" (e.g., credit card fraud, shoplifting, armed robbery)."}];

var sceneIndex = 0;
var inScene = false;
var fontChoice = 'Arial';
if(isMac){
    fontChoice = 'Helvetica';
}

var termFontStyle = {font:'18pt '+fontChoice,fill:'#000099',align:'center',wordWrap:true,wordWrapWidth:500};

var definitionFontStyle = {font:'12pt '+fontChoice,fill:'#000000',align:'left',wordWrap:true,wordWrapWidth:500};
if(isMac){
    definitionFontStyle = {font:'13pt '+fontChoice,fill:'#000000',align:'left',wordWrap:true,wordWrapWidth:500};
}
var uxFontStyle = {font:'9pt '+fontChoice,fill:'#FFFFFF',align:'left'};
var flipFontStyle = {font:'9pt ',fill:'#000000',align:'center'};
var buttonFontStyle= {font:'20px '+fontChoice,fill:'#FFFFFF',align:'center'};
var titleFontStyle = {font:'30pt '+fontChoice,fill:'#FFFFFF',align:'center'};
var flashcard;
var cardIndex =0;
var numCards = cardArray.length;
var buttonSound;
var flipped = false;

var definitionText;
var termText;
var currentPosition;
var sortButtonText;
var paperSound;
var shuffleSound;

var displayType = "term";
function preload(){
    game.stage.backgroundColor='#000066';
    game.load.image('mycard','assets/card6.png');
    game.load.spritesheet('greenbutton','assets/greenbutton.png',186,43);
    game.load.audio('button',['assets/buttonclick.mp3','assets/buttonclick.ogg']);
    game.load.audio('paper',['assets/paperflip.mp3','assets/paperflip.ogg']);
    game.load.audio('shuffle',['assets/shuffle.mp3','assets/shuffle.ogg']);
    game.load.image('flip','assets/fliparrow2.png');

};

function create(){
    Phaser.Canvas.setSmoothingEnabled(game.context, false);

    buttonSound = game.add.audio('button');
    paperSound  = game.add.audio('paper');
    shuffleSound = game.add.audio('shuffle');

  flashcard = game.add.sprite(game.world.centerX,game.world.centerY,'mycard');
  flashcard.anchor.setTo(0.5,0.5);

  var nextButton  = game.add.button(game.world.centerX+200,515,'greenbutton',nextCard,this,0,1,2);
  nextButton.anchor.setTo(0.5,0.5);

  var nextButtonText = game.add.text(nextButton.x,nextButton.y,"Next Card",buttonFontStyle);
  nextButtonText.anchor.setTo(0.5,0.5);

  var prevButton = game.add.button(game.world.centerX-200,515,'greenbutton',prevCard,this,0,1,2);
  prevButton.anchor.setTo(0.5,0.5);

  var prevButtonText = game.add.text(prevButton.x,prevButton.y,"Previous Card",buttonFontStyle);
  prevButtonText.anchor.setTo(0.5,0.5);

  var flipButton = game.add.button(flashcard.x+((flashcard.width/2)-40),flashcard.y+((flashcard.height/2)-50),'flip',flipCard,this);
  flipButton.anchor.setTo(0.5,0.5);

  var flipButtonText = game.add.text(flipButton.x-2,flipButton.y+30,"Flip Card",flipFontStyle);
  flipButtonText.anchor.setTo(0.5,0.5);

  var shuffleButton = game.add.button(game.world.centerX,515,'greenbutton',shuffle,this,0,1,2);
  shuffleButton.anchor.setTo(0.5,0.5);

  var shuffleText = game.add.text(shuffleButton.x,shuffleButton.y,"Shuffle Deck",buttonFontStyle);
  shuffleText.anchor.setTo(0.5,0.5);

  var titleText = game.add.text(game.world.centerX,75,"Crime in Canada: Tutorial 3 Flashcards",titleFontStyle);
  titleText.anchor.setTo(0.5,0.5);

  var sortButton = game.add.button(game.world.centerX,560,'greenbutton',swapSort,this);
  sortButton.anchor.setTo(0.5,0.5);
  sortButton.alpha =0;

  sortButtonText = game.add.text(sortButton.x,sortButton.y,"View By: Term",buttonFontStyle);
  sortButtonText.anchor.setTo(0.5,0.5);

  if(!isMac){
  definitionText = game.add.text(flashcard.x,flashcard.y-120,'',definitionFontStyle);
  termText = game.add.text(game.world.centerX,game.world.centerY+4,'',termFontStyle);
  currentPosition = game.add.text(game.world.centerX,110,"Card "+(cardIndex+1)+" of "+numCards,uxFontStyle);
  }else{
  definitionText = game.add.text(flashcard.x,flashcard.y-121,'',definitionFontStyle);
  termText = game.add.text(game.world.centerX,game.world.centerY+9,'',termFontStyle);
  currentPosition = game.add.text(game.world.centerX,111,"Card "+(cardIndex+1)+" of "+numCards,uxFontStyle);

  }
  currentPosition.anchor.setTo(0.5,0.5);
  definitionText.anchor.setTo(0.5,0);
  termText.anchor.setTo(0.5,0.5);

};

function swapSort(){
    flipped = false;
    buttonSound.play();
    if(displayType==="term"){
        displayType="definition";
        sortButtonText.setText("View By: Definition");
    }else{
        displayType="term";
        sortButtonText.setText("View By: Term");
    }
    displayCards();
}

function shuffle(){
    flipped = false;
    shuffleSound.play();
    var tempArray = [];

    for(var i=0;i<cardArray.length;i++){
        var randomNum = Math.floor(Math.random()*cardArray.length);
        tempArray.push(cardArray[randomNum]);
        cardArray.splice(randomNum,1);
        i--;
    }
    cardIndex=0;
    cardArray = tempArray;
    displayCards();
}

function nextCard(){
    flipped = false;
    buttonSound.play();
    if(cardIndex+1>=numCards){
        cardIndex=0;
    }else{
        cardIndex++;
    }
    displayCards();
}

function prevCard(){
    flipped=false;
    buttonSound.play();
    if(cardIndex-1<0){
        cardIndex = numCards-1;
    }else{
        cardIndex--;
    }
    displayCards();
}

function flipCard(){
    if(flipped===false){
        paperSound.play();
        if(displayType == "definition"){
             termText.setText(cardArray[cardIndex].term);
             definitionText.setText("");
        }else{
            definitionText.setText(cardArray[cardIndex].definition);
            termText.setText("");
        }
        flipped = true;
        return;
    }

    if(flipped){
        paperSound.play();
          if(displayType == "definition"){
             termText.setText("");
             definitionText.setText(cardArray[cardIndex].definition);
        }else{
            definitionText.setText("");
            termText.setText(cardArray[cardIndex].term);
        }
        flipped = false;
        return;
    }
}

function nextScene(){
    sceneIndex++;
    inScene = false;
}

function introduction(){
    console.log("introduction");
    nextScene();
};

function introductionFadeOut(){
    console.log("introductionFadeOut");
    nextScene();
}

function displayCards(){
    console.log("displayCards");
    //insert logic for displaying term or definition first
    //insert logic if sorting is applied
    definitionText.setText("");
    termText.setText("");

    if(displayType == "definition"){
        definitionText.setText(cardArray[cardIndex].definition);
    }else{
        termText.setText(cardArray[cardIndex].term);
    }
    currentPosition.setText("Card "+(cardIndex+1)+" of "+numCards);

}

function update(){

        if(!inScene){

            inScene = true;

            switch(sceneIndex){
                case 0: introduction();
                        break;
                case 1: introductionFadeOut();
                        break;
                case 2: displayCards();
                        break;
            };
        };

};


text:
package com.bitmonlab.osiris.test.acceptancetest.map.feature;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import com.bitmonlab.osiris.test.acceptancetest.map.commons.HttpResponse;
import com.bitmonlab.osiris.api.core.map.transferobject.FeatureDTO;
import com.bitmonlab.osiris.api.core.map.transferobject.GeometryDTO;
import com.bitmonlab.osiris.api.core.map.transferobject.LineStringDTO;
import com.bitmonlab.osiris.api.core.map.transferobject.PointDTO;
import com.bitmonlab.osiris.api.core.map.transferobject.PolygonDTO;
import com.bitmonlab.osiris.restsender.ClientResponse;
import com.bitmonlab.osiris.restsender.Headers;
import com.bitmonlab.osiris.restsender.RestMethod;
import com.bitmonlab.osiris.restsender.RestRequestSender;
import com.sun.jersey.api.client.GenericType;

import cucumber.api.java.en.When;
public class UpdateFeature {

	@Inject
	@Named("osirisMapRequestSender")
	private RestRequestSender sender;

	@Inject
	private HttpResponse httpResponse;

	@Inject
	private PreconditionStoreFeature preconditionStoreFeature;

	private ClientResponse<FeatureDTO> response;

	@Inject
	private CheckWithGetFeature checkWithGet;

	@When("^I invoke a PUT to \"([^\"]*)\" of type point and idFeature with latitude (\\d+), longitude (\\d+), altitude (\\d+) and jsonObject with key \"([^\"]*)\" and value \"([^\"]*)\"$")
	public void I_invoke_a_PUT_to_of_type_point_and_idFeature_with_latitude_longitude_altitude_and_jsonObject_with_key_and_value(String url, Double latitude, Double longitude, Double altitude, String key, String value){

		Map<String,String> properties = new HashMap<String, String>();
		properties.put(key, value);

		PointDTO pointDTO=createGeometryPoint(latitude,longitude);

		FeatureDTO featureDTO=createFeatureDTO(properties, pointDTO);

		FeatureDTO feature =  preconditionStoreFeature.getResponse().getEntity();
		String idFeature = feature.getId();

		response=sender.invoke(RestMethod.PUT, url + "/" + idFeature , featureDTO, new GenericType<FeatureDTO>(){}, new Headers("api_key", "1"), new Headers("Authorization", "Basic cm9vdDoxMjM0"));

		httpResponse.setResponse(response);

		checkWithGet.setResponse(response);

	}

	@When("^I invoke a PUT to \"([^\"]*)\" of type lineString and idFeature with latitude (\\d+), longitude (\\d+), altitude (\\d+), latitude (\\d+), longitude (\\d+), altitude (\\d+) and jsonObject with key \"([^\"]*)\" and value \"([^\"]*)\"$")
	public void I_invoke_a_PUT_to_of_type_lineString_and_idFeature_with_latitude_longitude_altitude_latitude_longitude_altitude_and_jsonObject_with_key_and_value(String url, Double latitude1, Double longitude1, Double altitude1, Double latitude2, Double longitude2, Double altitude2, String key, String value) throws Throwable {

		Map<String,String> properties = new HashMap<String, String>();
		properties.put(key, value);

		PointDTO pointDTO1=createGeometryPoint(latitude1,longitude1);
		PointDTO pointDTO2=createGeometryPoint(latitude2,longitude2);

		Collection<PointDTO> collectionPointDTOs=new ArrayList<PointDTO>();
		collectionPointDTOs.add(pointDTO1);
		collectionPointDTOs.add(pointDTO2);

		LineStringDTO lineStringDTO=createGeometryLineString(collectionPointDTOs);

		FeatureDTO featureDTO=createFeatureDTO(properties, lineStringDTO);

		FeatureDTO feature =  preconditionStoreFeature.getResponse().getEntity();
		String idFeature = feature.getId();

		response=sender.invoke(RestMethod.PUT, url + "/" + idFeature , featureDTO, new GenericType<FeatureDTO>(){}, new Headers("api_key", "1"), new Headers("Authorization", "Basic cm9vdDoxMjM0"));

		httpResponse.setResponse(response);

		checkWithGet.setResponse(response);

	}

	@When("^I invoke a PUT to \"([^\"]*)\" of type polygon and idFeature with latitude (\\d+), longitude (\\d+), altitude (\\d+), latitude (\\d+), longitude (\\d+), altitude (\\d+), latitude (\\d+), longitude (\\d+), altitude (\\d+), latitude (\\d+), longitude (\\d+), altitude (\\d+), latitude (\\d+), longitude (\\d+), altitude (\\d+), latitude (\\d+), longitude (\\d+), altitude (\\d+), latitude (\\d+), longitude (\\d+), altitude (\\d+), latitude (\\d+), longitude (\\d+), altitude (\\d+) and jsonObject with key \"([^\"]*)\" and value \"([^\"]*)\"$")
	public void I_invoke_a_PUT_to_of_type_polygon_and_idFeature_with_latitude_longitude_altitude_latitude_longitude_altitude_latitude_longitude_altitude_latitude_longitude_altitude_latitude_longitude_altitude_latitude_longitude_altitude_latitude_longitude_altitude_latitude_longitude_altitude_and_jsonObject_with_key_and_value(
			String url,
			Double latitude1, Double longitude1, Double altitude1,
			Double latitude2, Double longitude2, Double altitude2,
			Double latitude3, Double longitude3, Double altitude3,
			Double latitude4, Double longitude4, Double altitude4,
			Double latitude5, Double longitude5, Double altitude5,
			Double latitude6, Double longitude6, Double altitude6,
			Double latitude7, Double longitude7, Double altitude7,
			Double latitude8, Double longitude8, Double altitude8,
			String key, String value){

		Map<String,String> properties = new HashMap<String, String>();
		properties.put(key, value);

		PointDTO pointDTO1=createGeometryPoint(latitude1,longitude1);
		PointDTO pointDTO2=createGeometryPoint(latitude2,longitude2);
		PointDTO pointDTO3=createGeometryPoint(latitude3,longitude3);
		PointDTO pointDTO4=createGeometryPoint(latitude4,longitude4);
		PointDTO pointDTO5=createGeometryPoint(latitude5,longitude5);
		PointDTO pointDTO6=createGeometryPoint(latitude6,longitude6);
		PointDTO pointDTO7=createGeometryPoint(latitude7,longitude7);
		PointDTO pointDTO8=createGeometryPoint(latitude8,longitude8);

		Collection<PointDTO> collectionPointDTOs1=new ArrayList<PointDTO>();
		collectionPointDTOs1.add(pointDTO1);
		collectionPointDTOs1.add(pointDTO2);
		collectionPointDTOs1.add(pointDTO3);
		collectionPointDTOs1.add(pointDTO4);
		collectionPointDTOs1.add(pointDTO1);

		Collection<PointDTO> collectionPointDTOs2=new ArrayList<PointDTO>();
		collectionPointDTOs2.add(pointDTO5);
		collectionPointDTOs2.add(pointDTO6);
		collectionPointDTOs2.add(pointDTO7);
		collectionPointDTOs2.add(pointDTO8);
		collectionPointDTOs2.add(pointDTO5);

		LineStringDTO lineStringDTO1=createGeometryLineString(collectionPointDTOs1);
		LineStringDTO lineStringDTO2=createGeometryLineString(collectionPointDTOs2);

		Collection<LineStringDTO> collectionLineString=new ArrayList<LineStringDTO>();
		collectionLineString.add(lineStringDTO1);
		collectionLineString.add(lineStringDTO2);

		PolygonDTO polygonDTO=createGeometryPolygon(collectionLineString);

		FeatureDTO featureDTO=createFeatureDTO(properties, polygonDTO);

		FeatureDTO feature =  preconditionStoreFeature.getResponse().getEntity();
		String idFeature = feature.getId();

		response=sender.invoke(RestMethod.PUT, url + "/" + idFeature , featureDTO, new GenericType<FeatureDTO>(){}, new Headers("api_key", "1"), new Headers("Authorization", "Basic cm9vdDoxMjM0"));

		httpResponse.setResponse(response);

		checkWithGet.setResponse(response);

	}

	@When("^I invoke a PUT to \"([^\"]*)\" of type errorGeometry with key \"([^\"]*)\" and value \"([^\"]*)\"$")
	public void I_invoke_a_PUT_to_of_type_errorGeometry_with_key_and_value(String url, String key, String value) throws Throwable {

		Map<String,String> properties = new HashMap<String, String>();
		properties.put(key, value);

		FeatureDTO featureDTO=createFeatureDTO(properties, null);

		FeatureDTO feature =  preconditionStoreFeature.getResponse().getEntity();
		String idFeature = feature.getId();

		response=sender.invoke(RestMethod.PUT, url + "/" + idFeature , featureDTO, new GenericType<FeatureDTO>(){}, new Headers("api_key", "1"), new Headers("Authorization", "Basic cm9vdDoxMjM0"));

		httpResponse.setResponse(response);

		checkWithGet.setResponse(response);

	}

	@When("^I invoke a PUT to \"([^\"]*)\" of type point with latitude (\\d+), longitude (\\d+), altitude (\\d+) and jsonObject with key \"([^\"]*)\" and value \"([^\"]*)\"$")
	public void I_invoke_a_PUT_to_of_type_point_with_latitude_longitude_altitude_and_jsonObject_with_key_and_value(String url, Double latitude, Double longitude, Double altitude, String key, String value) throws Throwable {

		Map<String,String> properties = new HashMap<String, String>();
		properties.put(key, value);

		PointDTO pointDTO=createGeometryPoint(latitude,longitude);

		FeatureDTO featureDTO=createFeatureDTO(properties, pointDTO);

		response=sender.invoke(RestMethod.PUT, url, featureDTO, new GenericType<FeatureDTO>(){}, new Headers("api_key", "1"), new Headers("Authorization", "Basic cm9vdDoxMjM0"));

		httpResponse.setResponse(response);

		checkWithGet.setResponse(response);

	}

	private PointDTO createGeometryPoint(Double latitude, Double longitude){
		PointDTO pointDTO = new PointDTO();
		pointDTO.setLatitude(latitude);
		pointDTO.setLongitude(longitude);
		return pointDTO;
	}

	private LineStringDTO createGeometryLineString(Collection<PointDTO> collectionPointDTOs){
		LineStringDTO lineStringDTO = new LineStringDTO();
		lineStringDTO.setCollectionPointDTO(collectionPointDTOs);
		return lineStringDTO;
	}

	private PolygonDTO createGeometryPolygon(Collection<LineStringDTO> collectionLineStringDTOs){
		PolygonDTO polygonDTO = new PolygonDTO();
		polygonDTO.setCollectionLineStringDTO(collectionLineStringDTOs);
		return polygonDTO;
	}

	private FeatureDTO createFeatureDTO(Map<String,String> properties, GeometryDTO geometryDTO){
		FeatureDTO featureDTO = new FeatureDTO();
		featureDTO.setProperties(properties);
		featureDTO.setGeometryDTO(geometryDTO);
		return featureDTO;
	}
}


text:
class Admin::GroupsController < Admin::Base
  include ErrorDisplayable

  def new
    @page_title = "Create new group"
    @group = Group.new
  end

  def create
    @group = Group.create myparams
    if @group.save
      redirect_to groups_path, notice: "created."
    else
      display_errors @group.errors, :new, "Create new group"
    end
  end

  def edit
    @group = Group.find params[:id]
    @page_title = @group.name
  rescue
    redirect_to groups_path
  end

  def update
    @group = Group.find params[:id]
    name = @group.name
    if @group.update myparams
      redirect_to @group, notice: "updated."
    else
      display_errors @group.errors, :edit, name
    end
  rescue
    redirect_to groups_path
  end

  def destroy
    g = Group.find params[:id]
    if g.remove
      redirect_to groups_path, notice: "deleted."
    else
      redirect_to g, alert: "Error.#{" (Group with some items is protected)" unless g.items.empty?}"
    end
  rescue
    redirect_to groups_path, alert: "error"
  end

  private
  def myparams
    params.require(:group).permit(:name, :memo)
  end
end


text:
$:.unshift(File.dirname(__FILE__) + '/../lib')

require 'rubygems'
require 'bundler'
require 'ostruct'
require 'pry'
Bundler.require(:default, :test)

ActiveRecord::Base.establish_connection({
  :adapter  => 'mysql2',
  :host     => 'localhost',
  :database => 'encrypted_attributes_test',
  :username => 'root',
  :encoding => 'utf8'
})

class CreateSchema < ActiveRecord::Migration
  def self.up
    create_table :encrypto do |t|
      t.binary :description
    end
  end

  def self.down
    drop_table :encrypto
  end
end

RSpec.configure do |config|
  config.before(:suite) do
    CreateSchema.up
  end

  config.after(:each) do
    ActiveRecord::Base.connection.execute('TRUNCATE encrypto')
  end

  config.after(:suite) do
    CreateSchema.down
  end
end


text:
* make resume page (as opposed to just static PDF)
* handle printability
* Change favicon handling per https://github.com/audreyr/favicon-cheat-sheet
* Update article contents (ongoing)
* Write real phpunit tests for Travis CI (to replace the dummy one in place now)


text:
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'

import Input from './TextInputInput'
import Label from './TextInputLabel'

// `<input/>` and its `<label/>`.
function TextInputComponent(props, ref) {
	const {
		id,
		value,
		required,
		floatingLabel,
		label,
		placeholder,
		multiline,
		error,
		indicateInvalid,
		containerRef
	} = props

	const {
		icon: Icon,
		className,
		children,
		...rest
	} = props

	return (
		<div
			ref={containerRef}
			className={classNames('rrui__input', {
				'rrui__input--multiline' : multiline,
			})}>

			{Icon &&
				<Icon className="rrui__input-field__icon"/>
			}

			{/* `<input/>` */}
			<Input
				{...rest}
				ref={ref}
				className={classNames(className, {
					'rrui__input-field--with-icon': Icon
				})}/>

			{/* Input `<label/>`. */}
			{/* It is rendered after the input to utilize the
		       `input:focus + label` CSS selector rule */}
			{label &&
				<Label
					aria-hidden
					inputId={id}
					value={value}
					required={required}
					invalid={indicateInvalid && error}
					floats={floatingLabel && !placeholder}>
					{label}
				</Label>
			}

			{/* `children` are placed after the `<input/>`
			    so that in cases when they're `position: absolute`
			    then their default top position is right below the `<input/>`.
			    For example, this is used in `<DatePicker/>` so that
			    the list of options is displayed right below the `<input/>`. */}
			{children}
		</div>
	)
}

TextInputComponent = React.forwardRef(TextInputComponent)

TextInputComponent.propTypes = {
	// Set to `true` to mark the field as required.
	required : PropTypes.bool.isRequired,

	// Indicates that the input is invalid.
	error: PropTypes.oneOfType([
		PropTypes.string,
		PropTypes.bool
	]),

	// Labels float by default.
	floatingLabel : PropTypes.bool.isRequired,

	// `<input/>` icon.
	icon : PropTypes.func
}

TextInputComponent.defaultProps = {
	// Set to `true` to mark the field as required.
	required : false,

	// Labels float by default.
	floatingLabel : true
}

export default TextInputComponent


text:
The need for this library came from a business requirement to calculate a date, X number of business days into the future including public holidays.

Traditional approaches to this solving this problem might be a) storing public holidays in a database or configuration file and then reading this information at runtime, b) use of a third party service. Some of the negatives associated to this type of approaches include:
* Accessing a database, configuration file, or third party service is slow.
* Someone needs to remember to update the public holiday data every year.
* Implementing the public holiday business logic is additional code that needs to written and maintained.
* There is always a chance for data errors.

Looking at the list of Australian public holiday dates, it's soon clear that the date of most of them can be consistently deduced. An application-library/utility to solve this problem is absolutely possible, albiet with a few minor considerations outlined in the next section.

## Exclusions

The calculations for most Australian public holidays is pretty straight forward. However, there are a few cases that need special mention:

* Partial public holidays are not taken into consideration e.g. Chrismas Eve.
* Public holidays that are not observed in *most*\* areas/postcodes within a state are excluded e.g. Royal Queensland Show in QLD & other regional public holidays.
* Public holidays where the date cannot be consistently deduced have not been implemented e.g. Grand final Eve in VIC & Family & Community Day in ACT.
* Public holidays that only apply to specific industries are excluded e.g. Bank Holiday in NSW.

\* A public holiday that is *inclusive* of particluar city/town/postcode should be excluded e.g. Royal Queensland Show in QLD. Alternativly a public holiday that is *exclusive* of particluar city/town/postcode should be included e.g. The Melbourne Cup in VIC where some regions observe the holiday on a differnet day corresponding with their own local racing carnival.

## List of Public Holidays
| Holiday | State | Calculation |
| :--- | :--- | :--- |
| New Years Day | National | 1 January - if that date falls on a Saturday the public holiday transfers to the following Monday. If that date falls on a Sunday that day and the following Monday will be public holidays. |
| Australia Day | National | 26 January - if that date falls on a Saturday the public holiday transfers to the following Monday. If that date falls on a Sunday that day and the following Monday will be public holidays. |
| Labour Day | WA | 1st Monday in March. |
| Canberra Day | ACT | 2nd Monday in March. |
| Labour Day* | TAS, VIC | 2nd Monday in March. |
| March public holiday | SA | 2nd Monday in March (currently proclaimed until 2019). |
| Good Friday | National | Varies according to the lunar cycle. |
| Easter Saturday | ACT, NSW, NT, QLD, SA, VIC | Varies according to the lunar cycle. |
| Easter Sunday | ACT, NSW, VIC | Varies according to the lunar cycle. |
| Easter Monday | National | Varies according to the lunar cycle. |
| Easter Tuesday | TAS | Varies according to the lunar cycle. |
| Anzac Day | National | 25 April - if the date falls on a Saturday, the public holiday is observed on that Saturday. If that date falls on a Sunday that day and the following Monday will be public holidays. |
| Labour Day* | NT, QLD | 1st Monday in May. |
| Western Australia Day | WA | 1st Monday in June. |
| Queen's Birthday** | ACT, NSW, NT, SA, TAS, VIC | 2nd Monday in June. |
| Picnic Day | NT | 1st Monday in August. |
| Family & Community Day | ACT | 1st Monday of 3rd term school holidays. |
| Queen's Birthday | WA | Last Monday in September, or 1st Monday in October (when the last day in September falls on a weekend). |
| Grand Final Eve| VIC | Last Friday in September, or 1st Friday in October. |
| Queen's Birthday | QLD | 1st Monday in October. |
| Labour Day | ACT, NSW, SA | 1st Monday in October. |
| Melbourne Cup Day | VIC | 1st Tuesday in November. |
| Christmas Day  | National | 25 December - if that date falls on a Saturday the public holiday transfers to the following Monday. If that date falls on a Sunday that day and the following Monday will be public holidays. |
| Boxing Day*** | National | 26 December - if that date falls on a Saturday the public holiday transfers to the following Monday. If that date falls on a Sunday or a Monday that day and the following Tuesday will be public holidays. |

\* Known as May Day in NT and Eight Hours Day in TAS.

\*\* Also known as Volunteer's Day in SA.

\*\*\* Known as Proclamation Day in SA.

## Code
Most of the functionality is accessible via DateTime extension methods for example:
```c#
var nextBusinessDay = DateTime.Now.AddBusinessDays(10);
var nextBusinessDayInSA = DateTime.Now.AddBusinessDays(3, State.SA);
```

## Contributing
Would you be interested in contributing? All PRs are welcome.


text:
<?php declare(strict_types=1);
namespace Onion\Framework\Rest;

use Fig\Link\EvolvableLinkProviderTrait;
use Onion\Framework\Rest\Interfaces\EntityInterface;
use Onion\Framework\Rest\Interfaces\TransformableInterface;

/**
 * Class Entity
 *
 * @package Onion\Framework\Rest
 *
 * @codeCoverageIgnore
 */
class Entity implements EntityInterface
{
    use EvolvableLinkProviderTrait;

    /**
     * @var string The rel of the element
     */
    private $rel;

    /**
     * @var array
     */
    private $data = [];

    /**
     * @var \SplObjectStorage
     */
    private $embedded = [];

    private $meta = [];

    public function __construct(string $rel)
    {
        $this->rel = $rel;
        $this->embedded = new \SplObjectStorage();
    }

    public function getRel(): string
    {
        return $this->rel;
    }

    public function withAddedMetaData(iterable $meta): EntityInterface
    {
        $self = clone $this;
        $self->meta = array_merge($self->meta, $meta);

        return $self;
    }

    public function withMetaData(iterable $meta): EntityInterface
    {
        $self = clone $this;
        $self->meta = $meta;

        return $self;
    }

    public function getMetaData(): iterable
    {
        return $this->meta;
    }

    public function withDataItem(string $name, $value): EntityInterface
    {
        $self = clone $this;
        $self->data[$name] = $value;

        return $self;
    }

    public function withoutDataItem(string $name): EntityInterface
    {
        $self = clone $this;
        unset($self->data[$name]);

        return $self;
    }

    public function getDataItem(string $name, $default = null)
    {
        return $this->data[$name] ?? $default;
    }

    public function withData(iterable $data): EntityInterface
    {
        $self = clone $this;
        $self->data = array_merge($self->data, $data);

        return $self;
    }

    public function withoutData(): EntityInterface
    {
        $self = clone $this;
        $self->data = [];

        return $self;
    }

    public function getData(): iterable
    {
        return $this->data;
    }

    public function withEmbedded(TransformableInterface $entity): EntityInterface
    {
        $self = clone $this;
        if ($self->embedded->contains($entity)) {
            throw new \InvalidArgumentException('Attempting to insert duplicate entity');
        }
        $this->embedded->attach($entity);

        return $self;
    }

    public function withoutEmbedded(TransformableInterface $entity): EntityInterface
    {
        $self = clone $this;
        if ($this->embedded->contains($entity)) {
            $self->embedded->detach($entity);
        }

        return $self;
    }

    public function getEmbedded(): iterable
    {
        return $this->embedded;
    }

    public function hasEmbedded(): bool
    {
        return !empty($this->embedded);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Acta Soc. Sci. fenn. 7: 484 (1863)

#### Original name
Arthonia propinqua Nyl.

### Remarks
null


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of PurchaseViewModel
 *
 * @author 志鹏
 */
class PurchaseViewModel extends CommonViewModel {

    protected $workflowAlias = "purchase";

    protected $viewFields = array(
        "Purchase" => array("*", "_type"=>"left"),
        "Types"=> array("name"=>"purchase_type_label", "_on"=>"Purchase.purchase_type=Types.id", "_type"=>"left"),
        "User" => array("truename" => "buyer", "_on" => "Purchase.user_id=User.id", "_type"=>"left"),
        "RelationshipCompany" => array("name"=>"supplier_id_label", "address", "_on"=>"RelationshipCompany.id=Purchase.supplier_id", "_type"=>"left"),
    );

    public $searchFields = array(
        "bill_id", "User.truename", "RelationshipCompany.name", "Types.name"
    );

}

?>


text:
<?php

namespace Reliv\Deploy\Xmpp\Event;

use Reliv\Deploy\Command\CommandInterface;
use Reliv\Deploy\Xmpp\Helper\CronHelper;

class AuthEvent extends XmppEventAbstract
{
    protected $authenticated = false;
    protected $errorMessage  = '';

    /**
     * Event Constructor
     *
     * @param \JAXL            $client        Jaxl Client
     * @param CommandInterface $command       Running Command
     * @param CronHelper       $cronHelper    Cron Helper
     * @param boolean          $authenticated Authentication result
     * @param string           $errorMessage  Authentication Error Message
     */
    public function __construct(
        \JAXL $client,
        CommandInterface  $command,
        CronHelper $cronHelper,
        $authenticated,
        $errorMessage = ''
    ) {
        $this->authenticated = $authenticated;
        $this->errorMessage = $errorMessage;

        parent::__construct($client, $command, $cronHelper);
    }

    /**
     * Is the user Authenticated
     *
     * @return mixed
     */
    public function isAuthenticated()
    {
        return $this->authenticated;
    }

    /**
     * Get the connect error message
     *
     * @return string
     */
    public function getErrorMessage()
    {
        return $this->errorMessage;
    }
}


text:
package com.aftership.sdk.connect;

import android.support.annotation.NonNull;

import com.aftership.sdk.connect.dto.json.ASTrackingResponse;

/**
 * Common class for single tracking request.
 *
 * @author John
 */
public abstract class ASTrackingRequest extends AfterShipRequest<ASTrackingRequest.TrackingResponse,
        ASTrackingRequest.TrackingResponseData> {

    @NonNull
    protected final String mSlug;
    @NonNull
    protected final String mTrackingNumber;

    ASTrackingRequest(@NonNull String slug,
                      @NonNull String trackingNumber) {
        mSlug = slug;
        mTrackingNumber = trackingNumber;
    }

    ///////////////////////////
    // Class and interface
    ///////////////////////////
    public static class TrackingResponse extends ASEnvelopeResponse<TrackingResponseData> {
        TrackingResponseData data;

        @Override
        TrackingResponseData getData() {
            return data;
        }
    }

    public static class TrackingResponseData implements ASEnvelopeData {
        ASTrackingResponse tracking;

        public ASTrackingResponse getTracking() {
            return tracking;
        }
    }
}


text:
using SharpDX;

public class RawUberMaterialSettings {
	public string uvSet;

	public int baseMixing;

	//Base / Diffuse / Reflection
	public RawFloatTexture metallicWeight;
	public RawFloatTexture diffuseWeight;
	public RawColorTexture baseColor;

	//Base / Diffuse / Translucency
	public RawFloatTexture translucencyWeight;
	public int baseColorEffect;
	public RawColorTexture translucencyColor;
	public Vector3 sssReflectanceTint;

	//Base / Glossy / Reflection
	public RawFloatTexture glossyWeight;
	public RawFloatTexture glossyLayeredWeight;
	public RawColorTexture glossyColor;
	public int glossyColorEffect;
	public RawFloatTexture glossyReflectivity;
	public RawColorTexture glossySpecular;
	public RawFloatTexture glossyRoughness;
	public RawFloatTexture glossiness;

	//Base / Glossy / Refraction
	public float refractionIndex;
	public RawFloatTexture refractionWeight;

	//Base / Bump
	public RawFloatTexture bumpStrength;
	public RawFloatTexture normalMap;

	//Top Coat / General
	public RawFloatTexture topCoatWeight;
	public RawColorTexture topCoatColor;
	public int topCoatColorEffect;
	public RawFloatTexture topCoatRoughness;
	public RawFloatTexture topCoatGlossiness;
	public int topCoatLayeringMode;
	public RawFloatTexture topCoatReflectivity;
	public RawFloatTexture topCoatIor;
	public RawFloatTexture topCoatCurveNormal;
	public RawFloatTexture topCoatCurveGrazing;

	//Top Coat / Bump
	public int topCoatBumpMode;
	public RawFloatTexture topCoatBump;

	//Volume
	public bool thinWalled;
	public float transmittedMeasurementDistance;
	public Vector3 transmittedColor;
	public float scatteringMeasurementDistance;
	public float sssAmount;
	public float sssDirection;

	//Geometry / Cutout
	public RawFloatTexture cutoutOpacity;
}


text:
package work.zhili.password;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@MapperScan("work.zhili.password.mapper")
public class PasswordWebApplication {

	public static void main(String[] args) {
		SpringApplication.run(PasswordWebApplication.class, args);
		System.out.println("password started ...");
	}
}


text:
description("Tests dynamic updates of the 'slope' property of the SVGFEComponentTransferElement object")
createSVGTestCase();

var feRFunc = createSVGElement("feFuncR");
feRFunc.setAttribute("type", "linear");
feRFunc.setAttribute("slope", "1");

var feGFunc = createSVGElement("feFuncG");
feGFunc.setAttribute("type", "linear");
feGFunc.setAttribute("slope", "1");

var feBFunc = createSVGElement("feFuncB");
feBFunc.setAttribute("type", "linear");
feBFunc.setAttribute("slope", "1");

var feAFunc = createSVGElement("feFuncA");
feAFunc.setAttribute("type", "linear");
feAFunc.setAttribute("slope", "1");

var feCompnentTransferElement = createSVGElement("feComponentTransfer");
feCompnentTransferElement.appendChild(feRFunc);
feCompnentTransferElement.appendChild(feGFunc);
feCompnentTransferElement.appendChild(feBFunc);
feCompnentTransferElement.appendChild(feAFunc);

var compTranFilter = createSVGElement("filter");
compTranFilter.setAttribute("id", "compTranFilter");
compTranFilter.setAttribute("filterUnits", "objectBoundingBox");
compTranFilter.setAttribute("x", "0%");
compTranFilter.setAttribute("y", "0%");
compTranFilter.setAttribute("width", "100%");
compTranFilter.setAttribute("height", "100%");
compTranFilter.appendChild(feCompnentTransferElement);

var defsElement = createSVGElement("defs");
defsElement.appendChild(compTranFilter);
rootSVGElement.appendChild(defsElement);

var imageElement = createSVGElement("image");
imageElement.setAttributeNS(xlinkNS, "xlink:href", "../W3C-SVG-1.1/resources/struct-image-01.png");
imageElement.setAttribute("width", "400");
imageElement.setAttribute("height", "200");
imageElement.setAttribute("preserveAspectRatio", "none");
imageElement.setAttribute("filter", "url(#compTranFilter)");
rootSVGElement.appendChild(imageElement);

rootSVGElement.setAttribute("width", "400");
rootSVGElement.setAttribute("height", "200");

shouldBe("feRFunc.slope.baseVal", "1");
shouldBe("feGFunc.slope.baseVal", "1");
shouldBe("feBFunc.slope.baseVal", "1");
shouldBe("feAFunc.slope.baseVal", "1");

function repaintTest() {
    feRFunc.slope.baseVal = 2;
    feGFunc.slope.baseVal = 2;
    feBFunc.slope.baseVal = 2;
    feAFunc.slope.baseVal = 2;

    shouldBe("feRFunc.slope.baseVal", "2");
    shouldBe("feGFunc.slope.baseVal", "2");
    shouldBe("feBFunc.slope.baseVal", "2");
    shouldBe("feAFunc.slope.baseVal", "2");
}

var successfullyParsed = true;


text:
#include "webrtc/modules/video_capture/video_capture_impl.h"

#include <stdlib.h>

#include "webrtc/base/refcount.h"
#include "webrtc/base/timeutils.h"
#include "webrtc/base/trace_event.h"
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/modules/include/module_common_types.h"
#include "webrtc/modules/video_capture/video_capture_config.h"
#include "webrtc/system_wrappers/include/clock.h"
#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
#include "webrtc/system_wrappers/include/logging.h"

namespace webrtc {
namespace videocapturemodule {
rtc::scoped_refptr<VideoCaptureModule> VideoCaptureImpl::Create(
    const int32_t id,
    VideoCaptureExternal*& externalCapture) {
  rtc::scoped_refptr<VideoCaptureImpl> implementation(
      new rtc::RefCountedObject<VideoCaptureImpl>(id));
  externalCapture = implementation.get();
  return implementation;
}

const char* VideoCaptureImpl::CurrentDeviceName() const
{
    return _deviceUniqueId;
}

// static
int32_t VideoCaptureImpl::RotationFromDegrees(int degrees,
                                              VideoRotation* rotation) {
  switch (degrees) {
    case 0:
      *rotation = kVideoRotation_0;
      return 0;
    case 90:
      *rotation = kVideoRotation_90;
      return 0;
    case 180:
      *rotation = kVideoRotation_180;
      return 0;
    case 270:
      *rotation = kVideoRotation_270;
      return 0;
    default:
      return -1;;
  }
}

// static
int32_t VideoCaptureImpl::RotationInDegrees(VideoRotation rotation,
                                            int* degrees) {
  switch (rotation) {
    case kVideoRotation_0:
      *degrees = 0;
      return 0;
    case kVideoRotation_90:
      *degrees = 90;
      return 0;
    case kVideoRotation_180:
      *degrees = 180;
      return 0;
    case kVideoRotation_270:
      *degrees = 270;
      return 0;
  }
  return -1;
}

// returns the number of milliseconds until the module want a worker thread to call Process
int64_t VideoCaptureImpl::TimeUntilNextProcess()
{
    CriticalSectionScoped cs(&_callBackCs);
    const int64_t kProcessIntervalMs = 300;
    return kProcessIntervalMs -
           (rtc::TimeNanos() - _lastProcessTimeNanos) /
           rtc::kNumNanosecsPerMillisec;
}

// Process any pending tasks such as timeouts
void VideoCaptureImpl::Process()
{
    CriticalSectionScoped cs(&_callBackCs);

    const int64_t now_ns = rtc::TimeNanos();
    _lastProcessTimeNanos = rtc::TimeNanos();

    // Handle No picture alarm

    if (_lastProcessFrameTimeNanos == _incomingFrameTimesNanos[0] &&
        _captureAlarm != Raised)
    {
        if (_noPictureAlarmCallBack && _captureCallBack)
        {
            _captureAlarm = Raised;
            _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm);
        }
    }
    else if (_lastProcessFrameTimeNanos != _incomingFrameTimesNanos[0] &&
             _captureAlarm != Cleared)
    {
        if (_noPictureAlarmCallBack && _captureCallBack)
        {
            _captureAlarm = Cleared;
            _captureCallBack->OnNoPictureAlarm(_id, _captureAlarm);

        }
    }

    // Handle frame rate callback
    if ((now_ns - _lastFrameRateCallbackTimeNanos) /
        rtc::kNumNanosecsPerMillisec
        > kFrameRateCallbackInterval)
    {
        if (_frameRateCallBack && _captureCallBack)
        {
            const uint32_t frameRate = CalculateFrameRate(now_ns);
            _captureCallBack->OnCaptureFrameRate(_id, frameRate);
        }
        // Can be set by EnableFrameRateCallback
        _lastFrameRateCallbackTimeNanos = now_ns;

    }

    _lastProcessFrameTimeNanos = _incomingFrameTimesNanos[0];
}

VideoCaptureImpl::VideoCaptureImpl(const int32_t id)
    : _id(id),
      _deviceUniqueId(NULL),
      _apiCs(*CriticalSectionWrapper::CreateCriticalSection()),
      _captureDelay(0),
      _requestedCapability(),
      _callBackCs(*CriticalSectionWrapper::CreateCriticalSection()),
      _lastProcessTimeNanos(rtc::TimeNanos()),
      _lastFrameRateCallbackTimeNanos(rtc::TimeNanos()),
      _frameRateCallBack(false),
      _noPictureAlarmCallBack(false),
      _captureAlarm(Cleared),
      _setCaptureDelay(0),
      _dataCallBack(NULL),
      _captureCallBack(NULL),
      _lastProcessFrameTimeNanos(rtc::TimeNanos()),
      _rotateFrame(kVideoRotation_0),
      apply_rotation_(false) {
    _requestedCapability.width = kDefaultWidth;
    _requestedCapability.height = kDefaultHeight;
    _requestedCapability.maxFPS = 30;
    _requestedCapability.rawType = kVideoI420;
    _requestedCapability.codecType = kVideoCodecUnknown;
    memset(_incomingFrameTimesNanos, 0, sizeof(_incomingFrameTimesNanos));
}

VideoCaptureImpl::~VideoCaptureImpl()
{
    DeRegisterCaptureDataCallback();
    DeRegisterCaptureCallback();
    delete &_callBackCs;
    delete &_apiCs;

    if (_deviceUniqueId)
        delete[] _deviceUniqueId;
}

void VideoCaptureImpl::RegisterCaptureDataCallback(
    VideoCaptureDataCallback& dataCallBack) {
    CriticalSectionScoped cs(&_apiCs);
    CriticalSectionScoped cs2(&_callBackCs);
    _dataCallBack = &dataCallBack;
}

void VideoCaptureImpl::DeRegisterCaptureDataCallback() {
    CriticalSectionScoped cs(&_apiCs);
    CriticalSectionScoped cs2(&_callBackCs);
    _dataCallBack = NULL;
}
void VideoCaptureImpl::RegisterCaptureCallback(VideoCaptureFeedBack& callBack) {

    CriticalSectionScoped cs(&_apiCs);
    CriticalSectionScoped cs2(&_callBackCs);
    _captureCallBack = &callBack;
}
void VideoCaptureImpl::DeRegisterCaptureCallback() {

    CriticalSectionScoped cs(&_apiCs);
    CriticalSectionScoped cs2(&_callBackCs);
    _captureCallBack = NULL;
}
void VideoCaptureImpl::SetCaptureDelay(int32_t delayMS) {
    CriticalSectionScoped cs(&_apiCs);
    _captureDelay = delayMS;
}
int32_t VideoCaptureImpl::CaptureDelay()
{
    CriticalSectionScoped cs(&_apiCs);
    return _setCaptureDelay;
}

int32_t VideoCaptureImpl::DeliverCapturedFrame(VideoFrame& captureFrame) {
  UpdateFrameCount();  // frame count used for local frame rate callback.

  const bool callOnCaptureDelayChanged = _setCaptureDelay != _captureDelay;
  // Capture delay changed
  if (_setCaptureDelay != _captureDelay) {
      _setCaptureDelay = _captureDelay;
  }

  if (_dataCallBack) {
    if (callOnCaptureDelayChanged) {
      _dataCallBack->OnCaptureDelayChanged(_id, _captureDelay);
    }
    _dataCallBack->OnIncomingCapturedFrame(_id, captureFrame);
  }

  return 0;
}

int32_t VideoCaptureImpl::IncomingFrame(
    uint8_t* videoFrame,
    size_t videoFrameLength,
    const VideoCaptureCapability& frameInfo,
    int64_t captureTime/*=0*/)
{
    CriticalSectionScoped cs(&_apiCs);
    CriticalSectionScoped cs2(&_callBackCs);

    const int32_t width = frameInfo.width;
    const int32_t height = frameInfo.height;

    TRACE_EVENT1("webrtc", "VC::IncomingFrame", "capture_time", captureTime);

    if (frameInfo.codecType == kVideoCodecUnknown)
    {
        // Not encoded, convert to I420.
        const VideoType commonVideoType =
                  RawVideoTypeToCommonVideoVideoType(frameInfo.rawType);

        if (frameInfo.rawType != kVideoMJPEG &&
            CalcBufferSize(commonVideoType, width,
                           abs(height)) != videoFrameLength)
        {
            LOG(LS_ERROR) << "Wrong incoming frame length.";
            return -1;
        }

        int stride_y = width;
        int stride_uv = (width + 1) / 2;
        int target_width = width;
        int target_height = height;

        // SetApplyRotation doesn't take any lock. Make a local copy here.
        bool apply_rotation = apply_rotation_;

        if (apply_rotation) {
          // Rotating resolution when for 90/270 degree rotations.
          if (_rotateFrame == kVideoRotation_90 ||
              _rotateFrame == kVideoRotation_270) {
            target_width = abs(height);
            target_height = width;
          }
        }

        // Setting absolute height (in case it was negative).
        // In Windows, the image starts bottom left, instead of top left.
        // Setting a negative source height, inverts the image (within LibYuv).
        _captureFrame.CreateEmptyFrame(target_width,
                                       abs(target_height),
                                       stride_y,
                                       stride_uv, stride_uv);
        const int conversionResult = ConvertToI420(
            commonVideoType, videoFrame, 0, 0,  // No cropping
            width, height, videoFrameLength,
            apply_rotation ? _rotateFrame : kVideoRotation_0, &_captureFrame);
        if (conversionResult < 0)
        {
          LOG(LS_ERROR) << "Failed to convert capture frame from type "
                        << frameInfo.rawType << "to I420.";
            return -1;
        }

        if (!apply_rotation) {
          _captureFrame.set_rotation(_rotateFrame);
        } else {
          _captureFrame.set_rotation(kVideoRotation_0);
        }
        _captureFrame.set_ntp_time_ms(captureTime);
        _captureFrame.set_render_time_ms(rtc::TimeMillis());

        DeliverCapturedFrame(_captureFrame);
    }
    else // Encoded format
    {
        assert(false);
        return -1;
    }

    return 0;
}

int32_t VideoCaptureImpl::SetCaptureRotation(VideoRotation rotation) {
  CriticalSectionScoped cs(&_apiCs);
  CriticalSectionScoped cs2(&_callBackCs);
  _rotateFrame = rotation;
  return 0;
}

void VideoCaptureImpl::EnableFrameRateCallback(const bool enable) {
    CriticalSectionScoped cs(&_apiCs);
    CriticalSectionScoped cs2(&_callBackCs);
    _frameRateCallBack = enable;
    if (enable)
    {
      _lastFrameRateCallbackTimeNanos = rtc::TimeNanos();
    }
}

bool VideoCaptureImpl::SetApplyRotation(bool enable) {
  // We can't take any lock here as it'll cause deadlock with IncomingFrame.

  // The effect of this is the last caller wins.
  apply_rotation_ = enable;
  return true;
}

void VideoCaptureImpl::EnableNoPictureAlarm(const bool enable) {
    CriticalSectionScoped cs(&_apiCs);
    CriticalSectionScoped cs2(&_callBackCs);
    _noPictureAlarmCallBack = enable;
}

void VideoCaptureImpl::UpdateFrameCount()
{
  if (_incomingFrameTimesNanos[0] / rtc::kNumNanosecsPerMicrosec == 0)
    {
        // first no shift
    }
    else
    {
        // shift
        for (int i = (kFrameRateCountHistorySize - 2); i >= 0; i--)
        {
            _incomingFrameTimesNanos[i + 1] = _incomingFrameTimesNanos[i];
        }
    }
    _incomingFrameTimesNanos[0] = rtc::TimeNanos();
}

uint32_t VideoCaptureImpl::CalculateFrameRate(int64_t now_ns)
{
    int32_t num = 0;
    int32_t nrOfFrames = 0;
    for (num = 1; num < (kFrameRateCountHistorySize - 1); num++)
    {
        if (_incomingFrameTimesNanos[num] <= 0 ||
            (now_ns - _incomingFrameTimesNanos[num]) /
            rtc::kNumNanosecsPerMillisec >
                kFrameRateHistoryWindowMs) // don't use data older than 2sec
        {
            break;
        }
        else
        {
            nrOfFrames++;
        }
    }
    if (num > 1)
    {
        int64_t diff = (now_ns - _incomingFrameTimesNanos[num - 1]) /
                       rtc::kNumNanosecsPerMillisec;
        if (diff > 0)
        {
            return uint32_t((nrOfFrames * 1000.0f / diff) + 0.5f);
        }
    }

    return nrOfFrames;
}
}  // namespace videocapturemodule
}  // namespace webrtc


text:
/**
 * This class is generated by jOOQ
 */
package io.cattle.platform.core.model.tables.records;

/**
 * This class is generated by jOOQ.
 */
@javax.annotation.Generated(value    = { "http://www.jooq.org", "3.3.0" },
                            comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
@javax.persistence.Entity
@javax.persistence.Table(name = "vnet", schema = "cattle")
public class VnetRecord extends org.jooq.impl.UpdatableRecordImpl<io.cattle.platform.core.model.tables.records.VnetRecord> implements io.cattle.platform.db.jooq.utils.TableRecordJaxb, org.jooq.Record13<java.lang.Long, java.lang.String, java.lang.Long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.Date, java.util.Date, java.util.Date, java.util.Map<String,Object>, java.lang.String, java.lang.Long>, io.cattle.platform.core.model.Vnet {

	private static final long serialVersionUID = 1742356678;

	/**
	 * Setter for cattle.vnet.id.
	 */
	@Override
	public void setId(java.lang.Long value) {
		setValue(0, value);
	}

	/**
	 * Getter for cattle.vnet.id.
	 */
	@javax.persistence.Id
	@javax.persistence.Column(name = "id", unique = true, nullable = false, precision = 19)
	@Override
	public java.lang.Long getId() {
		return (java.lang.Long) getValue(0);
	}

	/**
	 * Setter for cattle.vnet.name.
	 */
	@Override
	public void setName(java.lang.String value) {
		setValue(1, value);
	}

	/**
	 * Getter for cattle.vnet.name.
	 */
	@javax.persistence.Column(name = "name", length = 255)
	@Override
	public java.lang.String getName() {
		return (java.lang.String) getValue(1);
	}

	/**
	 * Setter for cattle.vnet.account_id.
	 */
	@Override
	public void setAccountId(java.lang.Long value) {
		setValue(2, value);
	}

	/**
	 * Getter for cattle.vnet.account_id.
	 */
	@javax.persistence.Column(name = "account_id", precision = 19)
	@Override
	public java.lang.Long getAccountId() {
		return (java.lang.Long) getValue(2);
	}

	/**
	 * Setter for cattle.vnet.kind.
	 */
	@Override
	public void setKind(java.lang.String value) {
		setValue(3, value);
	}

	/**
	 * Getter for cattle.vnet.kind.
	 */
	@javax.persistence.Column(name = "kind", nullable = false, length = 255)
	@Override
	public java.lang.String getKind() {
		return (java.lang.String) getValue(3);
	}

	/**
	 * Setter for cattle.vnet.uuid.
	 */
	@Override
	public void setUuid(java.lang.String value) {
		setValue(4, value);
	}

	/**
	 * Getter for cattle.vnet.uuid.
	 */
	@javax.persistence.Column(name = "uuid", unique = true, nullable = false, length = 128)
	@Override
	public java.lang.String getUuid() {
		return (java.lang.String) getValue(4);
	}

	/**
	 * Setter for cattle.vnet.description.
	 */
	@Override
	public void setDescription(java.lang.String value) {
		setValue(5, value);
	}

	/**
	 * Getter for cattle.vnet.description.
	 */
	@javax.persistence.Column(name = "description", length = 1024)
	@Override
	public java.lang.String getDescription() {
		return (java.lang.String) getValue(5);
	}

	/**
	 * Setter for cattle.vnet.state.
	 */
	@Override
	public void setState(java.lang.String value) {
		setValue(6, value);
	}

	/**
	 * Getter for cattle.vnet.state.
	 */
	@javax.persistence.Column(name = "state", nullable = false, length = 128)
	@Override
	public java.lang.String getState() {
		return (java.lang.String) getValue(6);
	}

	/**
	 * Setter for cattle.vnet.created.
	 */
	@Override
	public void setCreated(java.util.Date value) {
		setValue(7, value);
	}

	/**
	 * Getter for cattle.vnet.created.
	 */
	@javax.persistence.Column(name = "created")
	@Override
	public java.util.Date getCreated() {
		return (java.util.Date) getValue(7);
	}

	/**
	 * Setter for cattle.vnet.removed.
	 */
	@Override
	public void setRemoved(java.util.Date value) {
		setValue(8, value);
	}

	/**
	 * Getter for cattle.vnet.removed.
	 */
	@javax.persistence.Column(name = "removed")
	@Override
	public java.util.Date getRemoved() {
		return (java.util.Date) getValue(8);
	}

	/**
	 * Setter for cattle.vnet.remove_time.
	 */
	@Override
	public void setRemoveTime(java.util.Date value) {
		setValue(9, value);
	}

	/**
	 * Getter for cattle.vnet.remove_time.
	 */
	@javax.persistence.Column(name = "remove_time")
	@Override
	public java.util.Date getRemoveTime() {
		return (java.util.Date) getValue(9);
	}

	/**
	 * Setter for cattle.vnet.data.
	 */
	@Override
	public void setData(java.util.Map<String,Object> value) {
		setValue(10, value);
	}

	/**
	 * Getter for cattle.vnet.data.
	 */
	@javax.persistence.Column(name = "data", length = 16777215)
	@Override
	public java.util.Map<String,Object> getData() {
		return (java.util.Map<String,Object>) getValue(10);
	}

	/**
	 * Setter for cattle.vnet.uri.
	 */
	@Override
	public void setUri(java.lang.String value) {
		setValue(11, value);
	}

	/**
	 * Getter for cattle.vnet.uri.
	 */
	@javax.persistence.Column(name = "uri", length = 255)
	@Override
	public java.lang.String getUri() {
		return (java.lang.String) getValue(11);
	}

	/**
	 * Setter for cattle.vnet.network_id.
	 */
	@Override
	public void setNetworkId(java.lang.Long value) {
		setValue(12, value);
	}

	/**
	 * Getter for cattle.vnet.network_id.
	 */
	@javax.persistence.Column(name = "network_id", precision = 19)
	@Override
	public java.lang.Long getNetworkId() {
		return (java.lang.Long) getValue(12);
	}

	// -------------------------------------------------------------------------
	// Primary key information
	// -------------------------------------------------------------------------

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Record1<java.lang.Long> key() {
		return (org.jooq.Record1) super.key();
	}

	// -------------------------------------------------------------------------
	// Record13 type implementation
	// -------------------------------------------------------------------------

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Row13<java.lang.Long, java.lang.String, java.lang.Long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.Date, java.util.Date, java.util.Date, java.util.Map<String,Object>, java.lang.String, java.lang.Long> fieldsRow() {
		return (org.jooq.Row13) super.fieldsRow();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Row13<java.lang.Long, java.lang.String, java.lang.Long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.Date, java.util.Date, java.util.Date, java.util.Map<String,Object>, java.lang.String, java.lang.Long> valuesRow() {
		return (org.jooq.Row13) super.valuesRow();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.lang.Long> field1() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.ID;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.lang.String> field2() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.NAME;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.lang.Long> field3() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.ACCOUNT_ID;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.lang.String> field4() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.KIND;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.lang.String> field5() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.UUID;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.lang.String> field6() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.DESCRIPTION;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.lang.String> field7() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.STATE;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.util.Date> field8() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.CREATED;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.util.Date> field9() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.REMOVED;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.util.Date> field10() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.REMOVE_TIME;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.util.Map<String,Object>> field11() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.DATA;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.lang.String> field12() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.URI;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public org.jooq.Field<java.lang.Long> field13() {
		return io.cattle.platform.core.model.tables.VnetTable.VNET.NETWORK_ID;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.lang.Long value1() {
		return getId();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.lang.String value2() {
		return getName();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.lang.Long value3() {
		return getAccountId();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.lang.String value4() {
		return getKind();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.lang.String value5() {
		return getUuid();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.lang.String value6() {
		return getDescription();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.lang.String value7() {
		return getState();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.util.Date value8() {
		return getCreated();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.util.Date value9() {
		return getRemoved();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.util.Date value10() {
		return getRemoveTime();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.util.Map<String,Object> value11() {
		return getData();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.lang.String value12() {
		return getUri();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public java.lang.Long value13() {
		return getNetworkId();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value1(java.lang.Long value) {
		setId(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value2(java.lang.String value) {
		setName(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value3(java.lang.Long value) {
		setAccountId(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value4(java.lang.String value) {
		setKind(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value5(java.lang.String value) {
		setUuid(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value6(java.lang.String value) {
		setDescription(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value7(java.lang.String value) {
		setState(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value8(java.util.Date value) {
		setCreated(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value9(java.util.Date value) {
		setRemoved(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value10(java.util.Date value) {
		setRemoveTime(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value11(java.util.Map<String,Object> value) {
		setData(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value12(java.lang.String value) {
		setUri(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord value13(java.lang.Long value) {
		setNetworkId(value);
		return this;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public VnetRecord values(java.lang.Long value1, java.lang.String value2, java.lang.Long value3, java.lang.String value4, java.lang.String value5, java.lang.String value6, java.lang.String value7, java.util.Date value8, java.util.Date value9, java.util.Date value10, java.util.Map<String,Object> value11, java.lang.String value12, java.lang.Long value13) {
		return this;
	}

	// -------------------------------------------------------------------------
	// FROM and INTO
	// -------------------------------------------------------------------------

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void from(io.cattle.platform.core.model.Vnet from) {
		setId(from.getId());
		setName(from.getName());
		setAccountId(from.getAccountId());
		setKind(from.getKind());
		setUuid(from.getUuid());
		setDescription(from.getDescription());
		setState(from.getState());
		setCreated(from.getCreated());
		setRemoved(from.getRemoved());
		setRemoveTime(from.getRemoveTime());
		setData(from.getData());
		setUri(from.getUri());
		setNetworkId(from.getNetworkId());
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public <E extends io.cattle.platform.core.model.Vnet> E into(E into) {
		into.from(this);
		return into;
	}

	// -------------------------------------------------------------------------
	// Constructors
	// -------------------------------------------------------------------------

	/**
	 * Create a detached VnetRecord
	 */
	public VnetRecord() {
		super(io.cattle.platform.core.model.tables.VnetTable.VNET);
	}

	/**
	 * Create a detached, initialised VnetRecord
	 */
	public VnetRecord(java.lang.Long id, java.lang.String name, java.lang.Long accountId, java.lang.String kind, java.lang.String uuid, java.lang.String description, java.lang.String state, java.util.Date created, java.util.Date removed, java.util.Date removeTime, java.util.Map<String,Object> data, java.lang.String uri, java.lang.Long networkId) {
		super(io.cattle.platform.core.model.tables.VnetTable.VNET);

		setValue(0, id);
		setValue(1, name);
		setValue(2, accountId);
		setValue(3, kind);
		setValue(4, uuid);
		setValue(5, description);
		setValue(6, state);
		setValue(7, created);
		setValue(8, removed);
		setValue(9, removeTime);
		setValue(10, data);
		setValue(11, uri);
		setValue(12, networkId);
	}
}


text:
package org.jasig.schedassist.impl.events;

import net.fortuna.ical4j.model.component.VEvent;

import org.jasig.schedassist.model.AvailableBlock;
import org.jasig.schedassist.model.IScheduleOwner;
import org.jasig.schedassist.model.IScheduleVisitor;

/**
 * {@link AbstractAppointmentEvent} raised when someone joins a
 * multiple visitor appointment.
 *
 * @author Nicholas Blair, nblair@doit.wisc.edu
 * @version $Id: AppointmentJoinedEvent.java 2103 2010-05-11 17:45:27Z npblair $
 */
public class AppointmentJoinedEvent extends AbstractAppointmentEvent {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * @param event
	 * @param owner
	 * @param visitor
	 * @param block
	 */
	public AppointmentJoinedEvent(VEvent event, IScheduleOwner owner,
			IScheduleVisitor visitor, AvailableBlock block) {
		super(event, owner, visitor, block);
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Philipp. J. Sci. , C, Bot. 13: 382 (1918)

#### Original name
Helminthosporium ficuum H.S. Yates

### Remarks
null


text:
module LambdaCat.Supplier
    (
      -- * Class and wrapper
      SupplierClass (..)

      -- * Callback type
    , Callback

      -- * Supplying for views
    , supplyForView
    , supplyForDownload
    )
where

import Data.List
    ( find
    )
import Data.Maybe
    ( isJust
    )
import Network.URI

import LambdaCat.Configure
import LambdaCat.Internal.Class

-- | Selects a proper supplier for the given URI.
supplyForView
    :: (Callback ui meta -> IO ())
    -> (View -> Callback ui meta)
    -> URI
    -> IO ()
supplyForView callbackHdl embedHdl uri = do
    let suppliers = supplierList lambdaCatConf
        uri'      = modifySupplierURI lambdaCatConf uri
        protocol  = uriScheme uri'
        mSupply   = find (\(SupplierSpec _ ps) -> isJust $ find (== protocol) ps)
                         suppliers

    case mSupply of
        Just (SupplierSpec conf _) -> do
            mView <- supplyView conf uri'

            case mView of
                Just view ->
                    callbackHdl $ embedHdl view

                Nothing ->
                    putStrLn $ "Load view for unhandled uri" ++ show uri'

        Nothing ->
            putStrLn $ "Can't find a supplier for protocol:" ++ protocol

supplyForDownload :: URI -> IO Bool
supplyForDownload uri = do
     let suppliers = downloadHook lambdaCatConf
         uri'      = modifySupplierURI lambdaCatConf uri
         protocol  = uriScheme uri'
     findDownloadSupplier protocol suppliers
  where
    findDownloadSupplier _        [] = return False
    findDownloadSupplier protocol ((SupplierSpec conf ps):suppliers) = do
                if (isJust $ find (== protocol) ps)
                    then do accept <- supplyDownload conf uri
                            if accept
                                then return True
                                else findDownloadSupplier protocol suppliers
                    else findDownloadSupplier protocol suppliers


text:
package org.apache.spark.scheduler.cluster.k8s

import java.util.Date

import org.scalatest.PrivateMethodTester

import org.apache.spark.SparkFunSuite
import org.apache.spark.deploy.k8s.Config.ExecutorRollPolicy
import org.apache.spark.executor.ExecutorMetrics
import org.apache.spark.status.api.v1.ExecutorSummary

class ExecutorRollPluginSuite extends SparkFunSuite with PrivateMethodTester {

  val plugin = new ExecutorRollPlugin().driverPlugin()

  private val _choose = PrivateMethod[Option[String]](Symbol("choose"))

  val metrics = Some(new ExecutorMetrics(
    Map("JVMHeapMemory" -> 1024L, "JVMOffHeapMemory" -> 1024L)))

  val driverSummary = new ExecutorSummary("driver", "host:port", true, 1,
    10, 10, 1, 1, 1,
    0, 0, 1, 100,
    1, 100, 100,
    10, false, 20, new Date(1639300000000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(), metrics, Map(), Map(), 1,
    false, Set())

  val execWithSmallestID = new ExecutorSummary("1", "host:port", true, 1,
    10, 10, 1, 1, 1,
    0, 0, 1, 100,
    20, 100, 100,
    10, false, 20, new Date(1639300001000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(), metrics, Map(), Map(), 1,
    false, Set())

  // The smallest addTime
  val execWithSmallestAddTime = new ExecutorSummary("2", "host:port", true, 1,
    10, 10, 1, 1, 1,
    0, 0, 1, 100,
    20, 100, 100,
    10, false, 20, new Date(1639300000000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(), metrics, Map(), Map(), 1,
    false, Set())

  // The biggest totalGCTime
  val execWithBiggestTotalGCTime = new ExecutorSummary("3", "host:port", true, 1,
    10, 10, 1, 1, 1,
    0, 0, 1, 100,
    40, 100, 100,
    10, false, 20, new Date(1639300002000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(), metrics, Map(), Map(), 1,
    false, Set())

  // The biggest totalDuration
  val execWithBiggestTotalDuration = new ExecutorSummary("4", "host:port", true, 1,
    10, 10, 1, 1, 1,
    0, 0, 4, 400,
    20, 100, 100,
    10, false, 20, new Date(1639300003000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(), metrics, Map(), Map(), 1,
    false, Set())

  // The biggest failedTasks
  val execWithBiggestFailedTasks = new ExecutorSummary("5", "host:port", true, 1,
    10, 10, 1, 1, 1,
    5, 0, 1, 100,
    20, 100, 100,
    10, false, 20, new Date(1639300003000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(), metrics, Map(), Map(), 1,
    false, Set())

  // The biggest average duration (= totalDuration / totalTask)
  val execWithBiggestAverageDuration = new ExecutorSummary("6", "host:port", true, 1,
    10, 10, 1, 1, 1,
    0, 0, 2, 300,
    20, 100, 100,
    10, false, 20, new Date(1639300003000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(), metrics, Map(), Map(), 1,
    false, Set())

  // The executor with no tasks
  val execWithoutTasks = new ExecutorSummary("7", "host:port", true, 1,
    0, 0, 1, 0, 0,
    0, 0, 0, 0,
    0, 0, 0,
    0, false, 0, new Date(1639300001000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(), metrics, Map(), Map(), 1,
    false, Set())

  // This is used to stabilize 'mean' and 'sd' in OUTLIER test cases.
  val execNormal = new ExecutorSummary("8", "host:port", true, 1,
    10, 10, 1, 1, 1,
    4, 0, 2, 280,
    30, 100, 100,
    10, false, 20, new Date(1639300001000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(),
    Some(new ExecutorMetrics(Map("JVMHeapMemory" -> 1200L, "JVMOffHeapMemory" -> 1200L))),
    Map(), Map(), 1,
    false, Set())

  val execWithTwoDigitID = new ExecutorSummary("10", "host:port", true, 1,
    10, 10, 1, 1, 1,
    4, 0, 2, 280,
    30, 100, 100,
    10, false, 20, new Date(1639300001000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(), metrics, Map(), Map(), 1,
    false, Set())

  val execWithBiggestPeakJVMOnHeapMemory = new ExecutorSummary("11", "host:port", true, 1,
    10, 10, 1, 1, 1,
    4, 0, 2, 280,
    30, 100, 100,
    10, false, 20, new Date(1639300001000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(),
    Some(new ExecutorMetrics(Map("JVMHeapMemory" -> 1201L, "JVMOffHeapMemory" -> 1200L))),
    Map(), Map(), 1, false, Set())

  val execWithBiggestPeakJVMOffHeapMemory = new ExecutorSummary("12", "host:port", true, 1,
    10, 10, 1, 1, 1,
    4, 0, 2, 280,
    30, 100, 100,
    10, false, 20, new Date(1639300001000L),
    Option.empty, Option.empty, Map(), Option.empty, Set(),
    Some(new ExecutorMetrics(Map("JVMHeapMemory" -> 1200L, "JVMOffHeapMemory" -> 1201L))),
    Map(), Map(), 1, false, Set())

  val list = Seq(driverSummary, execWithSmallestID, execWithSmallestAddTime,
    execWithBiggestTotalGCTime, execWithBiggestTotalDuration, execWithBiggestFailedTasks,
    execWithBiggestAverageDuration, execWithoutTasks, execNormal, execWithTwoDigitID,
    execWithBiggestPeakJVMOnHeapMemory, execWithBiggestPeakJVMOffHeapMemory)

  override def beforeEach(): Unit = {
    super.beforeEach()
    plugin.asInstanceOf[ExecutorRollDriverPlugin].minTasks = 0
  }

  test("Empty executor list") {
    ExecutorRollPolicy.values.foreach { value =>
      assert(plugin.invokePrivate[Option[String]](_choose(Seq.empty, value)).isEmpty)
    }
  }

  test("Driver summary should be ignored") {
    ExecutorRollPolicy.values.foreach { value =>
      assert(plugin.invokePrivate(_choose(Seq(driverSummary), value)).isEmpty)
    }
  }

  test("A one-item executor list") {
    ExecutorRollPolicy.values.filter(_ != ExecutorRollPolicy.OUTLIER_NO_FALLBACK).foreach { value =>
      assert(
        plugin.invokePrivate(_choose(Seq(execWithSmallestID), value))
          .contains(execWithSmallestID.id))
    }
  }

  test("SPARK-37806: All policy should ignore executor if totalTasks < minTasks") {
    plugin.asInstanceOf[ExecutorRollDriverPlugin].minTasks = 1000
    ExecutorRollPolicy.values.foreach { value =>
      assert(plugin.invokePrivate(_choose(list, value)).isEmpty)
    }
  }

  test("Policy: ID") {
    assert(plugin.invokePrivate(_choose(list, ExecutorRollPolicy.ID)).contains("1"))
    assert(plugin.invokePrivate(_choose(list.filter(_.id != "1"), ExecutorRollPolicy.ID))
      .contains("2"))
  }

  test("Policy: ADD_TIME") {
    assert(plugin.invokePrivate(_choose(list, ExecutorRollPolicy.ADD_TIME)).contains("2"))
  }

  test("Policy: TOTAL_GC_TIME") {
    assert(plugin.invokePrivate(_choose(list, ExecutorRollPolicy.TOTAL_GC_TIME)).contains("3"))
  }

  test("Policy: TOTAL_DURATION") {
    assert(plugin.invokePrivate(_choose(list, ExecutorRollPolicy.TOTAL_DURATION)).contains("4"))
  }

  test("Policy: FAILED_TASKS") {
    assert(plugin.invokePrivate(_choose(list, ExecutorRollPolicy.FAILED_TASKS)).contains("5"))
  }

  test("Policy: AVERAGE_DURATION") {
    assert(plugin.invokePrivate(_choose(list, ExecutorRollPolicy.AVERAGE_DURATION)).contains("6"))
  }

  test("Policy: PEAK_JVM_ONHEAP_MEMORY") {
    assert(plugin.invokePrivate(
      _choose(list, ExecutorRollPolicy.PEAK_JVM_ONHEAP_MEMORY)).contains("11"))
  }

  test("Policy: PEAK_JVM_OFFHEAP_MEMORY") {
    assert(plugin.invokePrivate(
      _choose(list, ExecutorRollPolicy.PEAK_JVM_OFFHEAP_MEMORY)).contains("12"))
  }

  test("Policy: OUTLIER - Work like TOTAL_DURATION if there is no outlier") {
    assert(
      plugin.invokePrivate(_choose(list, ExecutorRollPolicy.TOTAL_DURATION)) ==
        plugin.invokePrivate(_choose(list, ExecutorRollPolicy.OUTLIER)))
  }

  test("Policy: OUTLIER - Detect an average task duration outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1, 300,
      20, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(), Option.empty, Map(), Map(), 1,
      false, Set())
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.AVERAGE_DURATION)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER)))
  }

  test("Policy: OUTLIER - Detect a total task duration outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1000, 1000,
      0, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(), Option.empty, Map(), Map(), 1,
      false, Set())
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.TOTAL_DURATION)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER)))
  }

  test("Policy: OUTLIER - Detect a total GC time outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1, 100,
      1000, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(), Option.empty, Map(), Map(), 1,
      false, Set())
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.TOTAL_GC_TIME)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER)))
  }

  test("Policy: OUTLIER - Detect a peak JVM on-heap memory outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1, 100,
      1000, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(),
      Some(new ExecutorMetrics(Map("JVMHeapMemory" -> 2048L, "JVMOffHeapMemory" -> 1200L))),
      Map(), Map(), 1,
      false, Set())
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.PEAK_JVM_ONHEAP_MEMORY)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER)))
  }

  test("Policy: OUTLIER - Detect a peak JVM off-heap memory outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1, 100,
      1000, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(),
      Some(new ExecutorMetrics(Map("JVMHeapMemory" -> 1024L, "JVMOffHeapMemory" -> 2048L))),
      Map(), Map(), 1,
      false, Set())
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.PEAK_JVM_OFFHEAP_MEMORY)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER)))
  }

  test("Policy: OUTLIER_NO_FALLBACK - Return None if there are no outliers") {
    assert(plugin.invokePrivate(_choose(list, ExecutorRollPolicy.OUTLIER_NO_FALLBACK)).isEmpty)
  }

  test("Policy: OUTLIER_NO_FALLBACK - Detect an average task duration outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1, 300,
      20, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(), Option.empty, Map(), Map(), 1,
      false, Set())
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.AVERAGE_DURATION)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER_NO_FALLBACK)))
  }

  test("Policy: OUTLIER_NO_FALLBACK - Detect a total task duration outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1000, 1000,
      0, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(), Option.empty, Map(), Map(), 1,
      false, Set())
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.TOTAL_DURATION)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER_NO_FALLBACK)))
  }

  test("Policy: OUTLIER_NO_FALLBACK - Detect a total GC time outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1, 100,
      1000, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(), Option.empty, Map(), Map(), 1,
      false, Set())
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.TOTAL_GC_TIME)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER_NO_FALLBACK)))
  }

  test("Policy: OUTLIER_NO_FALLBACK - Detect a peak JVM on-heap memory outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1, 100,
      0, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(),
      Some(new ExecutorMetrics(Map("JVMHeapMemory" -> 2048L, "JVMOffHeapMemory" -> 1200L))),
      Map(), Map(), 1,
      false, Set())
    val x = plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.TOTAL_GC_TIME))
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.PEAK_JVM_ONHEAP_MEMORY)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER_NO_FALLBACK)))
  }

  test("Policy: OUTLIER_NO_FALLBACK - Detect a peak JVM off-heap memory outlier") {
    val outlier = new ExecutorSummary("9999", "host:port", true, 1,
      0, 0, 1, 0, 0,
      3, 0, 1, 100,
      0, 0, 0,
      0, false, 0, new Date(1639300001000L),
      Option.empty, Option.empty, Map(), Option.empty, Set(),
      Some(new ExecutorMetrics(Map("JVMHeapMemory" -> 1024L, "JVMOffHeapMemory" -> 2048L))),
      Map(), Map(), 1,
      false, Set())
    assert(
      plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.PEAK_JVM_OFFHEAP_MEMORY)) ==
        plugin.invokePrivate(_choose(list :+ outlier, ExecutorRollPolicy.OUTLIER_NO_FALLBACK)))
  }
}


text:
<?php
namespace Jd\Request;
class PopOtoCheckNumberConsumerRequest
{
	private $apiParas = array();

	public function getApiMethodName(){
	  return "jingdong.pop.oto.CheckNumber.consumer";
	}

	public function getApiParas(){
		return json_encode($this->apiParas);
	}

	public function check(){

	}

	public function putOtherTextParam($key, $value){
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
                                    	                        	                  private $orderId;

	public function setOrderId($orderId){
		$this->orderId = $orderId;
         $this->apiParas["order_id"] = $orderId;
	}

	public function getOrderId(){
	  return $this->orderId;
	}

                        	                   			private $cardNumber;

	public function setCardNumber($cardNumber){
		$this->cardNumber = $cardNumber;
         $this->apiParas["card_number"] = $cardNumber;
	}

	public function getCardNumber(){
	  return $this->cardNumber;
	}

                        	                   			private $pwdUmber;

	public function setPwdUmber($pwdUmber){
		$this->pwdUmber = $pwdUmber;
         $this->apiParas["pwd_umber"] = $pwdUmber;
	}

	public function getPwdUmber(){
	  return $this->pwdUmber;
	}

                        	                   			private $shopId;

	public function setShopId($shopId){
		$this->shopId = $shopId;
         $this->apiParas["shop_id"] = $shopId;
	}

	public function getShopId(){
	  return $this->shopId;
	}

                        	                   			private $shopName;

	public function setShopName($shopName){
		$this->shopName = $shopName;
         $this->apiParas["shop_name"] = $shopName;
	}

	public function getShopName(){
	  return $this->shopName;
	}

                        	                   			private $codeType;

	public function setCodeType($codeType){
		$this->codeType = $codeType;
         $this->apiParas["code_type"] = $codeType;
	}

	public function getCodeType(){
	  return $this->codeType;
	}

}


text:
package io.elssa.net;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

@ChannelHandler.Sharable
public class MessageEncoder extends MessageToByteEncoder<ElssaMessage> {

    @Override
    protected void encode(
            ChannelHandlerContext ctx, ElssaMessage msg, ByteBuf out) {
        byte[] payload = msg.payload();
        out.writeInt(payload.length);
        out.writeBytes(payload);
    }

}


text:
import org.json.JSONArray;
import org.json.JSONObject;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.PingEvent;
import org.pircbotx.hooks.types.GenericMessageEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Bot extends ListenerAdapter {

	//Mods usernames must be lowercase
	private List<String> mods = new ArrayList<>();

	public Bot() {
		mods.add("yourname");
	}

	//This will return the response from the command
	private String runCommands(GenericMessageEvent event, String command) {
		if(command.equalsIgnoreCase("!raffle") && mods.contains(event.getUser().getNick())) {
			try {
				List<String> temp = new ArrayList<>();
				JSONObject json = new JSONObject(JSONParser.readUrl(String.format("https://tmi.twitch.tv/group/user/%s/chatters", Main.CHANNEL)));
				JSONArray viewers = json.getJSONObject("chatters").getJSONArray("viewers");
				for (int j = 0; j < viewers.length(); j++) {
					temp.add(viewers.getString(j));
				}
				JSONArray mods = json.getJSONObject("chatters").getJSONArray("moderators");
				for (int j = 0; j < mods.length(); j++) {
					temp.add(mods.getString(j));
				}

				Random random = new Random();
				return String.format("Congratulations %s! You won the raffle!", temp.get(random.nextInt(temp.size())));
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if(command.equalsIgnoreCase("!schedule")) {
			return "This is an example bot, replace this text with your schedule text";
		}

		return null;
	}

	/**
	 * PircBotx will return the exact message sent and not the raw line
	 */
	@Override
	public void onGenericMessage(GenericMessageEvent event) throws Exception {
		String message = event.getMessage();
		String command = getCommandFromMessage(message);

		String response = runCommands(event, command);
		if(response != null) sendMessage(response);
	}

	/**
	 * The command will always be the first part of the message
	 * We can split the string into parts by spaces to get each word
	 * The first word if it starts with our command notifier "!" will get returned
	 * Otherwise it will return null
	 */
	private String getCommandFromMessage(String message) {
		String[] msgParts = message.split(" ");
		if (msgParts[0].startsWith("!")) {
			return msgParts[0];
		} else {
			return null;
		}
	}

	/**
	 * We MUST respond to this or else we will get kicked
	 */
	@Override
	public void onPing(PingEvent event) throws Exception {
		Main.bot.sendRaw().rawLineNow(String.format("PONG %s\r\n", event.getPingValue()));
	}

	private void sendMessage(String message) {
		Main.bot.sendIRC().message("#" + Main.CHANNEL, message);
	}
}


text:
define(['bluebird', 'marked', 'kb_common_ts/HttpClient', './lib/utils', 'kb_common_ts/Auth2'], function (
    Promise,
    marked,
    M_HttpClient,
    Utils,
    auth2
) {
    'use strict';

    function factory(config) {
        var runtime = config.runtime;
        var policies = null;
        var userAgreements = null;
        var utils = Utils.make({
            runtime: runtime
        });

        const auth2Client = new auth2.Auth2({
            baseUrl: runtime.config('services.auth.url')
        });
        const currentUserToken = runtime.service('session').getAuthToken();

        function getPolicyFile(arg) {
            var http = new M_HttpClient.HttpClient();
            var policyVersion = getPolicyVersion(arg.id, arg.version);
            var url = [window.location.origin + runtime.pluginResourcePath, 'agreements', arg.id, policyVersion.file].join('/');
            return http
                .request({
                    method: 'GET',
                    url: url
                })
                .then(function (result) {
                    if (result.status === 200) {
                        try {
                            return marked(result.response);
                        } catch (ex) {
                            throw new Error('Error formatting agreement file: ' + ex.message);
                        }
                    } else {
                        console.error('ERROR', result);
                        throw new Error('Error fetching agreement: ' + result.status);
                    }
                });
        }

        function loadPolicies() {
            var url = [window.location.origin + runtime.pluginResourcePath, 'agreements', 'policies.json'].join('/');
            var http = new M_HttpClient.HttpClient();
            return http
                .request({
                    method: 'GET',
                    url: url
                })
                .then(function (result) {
                    if (result.status === 200) {
                        return JSON.parse(result.response);
                    } else {
                        throw new Error('Error fetching index: ' + result.status);
                    }
                });
        }

        function getLatestPolicies() {
            return policies.map(function (policy) {
                var latestVersionId = Math.max.apply(
                    null,
                    policy.versions.map(function (version) {
                        return version.version;
                    })
                );
                // Array.from not supported in IE
                // TODO: use es6 polyfill lib
                var latestVersion = policy.versions.filter(function (version) {
                    return version.version === latestVersionId;
                })[0];

                return {
                    id: policy.id,
                    title: policy.title,
                    version: latestVersion.version,
                    date: latestVersion.date,
                    file: latestVersion.file
                };
            });
        }

        function getPolicy(id) {
            return policies.filter(function (policy) {
                return policy.id === id;
            })[0];
        }

        function getPolicyVersion(id, version) {
            var policy = getPolicy(id);
            if (!policy) {
                return;
            }

            return policy.versions.filter(function (ver) {
                return version === ver.version;
            })[0];
        }

        function getUserAgreements() {
            return userAgreements;
        }

        function start() {
            return loadPolicies()
                .then(function (result) {
                    policies = result;
                    return auth2Client.getMe(currentUserToken);
                })
                .then(function (account) {
                    userAgreements = utils.parsePolicyAgreements(account.policyids);
                });
        }

        function stop() {
            return Promise.try(function () { });
        }

        return {
            start: start,
            stop: stop,
            // user agreements
            getUserAgreements: getUserAgreements,

            // policies
            getPolicyFile: getPolicyFile,
            loadPolicies: loadPolicies,
            getPolicy: getPolicy,
            getPolicyVersion: getPolicyVersion,
            getLatestPolicies: getLatestPolicies
        };
    }

    return {
        make: function (config) {
            return factory(config);
        }
    };
});