text:
from environmentbase.template import Template
import environmentbase.resources as res
from environmentbase.networkbase import NetworkBase
from troposphere import Ref, Parameter, GetAtt, Output, Join, rds, ec2

class RDS(Template):
    """
    Adds an RDS instance.
    """

    # default configuration values
    DEFAULT_CONFIG = {
        'db': {
            # Database label
            'mydb': {
                'db_instance_type_default': 'db.m1.small',
                'rds_user_name': 'defaultusername',
                # Actual database name, cannot include non-alphanumeric characters (e.g. '-')
                'master_db_name': 'mydb',
                'volume_size': 100,
                'backup_retention_period': 30,
                'rds_engine': 'MySQL',
                # 5.6.19 is no longer supported
                'rds_engine_version': '5.6.22',
                'preferred_backup_window': '02:00-02:30',
                'preferred_maintenance_window': 'sun:03:00-sun:04:00',
                # Name of vm snapshot to use, empty string ('') means don't use an old snapshot
                # Note: 'master_db_name' value will be overridden if snapshot_id is non-empty
                'snapshot_id': '',
                # Empty string is ignored, requiring manual parameter binding instead
                'password': 'changeme',
                'multi_az': True
            }
        }
    }

    # schema of expected types for config values
    CONFIG_SCHEMA = {
        'db': {
            '*': {
                'db_instance_type_default': 'str',
                'rds_user_name': 'str',
                'master_db_name': 'str',
                'volume_size': 'int',
                'backup_retention_period': 'int',
                'rds_engine': 'str',
                'rds_engine_version': 'str',
                'preferred_backup_window': 'str',
                'preferred_maintenance_window': 'str',
                'snapshot_id': 'str',
                'password': 'str'
            }
        }
    }

    def __init__(self,
                 tier_name,
                 connect_from_cidr=None,
                 connect_from_sg=None,
                 subnet_set='private',
                 config_map=DEFAULT_CONFIG['db']):
        """
        Method initializes host in a given environment deployment
        @param tier_name: [string] - name of the tier to assign
        @param connect_from_cidr: [Ref|string] - CIDR notation for external access to RDS instance. Cannot be used in conjunction with connect_from_sg. If neither setting is used the CIDR of the VPC will be used.
        @param connect_from_sg: [Ref|string] - Name of security group allowed to access RDS instance. Cannot be used in conjunction with connect_from_cidr.
        @param subnet_set: 'public' or 'private', Type of subnets to use
        @param config_map: map of database config settings to be deployed.
        """

        self.tier_name = tier_name
        self.config_map = config_map
        self.subnet_set = subnet_set

        if connect_from_cidr and connect_from_sg:
            raise ValueError("RDS instance cannot be configured to be accessible from both CIDR and security group.")

        self.connect_from_cidr = connect_from_cidr
        self.connect_from_sg = connect_from_sg

        self.data = {}

        super(RDS, self).__init__(template_name=tier_name+'RDSInstance')

    # When no config.json file exists a new one is created using the 'factory default' file.  This function
    # augments the factory default before it is written to file with the config values required
    @staticmethod
    def get_factory_defaults():
        return RDS.DEFAULT_CONFIG

    # When the user request to 'create' a new RDS template the config.json file is read in. This file is checked to
    # ensure all required values are present. Because RDS has additional requirements beyond that of
    # EnvironmentBase this function is used to add additional validation checks.
    @staticmethod
    def get_config_schema():
        return RDS.CONFIG_SCHEMA

    def add_parameters(self, db_label, db_config):
        instance_type_param = self.add_parameter(Parameter(
            db_label.lower() + self.tier_name.title() + 'RdsInstanceType',
            Default=db_config.get('db_instance_type_default'),
            Type='String',
            Description='DB Instance Type for the RDS instance.',
            AllowedValues=res.COMMON_STRINGS.get('valid_db_instance_types'),
            ConstraintDescription=res.COMMON_STRINGS.get('valid_db_instance_type_message')))

        name_param = self.add_parameter(Parameter(
            db_label.lower() + self.tier_name.title() + 'RdsDbName',
            Type='String',
            Default=db_config.get('master_db_name'),
            Description='Master RDS database name for the RDS instance.',
            MinLength=3,
            MaxLength=32,
            ConstraintDescription='must be 3 or more characters and not longer than 64 characters.'))

        user_name_param = self.add_parameter(Parameter(
            db_label.lower() + self.tier_name.title() + 'RdsUserName',
            Default=db_config.get('rds_user_name'),
            Type='String',
            Description='Master RDS User name for the RDS instance',
            MinLength=3,
            MaxLength=64,
            ConstraintDescription='must be 3 or more characters and not longer than 64 characters.'))

        user_password_param = self.add_parameter(Parameter(
            db_label.lower() + self.tier_name.title() + 'RdsMasterUserPassword',
            NoEcho=True,
            Type='String',
            Description='Master RDS User Password for the RDS instance.',
            MinLength=12,
            MaxLength=64,
            ConstraintDescription='must be 12 or more characters and not longer than 64 characters.'))

        return instance_type_param, name_param, user_name_param, user_password_param

    # Called after add_child_template() has attached common parameters and some instance attributes:
    # - RegionMap: Region to AMI map, allows template to be deployed in different regions without updating AMI ids
    # - ec2Key: keyname to use for ssh authentication
    # - vpcCidr: IP block claimed by whole VPC
    # - vpcId: resource id of VPC
    # - commonSecurityGroup: sg identifier for common allowed ports (22 in from VPC)
    # - utilityBucket: S3 bucket name used to send logs to
    # - availabilityZone[0-3]: Indexed names of AZs VPC is deployed to
    # - [public|private]Subnet[0-9]: indexed and classified subnet identifiers
    #
    # and some instance attributes referencing the attached parameters:
    # - self.vpc_cidr
    # - self.vpc_id
    # - self.common_security_group
    # - self.utility_bucket
    # - self.subnets: keyed by type and index (e.g. self.subnets['public'][1])
    # - self.azs: List of parameter references
    def build_hook(self):

        for db_label, db_config in self.config_map.iteritems():

            (db_instance_type,
             db_name,
             db_user_name,
             db_user_password) = self.add_parameters(db_label, db_config)

            subnet_group = self.add_resource(rds.DBSubnetGroup(
                db_label.lower() + 'RdsSubnetGroup',
                DBSubnetGroupDescription='Subnet group for the RDS instance',
                SubnetIds=self.subnets[self.subnet_set]))

            rds_sg = self.add_resource(
                ec2.SecurityGroup(
                    db_label.lower() + self.tier_name.title() + 'RdsSg',
                    GroupDescription='Security group for %s RDS tier' % self.tier_name.lower(),
                    VpcId=Ref(self.vpc_id))
            )

            kwargs = {}
            if 'iops' in db_config:
                kwargs['Iops'] = db_config['iops']
            if 'storage_type' in db_config:
                kwargs['StorageType'] = db_config['storage_type']

            rds_instance = self.add_resource(rds.DBInstance(
                db_label.lower() + self.tier_name.title() + 'RdsInstance',
                AllocatedStorage=db_config.get('volume_size', '100'),
                BackupRetentionPeriod=db_config.get('backup_retention_period', '30'),
                DBInstanceClass=Ref(db_instance_type),
                DBName=Ref(db_name),
                VPCSecurityGroups=[Ref(rds_sg)],
                DBSubnetGroupName=Ref(subnet_group),
                Engine=db_config.get('rds_engine', 'mysql'),
                EngineVersion=db_config.get('rds_engine_version', '5.6.19'),
                MasterUsername=Ref(db_user_name),
                MasterUserPassword=Ref(db_user_password),
                PreferredBackupWindow=db_config.get('preferred_backup_window', '02:00-02:30'),
                PreferredMaintenanceWindow=db_config.get('preferred_maintenance_window', 'sun:03:00-sun:04:00'),
                MultiAZ=db_config.get('multi_az', True),
                **kwargs))

            # Set the snapshot id if provided (and null out the db name to avoid cfn error)
            if db_config['snapshot_id']:
                rds_instance.DBSnapshotIdentifier = db_config['snapshot_id']
                # DBName must be null when restoring from snapshot
                rds_instance.DBName = ''

            # Create the sg ingress rule for whatever port the rds instance needs
            ingress_rule = ec2.SecurityGroupIngress(
                db_label.lower() + self.tier_name.title() + 'RdsIngressRule',
                FromPort=GetAtt(rds_instance, "Endpoint.Port"),
                ToPort=GetAtt(rds_instance, "Endpoint.Port"),
                IpProtocol='tcp',
                GroupId=Ref(rds_sg))

            # Set the allowed origin on the ingress rule according the requested connect_from setting
            # OR vpc_cidr in no other setting provided
            if self.connect_from_sg:
                ingress_rule.SourceSecurityGroupId = self.connect_from_sg
            elif self.connect_from_cidr:
                ingress_rule.CidrIp = self.connect_from_cidr
            else:
                ingress_rule.CidrIp = Ref(self.vpc_cidr)

            self.add_resource(ingress_rule)

            # Add the connection endpoint output
            self.add_output(Output(
                db_label.lower() + self.tier_name.title() + 'RdsEndpoint',
                Value=Join('', [
                    Ref(db_user_name), '@',
                    GetAtt(rds_instance, "Endpoint.Address"), ':',
                    GetAtt(rds_instance, "Endpoint.Port")])
            ))

            self.data[db_label] = {
                'rds': rds_instance,
                'dbname': Ref(db_name),
                'endpoint_address': GetAtt(rds_instance, 'Endpoint.Address'),
                'endpoint_port': GetAtt(rds_instance, 'Endpoint.Port'),
                'masteruser': Ref(db_user_name),
                'masterpassword': Ref(db_user_password),
                'securitygroup': rds_sg
            }

class Controller(NetworkBase):
    """
    Example class showing how to use the RDS pattern file to generate an RDS database as a child stack

    To connect to this database log into the bastion and run:
    > sudo yum install -y mysql
    > mysql -h <db endpoint> -P <db port> -u <db username> -p
    """

    def __init__(self, *args, **kwargs):
        self.add_config_handler(RDS)
        super(Controller, self).__init__(*args, **kwargs)

    def create_action(self):
        self.initialize_template()
        self.construct_network()

        # Create the rds instance pattern (includes standard standard parameters)
        my_db = RDS(
            'dbTier',
            subnet_set='private',
            config_map=db_config)

        # Attach pattern as a child template
        self.add_child_template(my_db)

        # Our template is complete output it to file
        self.write_template_to_file()

    def deploy_action(self):
        self.load_db_passwords_from_env()

        for db_label, db_config in self.config['db'].iteritems():
            self.deploy_parameter_bindings.append({
                'ParameterKey': db_label.lower() + 'dbTier'.title() + 'RdsMasterUserPassword',
                'ParameterValue': db_config['password']
            })
        super(Controller, self).deploy_action()

if __name__ == '__main__':

    db_config = {
        'label1': {
            'db_instance_type_default': 'db.m1.small',
            'rds_user_name': 'defaultusername',
            # Actual database name, cannot include non-alphanumeric characters (e.g. '-')
            'master_db_name': 'mydb',
            'volume_size': 100,
            'backup_retention_period': 30,
            'rds_engine': 'MySQL',
            # 5.6.19 is no longer supported
            'rds_engine_version': '5.6.22',
            'preferred_backup_window': '02:00-02:30',
            'preferred_maintenance_window': 'sun:03:00-sun:04:00',
            # Name of vm snapshot to use, empty string ('') means don't use an old snapshot
            # Note: 'master_db_name' value will be overridden if snapshot_id is non-empty
            'snapshot_id': '',
            'password': 'changeme111111111111'
        },
        'label2': {
            'db_instance_type_default': 'db.m1.small',
            'rds_user_name': 'defaultusername',
            # Actual database name, cannot include non-alphanumeric characters (e.g. '-')
            'master_db_name': 'mydb2',
            'volume_size': 100,
            'backup_retention_period': 30,
            'rds_engine': 'MySQL',
            # 5.6.19 is no longer supported
            'rds_engine_version': '5.6.22',
            'preferred_backup_window': '02:00-02:30',
            'preferred_maintenance_window': 'sun:03:00-sun:04:00',
            # Name of vm snapshot to use, empty string ('') means don't use an old snapshot
            # Note: 'master_db_name' value will be overridden if snapshot_id is non-empty
            'snapshot_id': '',
            'password': 'changeme1111111111111'
        }
    }

    my_config = res.FACTORY_DEFAULT_CONFIG
    my_config['db'] = db_config

    Controller(config_file_override=my_config)


text:
/*jslint indent: 4, nomen:true, white:true */
/*global require, describe:true,it:true */

var expect = require('chai').expect,
    cronshot_local = require('../../index');

describe('cronshot-local middleware', function() {
    it("should error if null is passed as the first argument", function() {
        cronshot_local(null, function(err) {
            expect(err).not.to.equal(null);
        });
    });

    it("should error if options are not passed", function() {
        cronshot_local({}, function(err) {
            expect(err).not.to.equal(null);
        });
    });

    it("should error if the path option is not passed", function() {
        cronshot_local({
            options: {},
        }, function(err) {
            expect(err).not.to.equal(null);
        });
    });

    it("should error if the imageName option is not passed", function() {
        cronshot_local({
            options: {
                path: __dirname
            }
        }, function(err) {
            expect(err).not.to.equal(null);
        });
    });

    it("should error if the local file path does not exist", function() {
        cronshot_local({
            options: {
                path: __dirname,
                imageName: '/../images/notFound.png'
            }
        }, function(err) {
            expect(err).not.to.equal(null);
        });
    });

    it("should error if there is a writesteam error", function(done) {
        cronshot_local({
            options: {
                path: __dirname,
                imageName: '/../images/screenshot.png',
                error: true
            }
        }, function(err) {
            expect(err).not.to.equal(null);
            done();
        });
    });

    it("should succeed if all options and propeties are passed correctly", function(done) {
        cronshot_local({
            options: {
                path: __dirname,
                imageName: '/../images/screenshot.png',
            }
        }, function(err, data) {
            expect(err).to.equal(undefined);
            expect(data.name).to.equal('local');
            done();
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
/**
 * Utitles
 * This namespace contains helper functions that I use a lot around the code base
 * or encapluate snippets of code I use a lot in the codebase though by naming it
 * asa function gives the code more readablity.
 *
 * Logger
 * Just wraps the console.log functions alloing me to switch them on and off easily
 *
 * Keyboard
 * Keeps track of which keys are pressed and allows for polling in gameloop
 * which is faster then event based input.
 *
 *  License: Apache 2.0
 *  author:  Ciarán McCann
 *  url: http://www.ciaranmccann.me/
 */
///<reference path="../Settings.ts" />
///<reference path="Physics.ts" />
declare var $;
interface String
{
    format(...numbers: String[]);
}

String.prototype.format = function (...numbers: String[])
{
    var args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number)
    {
        return typeof args[number] != 'undefined'
          ? args[number]
          : match
            ;
    });
};

module Notify
{
    export var locked = false;
    export var levels = {
        sucess: "alert-success",
        warn: "alert-warn",
        error: "alert-error"
    };

    export function display(header: string, message: string, autoHideTime = 2800, cssStyle = Notify.levels.sucess,doNotOverWrite = false)
    {
        if (!locked)
        {
            locked = doNotOverWrite;
            $("#notifaction").removeClass(levels.warn);
            $("#notifaction").removeClass(levels.error);
            $("#notifaction").removeClass(levels.sucess);
            $("#notifaction").addClass(cssStyle);

            $("#notifaction strong").empty();
            $("#notifaction strong").html(header);

            $("#notifaction p").empty();
            $("#notifaction p").html(message);

            $("#notifaction").animate({
                top:  (parseInt($("#notifaction").css("height"))) +"px"
            }, 400, function ()
            {
                if (autoHideTime > 0)
                {
                    setTimeout(hide, autoHideTime);
                }
            });

        }

    }

    export function hide(callback)
    {
        if (!locked)
        {
            $("#notifaction").animate({
                top: (-parseInt($("#notifaction").css("height"))) - 100 + "px"
            }, 400, function () => {
                locked = false;
                if (callback != null)
                {
                    callback();
                }
            });
        }
    }

}

module Utilies
{

    //Allows for the copying of Object types into their proper types, used for copy constructer
    //for objects that are sent over the network. I have intergrated this function, into
    // the constructor of the Person object so it acts like C-style copy construction
    // WARNING: This creates a deep copy, so reference are not preserved
    export function copy(newObject, oldObject)
    {

        for (var member in oldObject)
        {
            // if the member is itself an object, then we most also call copy on that
            if (typeof (oldObject[member]) == "object")
            {
                //FIXME : Should be usig this try catch, fix it later
                try
                {
                    newObject[member] = copy(newObject[member], oldObject[member])
                } catch (e)
                {

                }
            } else
            {
                // if its a primative member just assign it
                try
                {
                    newObject[member] = oldObject[member];
                } catch (e)
                {

                }
            }
        }

        return newObject;
    };

    export function sign(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; }

    export function findByValue(needle, haystack, haystackProperity, )
    {

        for (var i = 0; i < haystack.length; i++)
        {
            if (haystack[i][haystackProperity] === needle)
            {
                return haystack[i];
            }
        }
        throw "Couldn't find object with proerpty " + haystackProperity + " equal to " + needle;
    }

    export function random(min, max)
    {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    export function pickRandom(collection)
    {
        return collection[random(0, collection.length - 1)];
    }

    var pickUnqineCollection = [];
    export function pickUnqine(collection, stringId: string)
    {
        if (pickUnqineCollection[stringId])
        {
            var items = pickUnqineCollection[stringId];

            if (items.length <= 0)
            {
                Logger.error("Out of unqine items in collection " + stringId);
                return;
            }

            var index = random(0, items.length - 1)
            var unqineItem = items[index];
            deleteFromCollection(items, index);
            return unqineItem;

        } else
        {
            pickUnqineCollection[stringId] = collection;
            return pickUnqine(collection, stringId);
        }
    }

    export function pickRandomSound(collection: string[])
    {
        var sound: Sound = AssetManager.getSound(collection[random(0, collection.length - 1)]);

        if (!sound.play)
        {
            Logger.warn(" Somthing looks dogoy with the sound object " + sound);
        }

        return sound;
    }

    export function deleteFromCollection(collection, indexToRemove)
    {
        delete collection[indexToRemove];
        collection.splice(indexToRemove, 1);
    }

    export function isBetweenRange(value, rangeMax, rangeMin)
    {
        return value >= rangeMin && value <= rangeMax;
    }

    export function angleToVector(angle: number)
    {
        return new b2Vec2(Math.cos(angle), Math.sin(angle));
    }

    export function vectorToAngle(vector)
    {
        return Math.atan2(vector.y, vector.x);
    }

    export function toRadians(angleInDegrees: number)
    {
        return angleInDegrees * (Math.PI / 180);
    }

    export function toDegrees(angleInRdains: number)
    {
        return angleInRdains * (180 / Math.PI);
    }

    //export function isBetweenRangeTest()
    //{
    //    var t1 = isBetweenRange(3.3, 10, -10);
    //    var t2 = isBetweenRange(-2.3, 40, -3);
    //    var t3 = isBetweenRange(-25.3, 40, -3);

    //    if ( t1 == false || t2 == false || t3 == true)
    //    {
    //        Logger.error(" isBetweenRangeTestFailed ");
    //    } else
    //    {
    //        Logger.log("isBetweenTestPassed");
    //    }
    //};

	export function compress(s){
		var dict = {};
	    var data = (s + "").split("");
	    var out = [];
	    var currChar;
	    var phrase = data[0];
	    var code = 256;
	    for (var i=1; i<data.length; i++) {
	        currChar=data[i];
	        if (dict[phrase + currChar] != null) {
	            phrase += currChar;
	        }
	        else {
	            out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
	            dict[phrase + currChar] = code;
	            code++;
	            phrase=currChar;
	        }
	    }
	    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
	    for (var i=0; i<out.length; i++) {
	        out[i] = String.fromCharCode(out[i]);
	    }
	    return out.join("");
	}

	export function decompress(s)
	{

	    var dict = {};
	    var data = (s + "").split("");
	    var currChar = data[0];
	    var oldPhrase = currChar;
	    var out = [currChar];
	    var code = 256;
	    var phrase;
	    for (var i = 1; i < data.length; i++)
	    {
	        var currCode = data[i].charCodeAt(0);
	        if (currCode < 256)
	        {
	            phrase = data[i];
	        }
	        else
	        {
	            phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
	        }
	        out.push(phrase);
	        currChar = phrase.charAt(0);
	        dict[code] = oldPhrase + currChar;
	        code++;
	        oldPhrase = phrase;
	    }
	    return out.join("");

	}

    export function isNumber(n) {
        return !isNaN(parseFloat(n)) && isFinite(n);
    }

}

module Logger
{

    export function log(message)
    {
        if (Settings.DEVELOPMENT_MODE || Settings.LOG)
            console.info(message);
    }

    export function warn(message)
    {
        if (Settings.DEVELOPMENT_MODE || Settings.LOG)
         console.warn(message);
    }

    export function debug(message)
    {
        if (Settings.DEVELOPMENT_MODE || Settings.LOG )
            console.log(message);
    }

    export function error(message)
    {
        if (Settings.DEVELOPMENT_MODE || Settings.LOG)
            console.error(message);
    }
}

module TouchUI
{
    var isFireHeld = false;
    var isJumpPressed = false;

    export function isTouchDevice() {
      return 'ontouchstart' in window || navigator.msMaxTouchPoints;

    };

    export function init()
    {
        if (TouchUI.isTouchDevice())
        {
            var fireButtonCssId = "touchFireButton";
            var jumpButtonCssId = "touchJump";
            //Using this to also insert the touch contorls for tablets
            $('body').append("
Fire
");
            $('body').append("
Jump
");

            $("#" + fireButtonCssId).bind('touchstart', function (e)
            {
                e.preventDefault();
                isFireHeld = true;
                Logger.log("touchstarted");
            });

            $("#" + fireButtonCssId).bind("touchend", function (e)
            {
                isFireHeld = false;
                Logger.log("touchend");
            });

            $("#" + jumpButtonCssId).bind('touchstart', function (e)
            {
                e.preventDefault();
                isJumpPressed = true;
            });

            $("#" + jumpButtonCssId).bind("touchend", function (e)
            {
                isJumpPressed = false;
            });
        }
    }

    export function isFireButtonDown(reset = false)
    {
        if (isFireHeld && reset)
        {
            isFireHeld = false;
            return true;
        }

        return  isFireHeld;
    }

    export function isJumpDown(reset = false)
    {
         if (isJumpPressed && reset)
        {
            isJumpPressed = false;
            return true;
        }

        return  isJumpPressed;
    }

}

module keyboard
{

    export var keys = [];

    (function ()
    {

        $(window).keydown(function (e)
        {
            keys[e.which] = true;
        });

        $(window).keyup(function (e)
        {
            delete keys[e.which];
        });

    })();

    export function isKeyDown(keyCode, actLikeKeyPress = false)
    {
        for (var key in keys)
        {
            if (key == keyCode)
            {
                if (actLikeKeyPress)
                {
                    delete keys[key]
                }

                return true;
            }
        }

        return false;
    }

    export function getKeyName(keycode: number)
    {
        for (var i in keyCodes)
        {
            if (keyCodes[i] == keycode)
            {
                return i;
            }
        }
    }

    export var keyCodes =  {
    'Backspace': 8,
    'Tab': 9,
    'Enter': 13,
    'Shift': 16,
    'Ctrl': 17,
    'Alt': 18,
    'Pause': 19,
    'Capslock': 20,
    'Esc': 27,
    'Pageup': 33,
        'Space': 32,
    'Pagedown': 34,
    'End': 35,
    'Home': 36,
    'Leftarrow': 37,
    'Uparrow': 38,
    'Rightarrow': 39,
    'Downarrow': 40,
    'Insert': 45,
    'Delete': 46,
    '0': 48,
    '1': 49,
    '2': 50,
    '3': 51,
    '4': 52,
    '5': 53,
    '6': 54,
    '7': 55,
    '8': 56,
    '9': 57,
    'a': 65,
    'b': 66,
    'c': 67,
    'd': 68,
    'e': 101,
    'f': 70,
    'g': 71,
    'h': 72,
    'i': 73,
    'j': 74,
    'k': 75,
    'l': 76,
    'm': 77,
    'n': 78,
    'o': 79,
    'p': 80,
    'q': 81,
    'r': 82,
    's': 83,
    't': 84,
    'u': 85,
    'v': 86,
    'w': 87,
    'x': 88,
    'y': 89,
    'z': 90,
    'numpad0': 96,
    'numpad1': 97,
    'numpad2': 98,
    'numpad3': 99,
    'numpad4': 100,
    'numpad6': 102,
    'numpad7': 103,
    'numpad8': 104,
    'numpad9': 105,
    'Multiply': 106,
    'Plus': 107,
    'Minut': 109,
    'Dot': 110,
    'Slash1': 111,
    'F1': 112,
    'F2': 113,
    'F3': 114,
    'F4': 115,
    'F5': 116,
    'F6': 117,
    'F7': 118,
    'F8': 119,
    'F9': 120,
    'F10': 121,
    'F11': 122,
    'F12': 123,
    'equal': 187,
    'Coma': 188,
    'Slash': 191,
    'Backslash': 220
    }

}


text:
import {Component} from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'mdc-radio-e2e',
  templateUrl: 'mdc-radio-e2e.html',
})
export class MdcRadioE2e {
  // TODO: copy implementation from existing mat-radio e2e page.
}


text:
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\AdminStoreSocialLinkRequest;
use App\Http\Requests\AdminUpdateSocialLinkRequest;
use App\SocialLink;
use Illuminate\Support\Facades\Redirect;
use Laracasts\Flash\Flash;

class SocialLinkController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $links = SocialLink::all();

        return view('admin.social.index')
            ->with('links', $links);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        return view('admin.social.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store(AdminStoreSocialLinkRequest $request)
    {
        $link = new SocialLink();
        $link->title = $request->input('title');
        $link->url = $request->input('url');
        $link->icon = $request->input('icon');
        $link->save();

        Flash::success('Link successfully added');

        return redirect()->route('admin.social.index');
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     *
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $link = SocialLink::find($id);

        return view('admin.social.edit')
            ->with('link', $link);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param int $id
     *
     * @return Response
     */
    public function update(AdminUpdateSocialLinkRequest $request, $id)
    {
        $link = SocialLink::find($id);
        $link->title = $request->input('title');
        $link->url = $request->input('url');
        $link->icon = $request->input('icon');
        $link->save();

        Flash::success('Link successfully updated');

        return redirect()->back();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     *
     * @return Response
     */
    public function delete($id)
    {
        SocialLink::find($id)->delete();

        Flash::success('Link deleted.');

        return redirect()->route('admin.social.index');
    }
}


text:
using OnLineShop.Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OnLineShop.Data.Services.Contracts
{
    public interface IProductService
    {
        IQueryable<Product> GetAllWithCategoryBrand();

        IQueryable<Product> GetAllByCategory(int categoryId);

        Product GetById(int? id);

        int Update(Product product);

        int Delete(int? id);

        int Insert(Product product);
    }
}


text:
function t = iscolvector(x)
%ISCOLVECTOR True for column vector input.
%
%   ISCOLVECTOR(X) returns 1 if X is a column vector and 0 otherwise.
%
%   An array is considered a colum vector if the length along each
%   dimension, except possibly the first, is never larger than one.  That
%   is, SIZE(X, DIM) <= 1 for all DIM except possibly when DIM = 1.

%   Author:      Peter J. Acklam
%   Time-stamp:  2002-03-03 13:51:06 +0100
%   E-mail:      pjacklam@online.no
%   URL:         http://home.online.no/~pjacklam

   t = ndims(x) == 2 & size(x, 2) == 1;


text:
title: Make Your First Event
text: In order to make your first event, follow the instructions here.
location: Your Location
link: https://github.com/mozillascience/studyGroup#how-to-set-up-your-own-mozilla-study-group-website
date: 1977-01-01
startTime: '20:00'
endTime: '21:00'

---


text:
package hudson.plugins.plotpipeline;

import hudson.model.Action;
import hudson.model.InvisibleAction;
import hudson.model.Run;
import jenkins.tasks.SimpleBuildStep;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.export.ExportedBean;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Created by Markus Axelsson on 2016-06-20.
 */
@ExportedBean
public class PlotBuildAction extends InvisibleAction implements StaplerProxy, SimpleBuildStep.LastBuildAction{

    private Run<?, ?> run;
    private List<Plot> plots;

    public PlotBuildAction(Run<?, ?> run, List<Plot> plots) {
        this.run = run;
        this.plots = plots;
    }

    @Override
    public Collection<? extends Action> getProjectActions() {
        return Collections.<Action>singleton(new PlotProjectAction(run.getParent(), plots));
    }

    @Override
    public Object getTarget() {
        return null;
    }

    public void addPlots( List<Plot> plots ) {
        this.plots.addAll( plots );
    }
}


text:
using AStarNavigator.Algorithms;
using AStarNavigator.Providers;
using System.Collections.Generic;
using System.Linq;

namespace AStarNavigator
{
    public class TileNavigator : ITileNavigator
    {
        private readonly IBlockedProvider blockedProvider;
        private readonly INeighborProvider neighborProvider;

        private readonly IDistanceAlgorithm distanceAlgorithm;
        private readonly IDistanceAlgorithm heuristicAlgorithm;

        public TileNavigator(
            IBlockedProvider blockedProvider,
            INeighborProvider neighborProvider,
            IDistanceAlgorithm distanceAlgorithm,
            IDistanceAlgorithm heuristicAlgorithm)
        {
            this.blockedProvider = blockedProvider;
            this.neighborProvider = neighborProvider;

            this.distanceAlgorithm = distanceAlgorithm;
            this.heuristicAlgorithm = heuristicAlgorithm;
        }

        public IEnumerable<Tile> Navigate(Tile from, Tile to)
        {
            var closed = new List<Tile>();
            var open = new List<Tile>() { from };

            var path = new Dictionary<Tile, Tile>();

            var gScore = new Dictionary<Tile, double>();
            gScore[from] = 0;

            var fScore = new Dictionary<Tile, double>();
            fScore[from] = heuristicAlgorithm.Calculate(from, to);

            while (open.Any())
            {
                var current = open
                    .OrderBy(c => fScore[c])
                    .First();

                if (current == to)
                {
                    return ReconstructPath(path, current);
                }

                open.Remove(current);
                closed.Add(current);

                foreach (Tile neighbor in neighborProvider.GetNeighbors(current))
                {
                    if (closed.Contains(neighbor) || blockedProvider.IsBlocked(neighbor))
                    {
                        continue;
                    }

                    var tentativeG = gScore[current] + distanceAlgorithm.Calculate(current, neighbor);

                    if (!open.Contains(neighbor))
                    {
                        open.Add(neighbor);
                    }
                    else if (tentativeG >= gScore[neighbor])
                    {
                        continue;
                    }

                    path[neighbor] = current;

                    gScore[neighbor] = tentativeG;
                    fScore[neighbor] = gScore[neighbor] + heuristicAlgorithm.Calculate(neighbor, to);
                }
            }

            return null;
        }

        private IEnumerable<Tile> ReconstructPath(
            IDictionary<Tile, Tile> path,
            Tile current)
        {
            List<Tile> totalPath = new List<Tile>() { current };

            while (path.ContainsKey(current))
            {
                current = path[current];
                totalPath.Add(current);
            }

            totalPath.Reverse();
            totalPath.RemoveAt(0);

            return totalPath;
        }
    }
}


text:
package com.pi4j.component.light.impl;

import com.pi4j.component.light.LightBase;
import com.pi4j.component.light.LightStateChangeEvent;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;

public class GpioLightComponent extends LightBase {

    // internal class members
    GpioPinDigitalOutput pin = null;
    PinState onState = PinState.HIGH;
    PinState offState = PinState.LOW;

    /**
     * using this constructor requires that the consumer
     *  define the LIGHT ON and LIGHT OFF pin states
     *
     * @param pin GPIO digital output pin
     * @param onState pin state to set when power is ON
     * @param offState pin state to set when power is OFF
     */
    public GpioLightComponent(GpioPinDigitalOutput pin, PinState onState, PinState offState) {
        this.pin = pin;
        this.onState = onState;
        this.offState = offState;
    }

    /**
     * default constructor; using this constructor assumes that:
     *  (1) a pin state of HIGH is LIGHT ON
     *  (2) a pin state of LOW  is LIGHT OFF
     *
     * @param pin GPIO digital output pin
     */
    public GpioLightComponent(GpioPinDigitalOutput pin) {
        this.pin = pin;
    }

    /**
     * Set the current GPIO digital output pin state
     * based for LIGHT ON
     */
    @Override
    public void on()
    {
        // turn the light ON by settings the GPIO pin to the on state
        pin.setState(onState);

        // notify any power state change listeners
        notifyListeners(new LightStateChangeEvent(this, true));
    }

    /**
     * Set the current GPIO digital output pin state
     * based for LIGHT OFF
     */
    @Override
    public void off()
    {
        // turn the light OFF by settings the GPIO pin to the off state
        pin.setState(offState);

        // notify any power state change listeners
        notifyListeners(new LightStateChangeEvent(this, false));
    }

    /**
     * Return the current power state based on the
     * GPIO digital output pin state.
     *
     * @return boolean is light on
     */
    @Override
    public boolean isOn()
    {
        return pin.isState(onState);
    }
}


text:
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.external_interface import ExternalInterfaceFunctionalMockupUnitImportToSchedule

log = logging.getLogger(__name__)

class TestExternalInterfaceFunctionalMockupUnitImportToSchedule(unittest.TestCase):

    def setUp(self):
        self.fd, self.path = tempfile.mkstemp()

    def tearDown(self):
        os.remove(self.path)

    def test_create_externalinterfacefunctionalmockupunitimporttoschedule(self):

        pyidf.validation_level = ValidationLevel.error

        obj = ExternalInterfaceFunctionalMockupUnitImportToSchedule()
        # alpha
        var_name = "Name"
        obj.name = var_name
        # object-list
        var_schedule_type_limits_names = "object-list|Schedule Type Limits Names"
        obj.schedule_type_limits_names = var_schedule_type_limits_names
        # object-list
        var_fmu_file_name = "object-list|FMU File Name"
        obj.fmu_file_name = var_fmu_file_name
        # alpha
        var_fmu_instance_name = "FMU Instance Name"
        obj.fmu_instance_name = var_fmu_instance_name
        # alpha
        var_fmu_variable_name = "FMU Variable Name"
        obj.fmu_variable_name = var_fmu_variable_name
        # real
        var_initial_value = 6.6
        obj.initial_value = var_initial_value

        idf = IDF()
        idf.add(obj)
        idf.save(self.path, check=False)

        with open(self.path, mode='r') as f:
            for line in f:
                log.debug(line.strip())

        idf2 = IDF(self.path)
        self.assertEqual(idf2.externalinterfacefunctionalmockupunitimporttoschedules[0].name, var_name)
        self.assertEqual(idf2.externalinterfacefunctionalmockupunitimporttoschedules[0].schedule_type_limits_names, var_schedule_type_limits_names)
        self.assertEqual(idf2.externalinterfacefunctionalmockupunitimporttoschedules[0].fmu_file_name, var_fmu_file_name)
        self.assertEqual(idf2.externalinterfacefunctionalmockupunitimporttoschedules[0].fmu_instance_name, var_fmu_instance_name)
        self.assertEqual(idf2.externalinterfacefunctionalmockupunitimporttoschedules[0].fmu_variable_name, var_fmu_variable_name)
        self.assertAlmostEqual(idf2.externalinterfacefunctionalmockupunitimporttoschedules[0].initial_value, var_initial_value)


text:
module AppAnnie
  class Intelligence
    # see AppAnnie Intelligence docs for options
    # all ops get passed as query params
    def self.top_app_charts(opts)
      [:market, :device, :categories].each do |key|
        unless opts.keys.include?(key)
          raise ArgumentError, "Missing #{key} key in options"
        end
      end
      default_options = {
        vertical: 'apps',
        countries: 'US',
      }
      opts = default_options.merge(opts)

      response = AppAnnie.connection.get do |req|
        req.headers['Authorization'] = "Bearer #{AppAnnie.api_key}"
        req.headers['Accept'] = 'application/json'
        req.url "/v1.1/intelligence/#{opts[:vertical]}/#{opts[:market]}/ranking"
        req.params = opts
      end

      if response.status == 200
        JSON.parse(response.body)['list']
      else
        ErrorResponse.raise_for(response)
      end
    end
  end
end


text:
package test.eidos.kingchanllenge.utils;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import java.util.ArrayList;
import java.util.TreeSet;

import org.easymock.EasyMockRunner;
import org.eidos.kingchallenge.domain.comparator.KingScoreChainedComparator;
import org.eidos.kingchallenge.domain.comparator.KingScoreReverseOrderByScore;
import org.eidos.kingchallenge.domain.comparator.KingScoreReverseUserIdComparator;
import org.eidos.kingchallenge.domain.model.KingScore;
import org.eidos.kingchallenge.utils.CollectionsChallengeUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import test.eidos.kingchanllenge.AbstractKingTest;

@RunWith(EasyMockRunner.class)
public class TestCollectionUtils extends AbstractKingTest {

	private static TreeSet<KingScore> setScore=  new TreeSet<KingScore>(
			new KingScoreChainedComparator( new KingScoreReverseOrderByScore(),new KingScoreReverseUserIdComparator()  )	);

	@BeforeClass public static void setupOnlyOnce() {
				//User 1
				setScore.add(  TestUtils.transformDTO(TestUtils.craeteKingScoreDTO(1L, 34, 1L)) 	 );
				//User 2
				setScore.add( TestUtils.transformDTO(TestUtils.craeteKingScoreDTO(1L, 34, 2L)) );
				//User 3
				setScore.add(  TestUtils.transformDTO(TestUtils.craeteKingScoreDTO(1L, 34, 3L))  );
				//User 4
				setScore.add(   TestUtils.transformDTO(TestUtils.craeteKingScoreDTO(1L, 34, 4L))  );
				//User5
				setScore.add(  TestUtils.transformDTO(TestUtils.craeteKingScoreDTO(1L, 34, 5L))  );
	}
	@Test
	public void validateOkCollecion(){
		String expected= "5=34, 4=34, 3=34, 2=34, 1=34";
			CollectionsChallengeUtils.returnCsvFromCollection(setScore);
		assertThat("", CollectionsChallengeUtils.returnCsvFromCollection(setScore), equalTo(expected));

	}
	@Test
	public void validateEmptyCollection(){
		String expected= "";
		TreeSet<KingScore> emptySet=  new TreeSet<KingScore>(
				new KingScoreChainedComparator( new KingScoreReverseOrderByScore(),new KingScoreReverseUserIdComparator()  )	);
		assertThat("", CollectionsChallengeUtils.returnCsvFromCollection(emptySet), equalTo(expected));

	}
	@Test
	public void validateNullCollection(){
		String expected= "";
		TreeSet<KingScore> nullSet=null;
		assertThat("", CollectionsChallengeUtils.returnCsvFromCollection(nullSet), equalTo(expected));

	}
	@Test
	public void validateCollectionWithNullElements(){
		String expected="1=34, null, 3=34, null, 5=34";
		ArrayList<KingScore> hasNullsArrayList = new ArrayList<KingScore>();
		hasNullsArrayList.add(TestUtils.transformDTO(TestUtils.craeteKingScoreDTO(1L, 34, 1L)) ) ;
		hasNullsArrayList.add(null);
		hasNullsArrayList.add(TestUtils.transformDTO(TestUtils.craeteKingScoreDTO(1L, 34, 3L)) ) ;
		hasNullsArrayList.add(null);
		hasNullsArrayList.add(TestUtils.transformDTO(TestUtils.craeteKingScoreDTO(1L, 34, 5L)) ) ;

		assertThat("", CollectionsChallengeUtils.returnCsvFromCollection(hasNullsArrayList), equalTo(expected));

	}
}


text:
import LowVoltage.testing as _tst
from . import *

_tst.main()


text:
package mcjty.rftools.blocks.shield;

import net.minecraftforge.common.property.IUnlistedProperty;

public class CamoProperty implements IUnlistedProperty<CamoBlockId> {

    private final String name;

    public CamoProperty(String name) {
        this.name = name;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public boolean isValid(CamoBlockId value) {
        return true;
    }

    @Override
    public Class<CamoBlockId> getType() {
        return CamoBlockId.class;
    }

    @Override
    public String valueToString(CamoBlockId value) {
        return value.toString();
    }
}


text:
Including include-placeholders-1.html:

<!-- INCLUDE include-placeholders-1.html -->


text:
package org.jacpfx.rest;

import com.google.gson.Gson;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.json.JsonObject;
import io.vertx.core.spi.cluster.ClusterManager;
import io.vertx.test.core.VertxTestBase;
import io.vertx.test.fakecluster.FakeClusterManager;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

import org.jacpfx.entity.Payload;
import org.jacpfx.entity.encoder.ExampleByteEncoder;
import org.jacpfx.entity.encoder.ExampleStringEncoder;
import org.jacpfx.vxms.common.ServiceEndpoint;
import org.jacpfx.vxms.common.util.Serializer;
import org.jacpfx.vxms.rest.base.RouteBuilder;
import org.jacpfx.vxms.rest.base.VxmsRESTRoutes;
import org.jacpfx.vxms.rest.base.response.RestHandler;
import org.jacpfx.vxms.services.VxmsEndpoint;
import org.junit.Before;
import org.junit.Test;

/** Created by Andy Moncsek on 23.04.15. */
public class RESTVerticleRouteBuilderSelfhostedTest extends VertxTestBase {

  public static final String SERVICE_REST_GET = "/wsService";
  public static final int PORT = 9998;
  private static final int MAX_RESPONSE_ELEMENTS = 4;
  private static final String HOST = "127.0.0.1";
  private HttpClient client;

  protected int getNumNodes() {
    return 1;
  }

  protected Vertx getVertx() {
    return vertices[0];
  }

  @Override
  protected ClusterManager getClusterManager() {
    return new FakeClusterManager();
  }

  @Override
  public void setUp() throws Exception {
    super.setUp();
    startNodes(getNumNodes());
  }

  @Before
  public void startVerticles() throws InterruptedException {

    CountDownLatch latch2 = new CountDownLatch(1);
    DeploymentOptions options = new DeploymentOptions().setInstances(1);
    options.setConfig(new JsonObject().put("clustered", false).put("host", HOST));
    // Deploy the module - the System property `vertx.modulename` will contain the name of the
    // module so you
    // don'failure have to hardecode it in your tests

    getVertx()
        .deployVerticle(
            new WsServiceOne(),
            options,
            asyncResult -> {
              // Deployment is asynchronous and this this handler will be called when it's complete
              // (or failed)
              System.out.println("start service: " + asyncResult.succeeded());
              assertTrue(asyncResult.succeeded());
              assertNotNull("deploymentID should not be null", asyncResult.result());
              // If deployed correctly then start the tests!
              //   latch2.countDown();

              latch2.countDown();
            });

    client = getVertx().createHttpClient(new HttpClientOptions());
    awaitLatch(latch2);
  }

  @Test
  public void endpointOne() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointOne",
            resp ->
                resp.bodyHandler(
                    body -> {
                      System.out.println("Got a createResponse: " + body.toString());
                      assertEquals(body.toString(), "test");
                      testComplete();
                    }));
    request.end();
    await();
  }

  @Test
  public void endpointTwo() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointTwo/123",
            resp ->
                resp.bodyHandler(
                    body -> {
                      System.out.println("Got a createResponse: " + body.toString());
                      assertEquals(body.toString(), "123");
                      testComplete();
                    }));
    request.end();
    await();
  }

  @Test
  public void endpointThree() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointThree?val=123&tmp=456",
            resp -> {
              resp.bodyHandler(
                  body -> {
                    System.out.println("Got a createResponse: " + body.toString());
                    assertEquals(body.toString(), "123456");
                      testComplete();
                  });
            });
    request.end();
    await();
  }

  @Test
  public void endpointFourErrorRetryTest() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointFourErrorRetryTest?val=123&tmp=456",
            resp -> resp.bodyHandler(
                body -> {
                  System.out.println("Got a createResponse: " + body.toString());
                  assertEquals(body.toString(), "123456");
                  testComplete();
                }));
    request.end();
    await();
  }

  @Test
  public void endpointFourErrorReturnRetryTest() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointFourErrorReturnRetryTest?productType=123&product=456",
            resp -> resp.bodyHandler(
                body -> {
                  System.out.println(
                      "Got a createResponse endpointFourErrorReturnRetryTest: "
                          + body.toString());
                  assertEquals(body.toString(), "456123");
                  testComplete();
                }));
    request.end();
    await();
  }

  @Test
  public void endpointFive() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointFive?val=123&tmp=456",
            resp -> {
              resp.bodyHandler(
                  body -> {
                    System.out.println("Got a createResponse: " + body.toString());
                    if(resp.statusCode()!=200) {
                        fail();
                    }
                    Payload<String> pp = new Gson().fromJson(body.toString(), Payload.class);
                    assertEquals(pp.getValue(), new Payload<>("123" + "456").getValue());
                      testComplete();
                  });
            });
    request.end();
    await();
  }

  @Test
  public void endpointFive_error() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointFive_error?val=123&tmp=456",
            resp -> {
              resp.bodyHandler(
                  body -> {
                    System.out.println("Got a createResponse: " + body.toString());
                      if(resp.statusCode()!=200) {
                          fail();
                      }
                    Payload<String> pp = new Gson().fromJson(body.toString(), Payload.class);
                    assertEquals(pp.getValue(), new Payload<>("123" + "456").getValue());
                      testComplete();
                  });
            });
    request.end();
    await();
  }

  @Test
  public void endpointSix() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointSix?val=123&tmp=456",
            resp -> {
              resp.bodyHandler(
                  body -> {
                    System.out.println("Got a createResponse: " + body.toString());
                    Payload<String> pp = null;
                    try {
                      pp = (Payload<String>) Serializer.deserialize(body.getBytes());
                    } catch (Exception e) {
                      e.printStackTrace();
                      fail();
                    }
                    assertEquals(pp.getValue(), new Payload<>("123" + "456").getValue());
                      testComplete();
                  });

            });
    request.end();
    await();
  }

  @Test
  public void endpointSeven() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointSeven?val=123&tmp=456",
            resp -> {
              resp.bodyHandler(
                  body -> {
                    System.out.println("Got a createResponse: " + body.toString());
                    Payload<String> pp = null;
                    try {
                      pp = (Payload<String>) Serializer.deserialize(body.getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                        fail();
                    }
                    assertEquals(pp.getValue(), new Payload<>("123" + "456").getValue());
                      testComplete();
                  });
            });
    request.end();
    await();
  }

  @Test
  public void endpointSeven_error() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointSeven_error?val=123&tmp=456",
            resp -> {
              resp.bodyHandler(
                  body -> {
                    System.out.println("Got a createResponse: " + body.toString());
                    Payload<String> pp = null;
                    try {
                      pp = (Payload<String>) Serializer.deserialize(body.getBytes());
                    } catch (Exception e) {
                        e.printStackTrace();
                        fail();
                    }
                    assertEquals(pp.getValue(), new Payload<>("123" + "456").getValue());
                      testComplete();
                  });
            });
    request.end();
    await();
  }

  @Test
  public void endpointEight_header() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointEight_header?val=123&tmp=456",
            resp -> {
              resp.bodyHandler(
                  body -> {
                    System.out.println(
                        "Got a createResponse endpointFourErrorReturnRetryTest: "
                            + body.toString());

                    assertEquals(body.toString(), "123456");
                  });
              String contentType = resp.getHeader("Content-Type");
              assertEquals(contentType, "application/json");
              testComplete();
            });
    request.end();
    await();
  }

  @Test
  public void endpointEight_put_header() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointEight_put_header?val=123&tmp=456",
            resp -> {
              resp.bodyHandler(
                  body -> {
                    System.out.println(
                        "Got a createResponse endpointFourErrorReturnRetryTest: "
                            + body.toString());

                    assertEquals(body.toString(), "123456");
                  });
              String contentType = resp.getHeader("Content-Type");
              assertEquals(contentType, "application/json");
              String key = resp.getHeader("key");
              assertEquals(key, "val");
              testComplete();
            });
    request.end();
    await();
  }

  @Test
  public void endpointNine_exception() throws InterruptedException {
    HttpClientOptions options = new HttpClientOptions();
    options.setDefaultPort(PORT);
    options.setDefaultHost(HOST);
    HttpClient client = vertx.createHttpClient(options);

    HttpClientRequest request =
        client.get(
            "/wsService/endpointNine_exception?val=123&tmp=456",
            resp -> {
              assertEquals(500, resp.statusCode());
              assertEquals("test", resp.statusMessage());
              testComplete();
            });
    request.end();
    await();
  }

  public HttpClient getClient() {
    return client;
  }

  @ServiceEndpoint(name = SERVICE_REST_GET, contextRoot = SERVICE_REST_GET, port = PORT)
  public class WsServiceOne extends AbstractVerticle {

    @Override
    public void start(io.vertx.core.Future<Void> startFuture) throws Exception {
      VxmsRESTRoutes routes =
          VxmsRESTRoutes.init()
              .route(RouteBuilder.get("/endpointOne", this::rsEndpointOne))
              .route(RouteBuilder.get("/endpointTwo/:help", this::rsEndpointTwo))
              .route(RouteBuilder.get("/endpointThree", this::rsEndpointThree))
              .route(RouteBuilder.get("/endpointFourErrorRetryTest", this::rsEndpointFourErrorRetryTest))
              .route(RouteBuilder.get("/endpointFourErrorReturnRetryTest", this::rsEndpointFourErrorReturnRetryTest))
              .route(RouteBuilder.get("/endpointFive", this::rsEndpointFive))
              .route(RouteBuilder.get("/endpointFive_error", this::rsEndpointFive_error))
              .route(RouteBuilder.get("/endpointSix", this::rsEndpointSix))
              .route(RouteBuilder.get("/endpointSeven", this::rsEndpointSeven))
              .route(RouteBuilder.get("/endpointSeven_error", this::rsEndpointSeven_error))
              .route(RouteBuilder.get("/endpointEight_header", this::rsEndpointEight_header))
              .route(RouteBuilder.get("/endpointEight_put_header", this::rsEndpointEight_put_header))
              .route(RouteBuilder.get("/endpointNine_exception", this::rsEndpointNine_exception));
      VxmsEndpoint.init(startFuture, this, routes);
    }

    public void rsEndpointOne(RestHandler reply) {
      System.out.println("wsEndpointOne: " + reply);
      reply.response().stringResponse((future) -> future.complete("test")).execute();
    }

    public void rsEndpointTwo(RestHandler handler) {
      String productType = handler.request().param("help");
      System.out.println("wsEndpointTwo: " + handler);
      handler.response().stringResponse((future) -> future.complete(productType)).execute();
    }

    public void rsEndpointThree(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      handler
          .response()
          .stringResponse((future) -> future.complete(productType + product))
          .execute();
    }

    public void rsEndpointFourErrorRetryTest(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      AtomicInteger count = new AtomicInteger(4);
      handler
          .response()
          .stringResponse(
              (future) -> {
                if (count.decrementAndGet() >= 0) {
                  System.out.println("throw:" + count.get());
                  throw new NullPointerException("test");
                }
                future.complete(productType + product);
              })
          .onError(
              error -> {
                error.printStackTrace();
                System.out.println("count: " + count.get());
              })
          .retry(3)
          .onFailureRespond((e, response) -> response.complete(productType + product))
          .execute();
    }

    public void rsEndpointFourErrorReturnRetryTest(RestHandler handler) {
      String productType = handler.request().param("productType");
      String product = handler.request().param("product");
      System.out.println("wsEndpointTwo: " + handler);
      AtomicInteger count = new AtomicInteger(4);
      handler
          .response()
          .stringResponse(
              (future) -> {
                if (count.decrementAndGet() >= 0) {
                  System.out.println("throw:" + count.get());
                  throw new NullPointerException("test");
                }
                future.complete(productType + product);
              })
          .onError(
              error -> System.out.println("retry: " + count.get() + "   " + error.getStackTrace()))
          .retry(3)
          .closeCircuitBreaker(0l)
          .onFailureRespond((error, response) -> response.complete(product + productType))
          .execute();
    }

    public void rsEndpointFive(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      Payload<String> pp = new Payload<>(productType + product);
      handler
          .response()
          .objectResponse((future) -> future.complete(pp), new ExampleStringEncoder())
          .execute();
    }

    public void rsEndpointFive_error(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      Payload<String> pp = new Payload<>(productType + product);
      AtomicInteger count = new AtomicInteger(4);
      handler
          .response()
          .objectResponse(
              (future) -> {
                if (count.decrementAndGet() >= 0) {
                  System.out.println("throw:" + count.get());
                  throw new NullPointerException("test");
                }
                future.complete(new Payload<>("hallo"));
              },
              new ExampleStringEncoder())
          .retry(3)
          .onFailureRespond((error, future) -> future.complete(pp), new ExampleStringEncoder())
          .execute();
    }

    public void rsEndpointSix(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      Payload<String> pp = new Payload<>(productType + product);
      handler
          .response()
          .objectResponse((future) -> future.complete(pp), new ExampleByteEncoder())
          .execute();
    }

    public void rsEndpointSeven(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      Payload<String> pp = new Payload<>(productType + product);
      handler
          .response()
          .byteResponse((future) -> future.complete(Serializer.serialize(pp)))
          .execute();
    }

    public void rsEndpointSeven_error(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      AtomicInteger count = new AtomicInteger(4);
      Payload<String> pp = new Payload<>(productType + product);
      handler
          .response()
          .byteResponse(
              (future) -> {
                if (count.decrementAndGet() >= 0) {
                  System.out.println("throw:" + count.get());
                  throw new NullPointerException("test");
                }
                future.complete(Serializer.serialize(pp));
              })
          .retry(3)
          .onFailureRespond(
              (error, future) -> {
                try {
                  future.complete(Serializer.serialize(pp));
                } catch (IOException e) {
                  e.printStackTrace();
                }
                future.complete(null);
              })
          .execute();
    }

    public void rsEndpointEight_header(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      AtomicInteger count = new AtomicInteger(4);
      Payload<String> pp = new Payload<>(productType + product);
      handler
          .response()
          .stringResponse(
              (future) -> {
                future.complete(productType + product);
              })
          .execute("application/json");
    }

    public void rsEndpointEight_put_header(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      AtomicInteger count = new AtomicInteger(4);
      Payload<String> pp = new Payload<>(productType + product);
      handler
          .response()
          .stringResponse(
              (future) -> {
                future.complete(productType + product);
              })
          .putHeader("key", "val")
          .execute("application/json");
    }

    public void rsEndpointNine_exception(RestHandler handler) {
      String productType = handler.request().param("val");
      String product = handler.request().param("tmp");
      System.out.println("wsEndpointTwo: " + handler);
      handler
          .response()
          .stringResponse(
              (future) -> {
                throw new NullPointerException("test");
              })
          .putHeader("key", "val")
          .execute("application/json");
    }

  }
}