text:
import {Meteor} from 'meteor/meteor';

import _ from 'underscore';

import Tables from '/imports/collections/tables';
import Reference from '/imports/collections/reference';
import ExposureResult from '/imports/collections/exposureResult';

import collSorts from '../sorts';
import { attachTableSchema } from '../schemas';

import schema_extension from './schema';
import {
    exposureScenarios,
    samplingApproaches,
    exposureLevelDescriptions,
    isOccupational,
} from './constants';

let instanceMethods = {
        isOccupational: function(){
            return isOccupational(this.exposureScenario);
        },
        setWordFields: function() {
            this.isOccupational = this.isOccupational();
            this.results.forEach((d) => d.setWordFields());
        },
        getReference: function(){
            if (_.isUndefined(this.reference)){
                this.reference = Reference.findOne(this.referenceID);
            }
            return this.reference;
        },
        getResults: function(){
            if (_.isUndefined(this.results)){
                this.results = ExposureResult
                        .find({parent_id: this._id}, {sort: {sortIdx: 1}})
                        .fetch();
            }
            return this.results;
        },
    },
    classMethods = {
        exposureScenarios,
        samplingApproaches,
        exposureLevelDescriptions,
        isOccupational: function(val){
            return isOccupational(val);
        },
        getTableEvidence: function(tbl_id){
            return ExposureEvidence
                .find({tbl_id: tbl_id}, {sort: {sortIdx: 1}})
                .fetch();
        },
        tabular: function(tbl_id) {

            let getResultData = function(results, row) {
                    return results.map(function(d){
                        let row2 = row.slice();  // shallow-copy
                        row2.push(
                            d._id,
                            d.agent, d.samplingMatrix, d.samplingApproach, d.numberMeasurements, d.measurementDuration,
                            d.exposureLevel, d.exposureLevelDescription, d.exposureLevelRange, d.units
                        );
                        return row2;
                    });
                },
                header = [
                    'Exposure ID', 'Reference', 'Reference year', 'Pubmed ID',
                    'Country', 'Location',
                    'Collection date', 'Exposure scenario', 'Occupation', 'Occupational information',
                    'Comments',

                    'Result ID',
                    'Agent', 'Sampling Matrix', 'Sampling Approach', 'Number of measurements', 'Measurement duration',
                    'Exposure level', 'Exposure level description', 'Exposure level range', 'Units',
                ],
                data = [header],
                qs = ExposureEvidence.getTableEvidence(tbl_id);

            qs.forEach(function(d){
                d.getReference();
                d.getResults();
                let row = [
                        d._id, d.reference.name, d.reference.getYear(), d.reference.pubmedID,
                        d.country, d.location,
                        d.collectionDate, d.exposureScenario, d.occupation, d.occupationInfo,
                        d.comments,
                    ],
                    rows = getResultData(d.results, row);

                data.push.apply(data, rows);
            });
            return data;
        },
        wordReportFormats: [
            {
                'type': 'ExposureTables',
                'fn': 'exposure',
                'text': 'Download Word',
            },
            {
                'type': 'ExposureHtmlTable',
                'fn': 'exposure',
                'text': 'Download Word (HTML re-creation)',
            },
        ],
        wordHtmlContext(tbl_id){
            var table = Tables.findOne(tbl_id),
                qs = ExposureEvidence.getTableEvidence(tbl_id);

            qs.forEach(function(d){
                d.getReference();
                d.getResults();
                d.setWordFields();
            });

            return {
                table,
                exposures: qs,
            };
        },
        wordContext(tbl_id){
            let context = this.wordHtmlContext(tbl_id),
                exposures = context.exposures;

            return {
                'table': context.table,
                'occupationals': exposures.filter((d) => d.exposureScenario === 'Occupational'),
                'environmentals': exposures.filter((d) => d.exposureScenario === 'Environmental'),
                'mixed': exposures.filter((d) => d.exposureScenario === 'Integrated/mixed'),
            };
        },
        sortFields: {
            'Reference':            collSorts.sortByReference,
            'Exposure scenario':    _.partial(collSorts.sortByFieldOrder, exposureScenarios, 'exposureScenario'),
            'Industry/occupation':  _.partial(collSorts.sortByTextField, 'occupation'),
            'Country':              _.partial(collSorts.sortByTextField, 'country'),
            'Collection date':      _.partial(collSorts.sortByTextField, 'collectionDate'),
        },
    },
    ExposureEvidence = new Meteor.Collection('exposureEvidence', {
        transform: function (doc) {
            return  _.extend(Object.create(instanceMethods), doc);
        },
    });

_.extend(ExposureEvidence, classMethods);
attachTableSchema(ExposureEvidence, schema_extension);

export default ExposureEvidence;


text:
from distance.filter.goldify import GoldifyFilter
from distance.filter.remove import RemoveFilter
from distance.filter.unkill import UnkillFilter
from distance.filter.visualize import VisualizeFilter
from distance.filter.settings import SettingsFilter
from distance.filter.downgrade import DowngradeFilter

__all__ = [
    'getfilter',
]

_filters = {
    'goldify' : GoldifyFilter,
    'rm' : RemoveFilter,
    'unkill' : UnkillFilter,
    'vis' : VisualizeFilter,
    'settings' : SettingsFilter,
    'downgrade' : DowngradeFilter,
}

def getfilter(name):
    return _filters[name]

# vim:set sw=4 ts=8 sts=4 et:

redpajama_set_name: RedPajamaGithub


text:
package google

import (
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccDataSourceGoogleClientOpenIDUserinfo_basic(t *testing.T) {
	t.Parallel()

	vcrTest(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			{
				Config: testAccCheckGoogleClientOpenIDUserinfo_basic,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttrSet("data.google_client_openid_userinfo.me", "email"),
				),
			},
		},
	})
}

const testAccCheckGoogleClientOpenIDUserinfo_basic = `
data "google_client_openid_userinfo" "me" {}
`


text:
__author__ = 'Jonathan Spitz'

import numpy as np
import matplotlib.pyplot as plt
import datetime
import json

# ############################## GENETIC ALGORITHM CLASS ############################## #
# A GenAlg object runs a genetic algorithm optimization for a given problem.
# To create an object you'll need to provide:
#       * A population size
#       * Max number of generations to run
#       * A testing object with a "test_pop" method
#       * A selection object with a "pick_pop" method
#       * A reproduction object with a "build_pop" method
# If no initial population is passed to the constructor, "build_pop" will be called to
# generate a random initial population.
# An end-condition function handle can be passed to stop the optimization. GenAlg will
# call this function and pass the fitness values encountered thus far. The function
# should return 0 to continue the optimization or 1 to stop the optimization. If no
# endCond is passed, GenAlg will run until the max number of generations is reached.
class GenAlg:
    # GenAlg constructor
    def __init__(self, n_genomes, n_generations, tester, picker, builder, init_pop=0, end_cond=0, filename=[]):
        self.verbose = True  # Set to true to print out intermediate optimization results

        self.nGenomes = n_genomes
        self.nGenerations = n_generations
        self.endCond = end_cond

        self.Tester = tester
        self.Picker = picker
        self.Builder = builder

        # Store the endCond function handle or use the built-in "0" function
        if hasattr(end_cond, '__call__'):
            self.endCond = end_cond
        else:
            self.endCond = lambda fits: self.false_cond()

        # Prepare initial population if none was given
        if not init_pop:
            init_pop, init_par = self.Builder.build_pop(n_genomes)
        else:
            init_par = [[] for i in range(n_genomes)]

        # Get the genome size from the new population
        self.genomeLen = len(init_pop[0])

        # Prepare the data structures
        self.Gens = [init_pop]      # Stores all the genomes
        self.Fits = []              # Stores all the fitness values
        self.Parents = init_par     # Stores all the genome parents (for ancestry)

        self.fit_max = []           # Stores the max fitness values
        self.fit_mean = []          # Stores the mean fitness values

        # Data saving info
        if not filename:
            self.save_filename = "GA-" + datetime.datetime.now().strftime("%m_%d-%H_%M") + ".txt"
        else:
            self.save_filename = filename
        self.description = "Results for GA with " + self.Tester.name + ", " + self.Picker.name + " and " \
                           + self.Builder.name + ".\n" \
                           + "Ran a population of " + str(self.nGenomes) + " over {0} generations on " \
                           + datetime.datetime.now().strftime("%Y-%m-%d starting at %H:%M")

        self.curGen = 0
    # End GenAlg constructor

    def load(self, filename):
        # Load data from the save file provided
        with open(filename, 'r') as f:
            data = json.load(f)
            print bcolors.OKGREEN + "Loaded data from " + filename + ":" + bcolors.ENDC
            print bcolors.OKBLUE + data[0] + bcolors.ENDC + "\n"
            self.Gens = [data[1][-1]]
        return self

    def run(self):
        if self.verbose:
            print bcolors.HEADER + bcolors.BOLD + "Running Genetic Algorithm..." + bcolors.ENDC

        # Open save file with 'w' to clean it up
        with open(self.save_filename, 'w') as f:
            f.close()

        # While the end-condition or the max. number of generations hasn't been reached do:
        while self.curGen < self.nGenerations and not self.endCond(self.Fits):
            if self.verbose:
                print bcolors.OKGREEN + "Running generation " + str(self.curGen) + \
                    " out of " + str(self.nGenerations) + bcolors.ENDC
                # TODO: calculate a run-time estimate for each generation

            # Calculate the current population's fitness
            fitness = self.Tester.test_pop(self.Gens[self.curGen])
            self.Fits.append(fitness)

            fit_array = np.array(fitness)
            fit_max = np.max(fit_array, 0)
            fit_mean = np.mean(fit_array, 0)
            self.fit_max.append(fit_max.tolist())
            self.fit_mean.append(fit_mean.tolist())

            if self.verbose:
                # Print average and max fitness values
                print bcolors.OKBLUE + "Top fitness results: "+str(fit_max)
                print "Avg. fitness results: "+str(fit_mean)
                print "" + bcolors.ENDC

            # Save results
            with open(self.save_filename, 'w') as f:
                output = [self.description.format(self.curGen+1), self.Gens, self.Fits]
                json.dump(output, f)
                f.close()

            # Select the top population for reproduction
            top_pop = self.Picker.pick_pop(self.nGenomes, fitness)

            # Build the next generation
            new_pop, parents = self.Builder.build_pop(self.Gens[self.curGen], top_pop)
            self.Gens.append(new_pop)
            self.Parents.append(parents)

            # Advance the generation counter
            self.curGen += 1

        if self.verbose:
            print 'Finished running Genetic Algorithm'
            plt.plot(range(self.nGenerations), self.fit_max)
            plt.plot(range(self.nGenerations), self.fit_mean)
            plt.show()

        return self

    @staticmethod
    def false_cond():
        return 0

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


text:
/*
 *  Document   : uiProgress.js
 *  Author     : pixelcave
 */
var UiProgress=function(){var r=function(r,t){return Math.floor(Math.random()*(t-r+1))+r};return{init:function(){var t=0;$(".toggle-bars").click(function(){$(".progress-bar",".bars-container").each(function(){t=r(10,100)+"%",$(this).css("width",t).html(t)}),$(".progress-bar",".bars-stacked-container").each(function(){t=r(10,25)+"%",$(this).css("width",t).html(t)})})}}}();


text:
<mvc:View controllerName="sap.ui.demokit.icex.view.Detail"
	xmlns="sap.m"
	xmlns:core="sap.ui.core"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns:h="http://www.w3.org/1999/xhtml">
	<Page
		id="page"
		title="{/name}"
		icon="{img>/icon/ui5}"
		showNavButton="{/isPhone}"
		navButtonPress="navBack">
		<headerContent>
			<Button
				icon="sap-icon://favorite"
				tooltip="Add Icon to Favorites"
				press="favorite"
				visible="{/showFavorite}">
			</Button>
			<Button
				icon="sap-icon://unfavorite"
				tooltip="Remove Icon from Favorites"
				press="favorite"
				visible="{/showUnfavorite}">
			</Button>
		</headerContent>
		<subHeader>
			<Toolbar>
				<ToolbarSpacer/>
				<Button icon="sap-icon://{/name}">
				</Button>
				<Button icon="sap-icon://{/name}">
				</Button>
				<Button icon="sap-icon://{/name}">
				</Button>
				<Button icon="sap-icon://{/name}">
				</Button>
				<ToolbarSpacer/>
			</Toolbar>
		</subHeader>
		<footer>
			<Toolbar>
				<ToolbarSpacer/>
				<Button icon="sap-icon://{/name}" visible="{/isNoPhone}">
				</Button>
				<Button icon="sap-icon://{/name}">
				</Button>
				<Button icon="sap-icon://{/name}">
				</Button>
				<Button icon="sap-icon://{/name}" visible="{/isNoPhone}">
				</Button>
				<ToolbarSpacer/>
				<Label text="id: {/id}">
				</Label>
			</Toolbar>
		</footer>
		<content>
			<HBox>
				<core:Icon src="sap-icon://{/name}" size="7em" class="preview previewColor1">
					<core:layoutData><FlexItemData growFactor="1" /></core:layoutData>
				</core:Icon>
				<core:Icon src="sap-icon://{/name}" size="7em" class="preview previewColor2">
					<core:layoutData><FlexItemData growFactor="1" /></core:layoutData>
				</core:Icon>
				<core:Icon src="sap-icon://{/name}" size="7em" class="preview previewColor3" visible="{/isNoPhone}">
					<core:layoutData><FlexItemData growFactor="1" /></core:layoutData>
				</core:Icon>
				<core:Icon src="sap-icon://{/name}" size="7em" class="preview previewColor4" visible="{/isNoPhone}">
					<core:layoutData><FlexItemData growFactor="1" /></core:layoutData>
				</core:Icon>
			</HBox>
			<List>
				<StandardListItem type="Inactive" icon="sap-icon://{/name}" title="{/name}"
					description="Lorem ipsum dolor sit amet, consetetur sadipscing elitr">
				</StandardListItem>
				<StandardListItem type="Inactive" icon="sap-icon://{/name}" title="{/name}"
					description="Lorem ipsum dolor sit amet, consetetur sadipscing elitr">
				</StandardListItem>
				<StandardListItem type="Navigation" icon="sap-icon://{/name}" title="{/name}"
					description="Lorem ipsum dolor sit amet, consetetur sadipscing elitr">
				</StandardListItem>
				<StandardListItem type="Navigation" icon="sap-icon://{/name}" title="{/name}"
					description="Lorem ipsum dolor sit amet, consetetur sadipscing elitr">
				</StandardListItem>
			</List>
			<HBox class="detailButtonBox">
				<Button
					icon="sap-icon://{/name}"
					text="Button"
					type="Accept">
					<layoutData><FlexItemData growFactor="1" /></layoutData>
				</Button>
				<Button
					icon="sap-icon://{/name}"
					text="Button"
					type="Reject">
					<layoutData><FlexItemData growFactor="1" /></layoutData>
				</Button>
				<Button
					icon="sap-icon://{/name}"
					text="Button">
					<layoutData><FlexItemData growFactor="1" /></layoutData>
				</Button>
				<Button
					icon="sap-icon://{/name}"
					text="Button">
					<layoutData><FlexItemData growFactor="1" /></layoutData>
				</Button>
			</HBox>
		</content>
	</Page>
</mvc:View>


text:
import Map = require("esri/Map");
import SceneView = require("esri/views/SceneView");
import Search = require("esri/widgets/Search");

const map = new Map({
    basemap: "dark-gray" as any
});
const view = new SceneView({
    map: map,
    container: "viewDiv",
    center: [-106.45, 31.76] as any,
    zoom: 16
});

// Create a logo image
const logo = document.createElement("img");
logo.src = "https://placeholdit.imgix.net/~text?bg=000&txtclr=e8117f&txtsize=48&txt=logo&w=100&h=80";
logo.title = "Logo";

const search = new Search({
    view: view
});

view.ui.add(logo, "bottom-right");
view.ui.add(search, "top-right");


text:
<?php

namespace Qafoo\ChangeTrack\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class AnonymouseServiceGenerator
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerBuilder
     */
    private $container;

    /**
     * @var int
     */
    private $runningNumber = 0;

    /**
     * @var string
     */
    private $seed;

    /**
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
     */
    public function __construct(ContainerBuilder $container)
    {
        $this->container = $container;
    }

    /**
     * @param \Symfony\Component\DependencyInjection\Definition $definition
     * @return \Symfony\Component\DependencyInjection\Reference Reference to the anonymous service
     */
    public function registerAnonymousService(Definition $definition)
    {
        $serviceId = $this->generateUniqueServiceId($definition->getClass());
        $this->container->setDefinition($serviceId, $definition);
        return new Reference($serviceId);
    }

    /**
     * Generates a service ID somewhat unique and speaking for our project.
     *
     * @param string $serviceClass
     * @return string
     */
    private function generateUniqueServiceId($serviceClass)
    {
        return sprintf(
            '__%s.%s.%s',
            strtr($serviceClass, '\\', '.'),
            $this->getSeed(),
            ++$this->runningNumber
        );
    }

    /**
     * Returns a random seed to make service IDs unique across instances.
     *
     * @return string
     */
    private function getSeed()
    {
        if (!isset($this->seed)) {
            $this->seed = substr(md5(microtime()), 0, 5);
        }
        return $this->seed;
    }
}


text:
namespace DKFramework
{
	class DKMatrix4;
	/// @brief a Euclidean vector for four-dimensional space.
	class DKGL_API DKVector4
	{
	public:
		DKVector4();
		DKVector4(float x_, float y_, float z_, float w_);

		static DKVector4 Cross(const DKVector4&v1, const DKVector4& v2, const DKVector4& v3);///< cross product
		static float Dot(const DKVector4& v1, const DKVector4& v2); ///< dot product

		bool operator == (const DKVector4& v) const;
		bool operator != (const DKVector4& v) const;

		DKVector4 operator + (const DKVector4& v) const;
		DKVector4 operator - (const DKVector4& v) const;
		DKVector4 operator - () const;
		DKVector4 operator * (float f) const;
		DKVector4 operator * (const DKVector4& v) const;
		DKVector4 operator * (const DKMatrix4& m) const;
		DKVector4 operator / (float f) const;
		DKVector4 operator / (const DKVector4& v) const;

		DKVector4& operator += (const DKVector4& v);
		DKVector4& operator -= (const DKVector4& v);
		DKVector4& operator *= (float f);
		DKVector4& operator *= (const DKVector4& v);
		DKVector4& operator *= (const DKMatrix4& m);
		DKVector4& operator /= (float f);
		DKVector4& operator /= (const DKVector4& v);

		float Length() const;
		float LengthSq() const; ///< length^2

		DKVector4& Transform(const DKMatrix4& m);
		DKVector4& Normalize();

		union
		{
			struct
			{
				float x, y, z, w;
			};
			float val[4];
		};

		static const DKVector4 zero;
	};
}
#pragma pack(pop)


text:
import asyncio
from unittest import mock

from aiorpcx import RPCError
from server.env import Env
from server.controller import Controller

loop = asyncio.get_event_loop()

def set_env():
    env = mock.create_autospec(Env)
    env.coin = mock.Mock()
    env.loop_policy = None
    env.max_sessions = 0
    env.max_subs = 0
    env.max_send = 0
    env.bandwidth_limit = 0
    env.identities = ''
    env.tor_proxy_host = env.tor_proxy_port = None
    env.peer_discovery = env.PD_SELF = False
    env.daemon_url = 'http://localhost:8000/'
    return env

async def coro(res):
    return res

def raise_exception(msg):
    raise RPCError(1, msg)

def ensure_text_exception(test, exception):
    res = err = None
    try:
        res = loop.run_until_complete(test)
    except Exception as e:
        err = e
    assert isinstance(err, exception), (res, err)

def test_transaction_get():
    async def test_verbose_ignore_by_backend():
        env = set_env()
        sut = Controller(env)
        sut.daemon_request = mock.Mock()
        sut.daemon_request.return_value = coro('11'*32)
        res = await sut.transaction_get('ff'*32, True)
        assert res == '11'*32

    async def test_verbose_ok():
        env = set_env()
        sut = Controller(env)
        sut.daemon_request = mock.Mock()
        response = {
            "hex": "00"*32,
            "blockhash": "ff"*32
        }
        sut.daemon_request.return_value = coro(response)
        res = await sut.transaction_get('ff'*32, True)
        assert res == response

        response = {
            "hex": "00"*32,
            "blockhash": None
        }
        sut.daemon_request.return_value = coro(response)
        res = await sut.transaction_get('ff'*32, True)
        assert res == response

    async def test_no_verbose():
        env = set_env()
        sut = Controller(env)
        sut.daemon_request = mock.Mock()
        response = 'cafebabe'*64
        sut.daemon_request.return_value = coro(response)
        res = await sut.transaction_get('ff'*32)
        assert res == response

    async def test_verbose_failure():
        env = set_env()
        sut = Controller(env)
        sut.daemon_request = mock.Mock()
        sut.daemon_request.return_value = coro(
            raise_exception('some unhandled error'))
        await sut.transaction_get('ff' * 32, True)

    async def test_wrong_txhash():
        env = set_env()
        sut = Controller(env)
        sut.daemon_request = mock.Mock()
        await sut.transaction_get('cafe')
        sut.daemon_request.assert_not_called()

    loop.run_until_complete(asyncio.gather(
        *[
            test_verbose_ignore_by_backend(),
            test_verbose_ok(),
            test_no_verbose()
        ]
    ))

    for error_test in [test_verbose_failure, test_wrong_txhash]:
        ensure_text_exception(error_test(), RPCError)


text:
package net.ssehub.easy.reasoning.sseReasoner.functions;

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

import net.ssehub.easy.basics.logger.EASyLoggerFactory;
import net.ssehub.easy.basics.modelManagement.ModelManagementException;
import net.ssehub.easy.reasoning.sseReasoner.Descriptor;
import net.ssehub.easy.reasoning.sseReasoner.functions.AbstractConstraintProcessor.ExpressionType;
import net.ssehub.easy.varModel.cst.AttributeVariable;
import net.ssehub.easy.varModel.cst.BlockExpression;
import net.ssehub.easy.varModel.cst.Comment;
import net.ssehub.easy.varModel.cst.CompoundAccess;
import net.ssehub.easy.varModel.cst.CompoundInitializer;
import net.ssehub.easy.varModel.cst.ConstantValue;
import net.ssehub.easy.varModel.cst.ConstraintSyntaxTree;
import net.ssehub.easy.varModel.cst.ContainerInitializer;
import net.ssehub.easy.varModel.cst.ContainerOperationCall;
import net.ssehub.easy.varModel.cst.DeferInitExpression;
import net.ssehub.easy.varModel.cst.IConstraintTreeVisitor;
import net.ssehub.easy.varModel.cst.IfThen;
import net.ssehub.easy.varModel.cst.Let;
import net.ssehub.easy.varModel.cst.MultiAndExpression;
import net.ssehub.easy.varModel.cst.OCLFeatureCall;
import net.ssehub.easy.varModel.cst.Parenthesis;
import net.ssehub.easy.varModel.cst.Self;
import net.ssehub.easy.varModel.cst.UnresolvedExpression;
import net.ssehub.easy.varModel.cst.Variable;
import net.ssehub.easy.varModel.model.AbstractVariable;
import net.ssehub.easy.varModel.model.Attribute;
import net.ssehub.easy.varModel.model.AttributeAssignment;
import net.ssehub.easy.varModel.model.Constraint;
import net.ssehub.easy.varModel.model.DecisionVariableDeclaration;
import net.ssehub.easy.varModel.model.IModelElement;
import net.ssehub.easy.varModel.model.IModelVisitor;
import net.ssehub.easy.varModel.model.Project;
import net.ssehub.easy.varModel.model.ProjectImport;
import net.ssehub.easy.varModel.model.datatypes.AnyType;
import net.ssehub.easy.varModel.model.datatypes.BooleanType;
import net.ssehub.easy.varModel.model.datatypes.Compound;
import net.ssehub.easy.varModel.model.datatypes.ConstraintType;
import net.ssehub.easy.varModel.model.datatypes.DerivedDatatype;
import net.ssehub.easy.varModel.model.datatypes.Enum;
import net.ssehub.easy.varModel.model.datatypes.IDatatype;
import net.ssehub.easy.varModel.model.datatypes.IDatatypeVisitor;
import net.ssehub.easy.varModel.model.datatypes.IntegerType;
import net.ssehub.easy.varModel.model.datatypes.MetaType;
import net.ssehub.easy.varModel.model.datatypes.OrderedEnum;
import net.ssehub.easy.varModel.model.datatypes.RealType;
import net.ssehub.easy.varModel.model.datatypes.Sequence;
import net.ssehub.easy.varModel.model.datatypes.StringType;
import net.ssehub.easy.varModel.model.datatypes.TypeQueries;
import net.ssehub.easy.varModel.model.datatypes.VersionType;
import net.ssehub.easy.varModel.model.filter.ConstraintFinder;

/**
 * Generic constraint functions based on the {@link AbstractConstraintProcessor}.
 *
 * @author Holger Eichelberger
 */
public class ConstraintFunctions {

    /**
     * Processes all constraints relevant to the given {@link Compound}.
     *
     * @param cmpType Compound to be processed.
     * @param processor The constraint processor functor.
     * @param includeConstraintVariables true whether constraint variables shall be included.
     * @param includeDefaults true whether default value expressions shall be included.
     * @param parent the intended parent for constraints, typically the containing project
     */
    public static void allCompoundConstraints(Compound cmpType, AbstractConstraintProcessor processor,
        boolean includeConstraintVariables, boolean includeDefaults, IModelElement parent) {
        if (!processor.getContextStack().isTypeExcluded(cmpType)) {
            for (int c = 0; c < cmpType.getConstraintsCount(); c++) {
                processor.process(cmpType.getConstraint(c), ExpressionType.CONSTRAINT);
            }
            if (includeConstraintVariables || includeDefaults) {
                for (int i = 0; i < cmpType.getElementCount(); i++) {
                    DecisionVariableDeclaration decl = cmpType.getElement(i);
                    ConstraintSyntaxTree defaultValue = decl.getDefaultValue();
                    if (null != defaultValue) {
                        if (includeConstraintVariables && TypeQueries.isConstraint(decl.getType())) {
                            processor.process(defaultValue, ExpressionType.CONSTRAINT_VALUE, decl.getName(), parent);
                        } else if (includeDefaults) {
                            processor.process(defaultValue, ExpressionType.DEFAULT, decl.getName(), parent);
                        }
                    }
                    for (int a = 0, n = decl.getAttributesCount(); includeDefaults && a < n; a++) {
                        Attribute attr = decl.getAttribute(a);
                        defaultValue = attr.getDefaultValue();
                        if (null != defaultValue) {
                            processor.process(defaultValue, ExpressionType.ANNOTATION_DEFAULT, attr.getName(), parent);
                        }
                    }
                }
            }
            for (int r = 0; r < cmpType.getRefinesCount(); r++) {
                allCompoundConstraints(cmpType.getRefines(r), processor, includeConstraintVariables,
                    includeDefaults, parent);
            }
            for (int a = 0; a < cmpType.getAssignmentCount(); a++) {
                allAssignmentConstraints(cmpType.getAssignment(a), processor);
            }
        }
    }

    /**
     * Processes all assignment constraints.
     *
     * @param assng the assignment constraint
     * @param processor the constraint processor for assignment constraints
     */
    public static void allAssignmentConstraints(AttributeAssignment assng, AbstractConstraintProcessor processor) {
        for (int c = 0; c < assng.getConstraintsCount(); c++) {
            processor.process(assng.getConstraint(c), ExpressionType.ASSIGNMENT_CONSTRAINT);
        }
        for (int a = 0; a < assng.getAssignmentCount(); a++) {
            allAssignmentConstraints(assng.getAssignment(a), processor);
        }
    }

    /**
     * A transitive constraint/variables finder.
     *
     * @author Holger Eichelberger
     */
    private static class TransitiveConstraintFinder extends ConstraintFinder implements IConstraintTreeVisitor,
        IDatatypeVisitor {

        private boolean add;
        private Set<AbstractVariable> variables = new HashSet<AbstractVariable>();
        private Set<AbstractVariable> scheduled = new HashSet<AbstractVariable>();
        private Set<AbstractVariable> candidates = new HashSet<AbstractVariable>();
        private Set<Object> done = new HashSet<Object>();
        private Project scope;
        private Project target;
        private IModelVisitor mVisitor;

        /**
         * Creates a finder with search scope and target project.
         *
         * @param scope the scope
         * @param target the target project
         */
        public TransitiveConstraintFinder(Project scope, Project target) {
            super(scope);
            this.scope = scope;
            this.target = target;
            mVisitor = this;
        }

        @Override
        protected void startAccept(Project project) {
            // override, do nothing; allow for further init in constructor
        }

        /**
         * Call for the top-level variable to be visited.
         *
         * @param var the variable
         */
        public void visit(AbstractVariable var) {
            addToVariables(var);
            scope.accept(this);
            while (!scheduled.isEmpty()) {
                boolean visitAgain = false;
                for (AbstractVariable v : scheduled) {
                    if (!variables.contains(v)) {
                        addToVariables(var);
                        // TODO duplicate variables, mock the target imports
                        target.add(v);
                        visitAgain = true;
                    }
                }
                scheduled.clear();
                if (visitAgain) {
                    scope.accept(this);
                }
            }
        }

        /**
         * Internal method to start visiting a datatype. Due to additional checks,
         * please do not visit the type directly.
         *
         * @param type the type to be visited
         */
        private void visit(IDatatype type) {
            if (null != type && !done.contains(type)) {
                done.add(type);
                type.accept(this);
            }
        }

        /**
         * Adds a variable to {@link #variables}.
         *
         * @param var the variable
         */
        private void addToVariables(AbstractVariable var) {
            variables.add(var);
            var.accept(mVisitor);
        }

        @Override
        public void visitDecisionVariableDeclaration(DecisionVariableDeclaration decl) {
            visit(decl.getType());
            if (null != decl.getDefaultValue()) {
                int size = candidates.size();
                decl.getDefaultValue().accept(this);
                if (candidates.size() > size) { // add does not work here, default expression
                    scheduled.addAll(candidates);
                    candidates.clear();
                }
            }
        }

        @Override
        public void visitConstraint(Constraint constraint) {
            add = false;
            constraint.getConsSyntax().accept(this);
            if (add) {
                target.addConstraint(constraint);
                scheduled.addAll(candidates);
                candidates.clear();
            }
        }

        @Override
        public void visitProject(Project project) {
            Project old = target;
            String pName = project.getName();
            for (int i = 0; old == target && i < old.getImportsCount(); i++) {
                ProjectImport imp = old.getImport(i);
                if (imp.getName().equals(pName) && null != imp.getResolved()) {
                    target = imp.getResolved();
                }
            }
            if (old == target) {
                target = new Project(pName);
                ProjectImport imp = new ProjectImport(pName);
                try {
                    imp.setResolved(target);
                    old.addImport(imp);
                } catch (ModelManagementException e) {
                    EASyLoggerFactory.INSTANCE.getLogger(getClass(), Descriptor.BUNDLE_NAME);
                }
            }
            super.visitProject(project);
        }

        @Override
        public void visitConstantValue(ConstantValue value) {
        }

        /**
         * Handles the occurrence of a variable.
         *
         * @param variable the variable
         */
        private void handle(AbstractVariable variable) {
            boolean found = variables.contains(variable);
            if (!found) {
                candidates.add(variable);
            }
            add |= found;
        }

        @Override
        public void visitVariable(Variable variable) {
            handle(variable.getVariable());
        }

        @Override
        public void visitAnnotationVariable(AttributeVariable variable) {
            handle(variable.getVariable());
        }

        @Override
        public void visitParenthesis(Parenthesis parenthesis) {
            parenthesis.getExpr().accept(this);
        }

        @Override
        public void visitComment(Comment comment) {
        }

        @Override
        public void visitOclFeatureCall(OCLFeatureCall call) {
            if (null != call.getOperand()) {
                call.getOperand().accept(this);
            }
            for (int p = 0; p < call.getParameterCount(); p++) {
                call.getParameter(p).accept(this);
            }
        }

        @Override
        public void visitLet(Let let) {
            let.getInExpression().accept(this);
        }

        @Override
        public void visitIfThen(IfThen ifThen) {
            ifThen.getIfExpr().accept(this);
            if (null != ifThen.getElseExpr()) {
                ifThen.getElseExpr().accept(this);
            }
        }

        @Override
        public void visitContainerOperationCall(ContainerOperationCall call) {
            call.getExpression().accept(this);
        }

        @Override
        public void visitCompoundAccess(CompoundAccess access) {
            if (null != access.getResolvedSlot()) {
                access.getResolvedSlot().accept(mVisitor);
            }
        }

        @Override
        public void visitUnresolvedExpression(UnresolvedExpression expression) {
        }

        @Override
        public void visitCompoundInitializer(CompoundInitializer initializer) {
            for (int e = 0; e < initializer.getExpressionCount(); e++) {
                initializer.getExpression(e).accept(this);
            }
        }

        @Override
        public void visitContainerInitializer(ContainerInitializer initializer) {
            for (int e = 0; e < initializer.getExpressionCount(); e++) {
                initializer.getExpression(e).accept(this);
            }
        }

        @Override
        public void visitSelf(Self self) {
        }

        @Override
        public void visitBlockExpression(BlockExpression block) {
            for (int e = 0; e < block.getExpressionCount(); e++) {
                block.getExpression(e).accept(this);
            }
        }

        @Override
        public void visitDeferInitExpression(DeferInitExpression expression) {
            expression.getExpression().accept(this);
        }

        @Override
        public void visitMultiAndExpression(MultiAndExpression expression) {
            for (int e = 0; e < expression.getExpressionCount(); e++) {
                expression.getExpression(e).accept(this);
            }
        }

        @Override
        public void visitDatatype(IDatatype datatype) {
        }

        @Override
        public void visitAnyType(AnyType datatype) {
        }

        @Override
        public void visitMetaType(MetaType datatype) {
        }

        @Override
        public void visitDerivedType(DerivedDatatype datatype) {
            datatype.getBasisType().accept(this);
        }

        @Override
        public void visitBooleanType(BooleanType type) {
        }

        @Override
        public void visitStringType(StringType type) {
        }

        @Override
        public void visitConstraintType(ConstraintType type) {
        }

        @Override
        public void visitIntegerType(IntegerType type) {
        }

        @Override
        public void visitVersionType(VersionType type) {
        }

        @Override
        public void visitRealType(RealType type) {
        }

        @Override
        public void visitCompoundType(Compound compound) {
            for (int e = 0; e < compound.getElementCount(); e++) {
                compound.getElement(e).accept(mVisitor);
            }
            for (int a = 0; a < compound.getAssignmentCount(); a++) {
                compound.getAssignment(a).accept(mVisitor);
            }
        }

        @Override
        public void visitAttributeAssignment(AttributeAssignment assignment) {
            for (int e = 0; e < assignment.getElementCount(); e++) {
                assignment.getElement(e).accept(mVisitor);
            }
            super.visitAttributeAssignment(assignment);
        }

        @Override
        public void visitSet(net.ssehub.easy.varModel.model.datatypes.Set set) {
            for (int g = 0; g < set.getGenericTypeCount(); g++) {
                set.getGenericType(g).accept(this);
            }
        }

        @Override
        public void visitSequence(Sequence sequence) {
            for (int g = 0; g < sequence.getGenericTypeCount(); g++) {
                sequence.getGenericType(g).accept(this);
            }
        }

        @Override
        public void visitEnumType(Enum enumType) {
        }

        @Override
        public void visitOrderedEnumType(OrderedEnum enumType) {
        }

    }

    /**
     * Adds constraints related to {@code var} and transitively related constraints and variables
     * in {@code scope} to {@code target} although the parent relationships of the added variables/constraints
     * are then not correct. This method is intended for creating temporary projects/configurations.
     *
     * @param var the variable used as starting point for the transitive search
     * @param scope the search scope including imports
     * @param target the target project to add the elements to
     */
    public static void addConstraintsToProject(AbstractVariable var, Project scope, Project target) {
        new TransitiveConstraintFinder(scope, target).visit(var);
    }

}


text:
#ifndef BOOST_CONTAINERS_DETAIL_WORKAROUND_HPP
#define BOOST_CONTAINERS_DETAIL_WORKAROUND_HPP

#include <boost/interprocess/containers/container/detail/config_begin.hpp>

#if     defined(BOOST_HAS_RVALUE_REFS) && defined(BOOST_HAS_VARIADIC_TMPL)\
    && !defined(BOOST_INTERPROCESS_DISABLE_VARIADIC_TMPL)
#define BOOST_CONTAINERS_PERFECT_FORWARDING

#endif

#include <boost/interprocess/containers/container/detail/config_end.hpp>

#endif   //#ifndef BOOST_CONTAINERS_DETAIL_WORKAROUND_HPP


text:
module AmCharts
  module AmChartsHelper
    def amchart(chart, container)
      # Load necessary JS and CSS files, without loading one more than once
      @loaded_amchart_files ||= { js: [], css: []}

      js_files = ['amcharts', "amcharts/#{chart.type}"]
      js_files << "amcharts/lang/#{chart.language}" if chart.language? && chart.language != 'en' # English is default already

      css_files = ['amcharts']

      if chart.export?
        chart.export.settings.libs = { autoLoad: false } # Turn off automatic loading of libraries

        export_dir = 'amcharts/plugins/export'

        # For any export
        js_files << "#{export_dir}/export.min"
        js_files << "#{export_dir}/libs/fabric.js/fabric.min"

        # Used to offer download files
        js_files << "#{export_dir}/libs/FileSaver.js/FileSaver.min"

        # For PDF format
        js_files << "#{export_dir}/libs/pdfmake/pdfmake"
        js_files << "#{export_dir}/libs/pdfmake/vfs_fonts"

        # For XLSX format
        js_files << "#{export_dir}/libs/jszip/jszip.min"
        js_files << "#{export_dir}/libs/xlsx/xlsx"

        # Language support
        js_files << "#{export_dir}/lang/#{chart.language}" if chart.language?

        # CSS
        css_files << "#{export_dir}/export"
      end

      js_files -= @loaded_amchart_files[:js]
      css_files -= @loaded_amchart_files[:css]

      @loaded_amchart_files[:js] += js_files
      @loaded_amchart_files[:css] += css_files

      content_for(:javascript) { javascript_include_tag(*js_files) }
      content_for(:stylesheets) { stylesheet_link_tag(*css_files) }

      # Render the chart builder
      builder = AmCharts::ChartBuilder.new(chart, self)
      chart.container = container
      javascript_tag do
        builder.render_js('chart_builder', template_type: :file, locals: { chart: chart, container: container })
      end
    end
  end
end


text:
namespace Spextensions.Dynamics.Infrastructure
{
    public class SuccessfulInvocationResult : InvocationResult
    {
        public SuccessfulInvocationResult(object returnValue) : base(true, returnValue) {}
    }
}


text:
package wint.mvc.url;

import wint.core.config.Constants;
import wint.help.mvc.security.csrf.CsrfTokenUtil;
import wint.lang.convert.ConvertUtil;
import wint.lang.exceptions.UrlException;
import wint.lang.magic.MagicObject;
import wint.lang.magic.Property;
import wint.lang.utils.AutoFillArray;
import wint.lang.utils.NumberUtil;
import wint.lang.utils.StringUtil;
import wint.lang.utils.Tuple;
import wint.mvc.flow.FlowData;
import wint.mvc.holder.WintContext;
import wint.mvc.parameters.Parameters;
import wint.mvc.view.Render;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 一个urlBroker类,用于生成URL
 *
 * @author pister 2012-3-2 07:50:40
 */
public class UrlBroker implements Render {

    private String moduleName;
    private UrlBrokerService urlBrokerService;
    private String path;
    private String target;
    private LinkedHashMap<String, Object> queryData = new LinkedHashMap<String, Object>();
    private AutoFillArray<Object> arguments = new AutoFillArray<Object>();
    private String anchor;
    private String tokenName;
    private String pathAsTargetName;
    private boolean pathHasNumber;
    private String suffix;

    protected UrlBroker() {}

    public UrlBroker(String moduleName, UrlBrokerService urlBrokerService, String path, String target,
                     String tokenName, String pathAsTargetName, boolean pathHasNumber) {
        super();
        this.moduleName = moduleName;
        this.urlBrokerService = urlBrokerService;
        this.path = UrlBrokerUtil.normalizePath(path);
        target = StringUtil.getLastBefore(target, ".");
        this.target = StringUtil.camelToFixedString(target, "-");
        this.tokenName = tokenName;
        this.pathAsTargetName = pathAsTargetName;
        this.pathHasNumber = pathHasNumber;
    }

    /**
     * 参数,用于生成queryString
     * 同parameter
     *
     * @param name
     * @param value
     * @return
     */
    public UrlBroker param(String name, Object value) {
        return parameter(name, value);
    }

    /**
     * url上附带csrf token
     *
     * @return
     */
    public UrlBroker withToken() {
        return parameter(tokenName, CsrfTokenUtil.token());
    }

    /**
     * 参数,用于生成queryString
     *
     * @param name
     * @param value
     * @return
     */
    public UrlBroker parameter(String name, Object value) {
        name = StringUtil.camelToFixedString(name, "-");
        queryData.put(name, value);
        return this;
    }

    /**
     * 把对象的属性作为参数传入
     * @param object
     * @since 1.3.9.8
     * @return
     */
    public UrlBroker params(Object object) {
        return parameters(object);
    }

    public UrlBroker removeParam(String name) {
        name = StringUtil.camelToFixedString(name, "-");
        queryData.remove(name);
        return this;
    }

    /**
     * 从url的params中复制
     * @param names
     * @return
     */
    public UrlBroker fromParams(String ...names) {
        if (names == null || names.length == 0) {
            return this;
        }
        FlowData flowData = WintContext.getFlowData();
        if (flowData == null) {
            return this;
        }
        Parameters parameters = flowData.getParameters();
        for (String name : names) {
            String[] values = parameters.getStringArray(name);
            if (values == null) {
                continue;
            }
            for (String value : values) {
                parameter(name, value);
            }
        }
        return this;
    }

    /**
     * 把对象的属性作为参数传入
     * @param object
     * @since 1.3.9.8
     * @return
     */
    public UrlBroker parameters(Object object) {
        if (object == null) {
            return this;
        }
        if (object instanceof Map) {
            Map<String, Object> mapItems = (Map<String, Object>)object;
            for (Map.Entry<String, Object> entry : mapItems.entrySet()) {
                parameter(String.valueOf(entry.getKey()), entry.getValue());
            }
        } else {
            MagicObject mo = MagicObject.wrap(object);
            Map<String, Property> propertyMap = mo.getMagicClass().getReadAndWritableProperties();
            for (Map.Entry<String, Property> propertyEntry : propertyMap.entrySet()) {
                String name = propertyEntry.getKey();
                Property property = propertyEntry.getValue();
                Object value = property.getValue(object);
                parameter(name, value);
            }
        }
        return this;
    }

    /**
     * 设置arg参数
     * 同argument
     *
     * @param index
     * @param value
     * @return
     */
    public UrlBroker arg(int index, Object value) {
        return argument(index, value);
    }

    /**
     * 设置arg参数
     *
     * @param index
     * @param value
     * @return
     */
    public UrlBroker argument(int index, Object value) {
        if (StringUtil.isEmpty(target)) {
            this.setTarget(pathAsTargetName);
        }
        if (index > Constants.Url.MAX_ARGUMENT_COUNT) {
            throw new UrlException("url argument index is too large: " + index);
        }
        if (index == 0) {
            if (!pathHasNumber && !NumberUtil.isPositiveInteger(value)) {
                throw new UrlException("the first argument for url[" + target + "] must be a Positive Integer.");
            }
        }
        arguments.set(index, ArgumentEncoder.transformStringArgument(value));
        return this;
    }

    public UrlBroker appendPath(Object inputPath) {
        if (NumberUtil.isNumeric(ConvertUtil.toString(inputPath))) {
            pathHasNumber = true;
        }
        this.path = UrlBrokerUtil.appendPath(this.path, inputPath);
        return this;
    }

    public UrlBroker suffix(String suffix) {
        if (suffix != null && !suffix.startsWith(".")) {
            suffix = "." + suffix;
        }
        this.suffix = suffix;
        return this;
    }

    /**
     * 一次设置多个arg参数,参数索引从0开始
     *
     * @param values
     * @return
     */
    public UrlBroker arguments(Object... values) {
        if (values == null) {
            return this;
        }
        int index = 0;
        for (Object object : values) {
            argument(index, object);
            ++index;
        }
        return this;
    }

    /**
     * 一次设置多个arg参数,参数索引从0开始
     * 同arguments
     *
     * @param values
     * @return
     */
    public UrlBroker args(Object... values) {
        return arguments(values);
    }

    public String render() {
        if (StringUtil.isEmpty(target)) {
            this.setTarget(pathAsTargetName);
        }
        return urlBrokerService.render(this);
    }

    public Map<String, Object> getQueryData() {
        return queryData;
    }

    public AutoFillArray<Object> getArguments() {
        return arguments;
    }

    public String getPath() {
        return path;
    }

    public String getTarget() {
        return target;
    }

    public UrlBroker setTarget(String target) {
        String basePath = path;
        while (basePath.endsWith("/")) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        Tuple<String, String> pathAndTarget = UrlBrokerUtil.parseTarget(basePath, target, pathAsTargetName);

        this.path = UrlBrokerUtil.normalizePath(pathAndTarget.getT1());
        this.target = pathAndTarget.getT2();
        return this;
    }

    public String getAnchor() {
        return anchor;
    }

    public UrlBroker setAnchor(String anchor) {
        this.anchor = anchor;
        return this;
    }

    public String getModuleName() {
        return moduleName;
    }

    public String getSuffix() {
        return suffix;
    }
}


text:
package org.tuxdevelop.spring.batch.lightmin.batch.configuration;

/**
 * @author Marcel Becker
 * @since 0.3
 */
public enum BatchRepositoryType {

    MAP,
    JDBC
}


text:
package com.warrenstrange.googleauth;

/**
 * Date: 12/02/14
 * Time: 13:36
 *
 * @author Enrico M. Crisostomo
 */
public class GoogleAuthenticatorException extends RuntimeException {

    /**
     * Builds an exception with the provided error message.
     *
     * @param message the error message.
     */
    public GoogleAuthenticatorException(String message) {
        super(message);
    }

    /**
     * Builds an exception with the provided error mesasge and
     * the provided cuase.
     *
     * @param message the error message.
     * @param cause   the cause.
     */
    public GoogleAuthenticatorException(String message, Throwable cause) {
        super(message, cause);
    }
}


text:
class Group < ActiveRecord::Base
  attr_accessible :name

  has_and_belongs_to_many :tunes
end


text:
from __future__ import absolute_import

import os

from django.core.wsgi import get_wsgi_application

"""
WSGI config for ckeditor_demo project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ckeditor_demo.settings")

application = get_wsgi_application()


text:
package com.parse;

import android.util.SparseArray;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import bolts.Task;

/* package */ abstract class ParseEventuallyQueue {

  private boolean isConnected;

  /**
   * Gets notifications of various events happening in the command cache, so that tests can be
   * synchronized.
   */
  private TestHelper testHelper;

  public abstract void onDestroy();

  public void setConnected(boolean connected) {
    isConnected = connected;
  }

  public boolean isConnected() {
    return isConnected;
  }

  public abstract int pendingCount();

  public void setTimeoutRetryWaitSeconds(double seconds) {
    // do nothing
  }

  public void setMaxCacheSizeBytes(int bytes) {
    // do nothing
  }

  /** See class TestHelper below. */
  public TestHelper getTestHelper() {
    if (testHelper == null) {
      testHelper = new TestHelper();
    }
    return testHelper;
  }

  protected void notifyTestHelper(int event) {
    notifyTestHelper(event, null);
  }

  protected void notifyTestHelper(int event, Throwable t) {
    if (testHelper != null) {
      testHelper.notify(event, t);
    }
  }

  public abstract void pause();

  public abstract void resume();

  /**
   * Attempts to run the given command and any pending commands. Adds the command to the pending set
   * if it can't be run yet.
   *
   * @param command
   *          - The command to run.
   * @param object
   *          - If this command references an unsaved object, we need to remove any previous command
   *          referencing that unsaved object. Otherwise, it will get created over and over again.
   *          So object is a reference to the object, if it has no objectId. Otherwise, it can be
   *          null.
   */
  public abstract Task<JSONObject> enqueueEventuallyAsync(ParseRESTCommand command,
      ParseObject object);

  protected ParseRESTCommand commandFromJSON(JSONObject json)
      throws JSONException {
    ParseRESTCommand command = null;
    if (ParseRESTCommand.isValidCommandJSONObject(json)) {
      command = ParseRESTCommand.fromJSONObject(json);
    } else if (ParseRESTCommand.isValidOldFormatCommandJSONObject(json)) {
      // do nothing
    } else {
      throw new JSONException("Failed to load command from JSON.");
    }
    return command;
  }

  /* package */ Task<JSONObject> waitForOperationSetAndEventuallyPin(ParseOperationSet operationSet,
        EventuallyPin eventuallyPin) {
    return Task.forResult(null);
  }

  /* package */ abstract void simulateReboot();

  /**
   * Gets rid of all pending commands.
   */
  public abstract void clear();

  /**
   * Fakes an object update notification for use in tests. This is used by saveEventually to make it
   * look like test code has updated an object through the command cache even if it actually
   * avoided executing update by determining the object wasn't dirty.
   */
  void fakeObjectUpdate() {
    if (testHelper != null) {
      testHelper.notify(TestHelper.COMMAND_ENQUEUED);
      testHelper.notify(TestHelper.COMMAND_SUCCESSFUL);
      testHelper.notify(TestHelper.OBJECT_UPDATED);
    }
  }

  /**
   * Gets notifications of various events happening in the command cache, so that tests can be
   * synchronized. See ParseCommandCacheTest for examples of how to use this.
   */
  public static class TestHelper {
    private static final int MAX_EVENTS = 1000;

    public static final int COMMAND_SUCCESSFUL = 1;
    public static final int COMMAND_FAILED = 2;
    public static final int COMMAND_ENQUEUED = 3;
    public static final int COMMAND_NOT_ENQUEUED = 4;
    public static final int OBJECT_UPDATED = 5;
    public static final int OBJECT_REMOVED = 6;
    public static final int NETWORK_DOWN = 7;
    public static final int COMMAND_OLD_FORMAT_DISCARDED = 8;

    public static String getEventString(int event) {
      switch (event) {
        case COMMAND_SUCCESSFUL:
          return "COMMAND_SUCCESSFUL";
        case COMMAND_FAILED:
          return "COMMAND_FAILED";
        case COMMAND_ENQUEUED:
          return "COMMAND_ENQUEUED";
        case COMMAND_NOT_ENQUEUED:
          return "COMMAND_NOT_ENQUEUED";
        case OBJECT_UPDATED:
          return "OBJECT_UPDATED";
        case OBJECT_REMOVED:
          return "OBJECT_REMOVED";
        case NETWORK_DOWN:
          return "NETWORK_DOWN";
        case COMMAND_OLD_FORMAT_DISCARDED:
          return "COMMAND_OLD_FORMAT_DISCARDED";
        default:
          throw new IllegalStateException("Encountered unknown event: " + event);
      }
    }

    private SparseArray<Semaphore> events = new SparseArray<>();

    private TestHelper() {
      clear();
    }

    public void clear() {
      events.clear();
      events.put(COMMAND_SUCCESSFUL, new Semaphore(MAX_EVENTS));
      events.put(COMMAND_FAILED, new Semaphore(MAX_EVENTS));
      events.put(COMMAND_ENQUEUED, new Semaphore(MAX_EVENTS));
      events.put(COMMAND_NOT_ENQUEUED, new Semaphore(MAX_EVENTS));
      events.put(OBJECT_UPDATED, new Semaphore(MAX_EVENTS));
      events.put(OBJECT_REMOVED, new Semaphore(MAX_EVENTS));
      events.put(NETWORK_DOWN, new Semaphore(MAX_EVENTS));
      events.put(COMMAND_OLD_FORMAT_DISCARDED, new Semaphore(MAX_EVENTS));
      for (int i = 0; i < events.size(); i++) {
        int event = events.keyAt(i);
        events.get(event).acquireUninterruptibly(MAX_EVENTS);
      }
    }

    public int unexpectedEvents() {
      int sum = 0;
      for (int i = 0; i < events.size(); i++) {
        int event = events.keyAt(i);
        sum += events.get(event).availablePermits();
      }
      return sum;
    }

    public List<String> getUnexpectedEvents() {
      List<String> unexpectedEvents = new ArrayList<>();
      for (int i = 0; i < events.size(); i++) {
        int event = events.keyAt(i);
        if (events.get(event).availablePermits() > 0) {
          unexpectedEvents.add(getEventString(event));
        }
      }
      return unexpectedEvents;
    }

    public void notify(int event) {
      notify(event, null);
    }

    public void notify(int event, Throwable t) {
      events.get(event).release();
    }

    public boolean waitFor(int event) {
      return waitFor(event, 1);
    }

    public boolean waitFor(int event, int permits) {
      try {
        return events.get(event).tryAcquire(permits, 10, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
      }
    }
  }
}


text:
extern "C" {
#endif

#include <epopeia/keyboard.h>
#include "graphics_wgl.h"

typedef struct TKeyboardTds_t
{
    int  (*Init)       (struct TKeyboardTds_t* self);
    void (*End)        (struct TKeyboardTds_t* self);
    int  (*ExitPressed)(struct TKeyboardTds_t* self);
    int  (*KeyPressed) (struct TKeyboardTds_t* self); // <0 no, >0 keycode
    int  (*Pressed)    (struct TKeyboardTds_t* self, int KeyCode);
    void (*Delete)     (struct TKeyboardTds_t* self);
    // variables propias
    TGraphicsWgl* Tds;

} TKeyboardTds;

TKeyboard* TdsKeyboard_New(TGraphicsWgl* Tds);

#ifdef __cplusplus
};
#endif

#endif


text:
export declare const path: {
    join(pth: string, name: string): never;
};


text:
package org.kie.pmml.evaluator.assembler.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.drools.compiler.builder.impl.KnowledgeBuilderImpl;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceWithConfiguration;
import org.kie.pmml.api.exceptions.ExternalException;
import org.kie.pmml.api.exceptions.KiePMMLException;
import org.kie.pmml.commons.HasRule;
import org.kie.pmml.commons.model.HasNestedModels;
import org.kie.pmml.commons.model.HasSourcesMap;
import org.kie.pmml.commons.model.KiePMMLModel;
import org.kie.pmml.compiler.executor.PMMLCompiler;
import org.kie.pmml.compiler.executor.PMMLCompilerImpl;
import org.kie.pmml.evaluator.assembler.factories.PMMLRuleMapperFactory;
import org.kie.pmml.evaluator.assembler.factories.PMMLRuleMappersFactory;
import org.kie.pmml.evaluator.assembler.implementations.HasKnowledgeBuilderImpl;

import static org.kie.pmml.evaluator.assembler.factories.PMMLRuleMapperFactory.KIE_PMML_RULE_MAPPER_CLASS_NAME;
import static org.kie.pmml.evaluator.assembler.factories.PMMLRuleMappersFactory.KIE_PMML_RULE_MAPPERS_CLASS_NAME;
import static org.kie.pmml.evaluator.assembler.service.PMMLAssemblerService.PMML_COMPILER_CACHE_KEY;
import static org.kie.pmml.evaluator.assembler.service.PMMLAssemblerService.getFactoryClassNamePackageName;

/**
 * Class meant to compile resources
 */
public class PMMLCompilerService {

    static final String RULES_FILE_NAME = "Rules";

    private PMMLCompilerService() {
        // Avoid instantiation
    }

    /**
     * @param kbuilderImpl
     * @param resourceWithConfigurations
     * @return
     * @throws KiePMMLException if any KiePMMLInternalException has been thrown during execution
     * @throws ExternalException if any other kind of Exception has been thrown during execution
     */
    public static List<KiePMMLModel> getKiePMMLModelsFromResourcesWithConfigurationsWithSources(KnowledgeBuilderImpl kbuilderImpl, Collection<ResourceWithConfiguration> resourceWithConfigurations) {
        return resourceWithConfigurations.stream()
                .map(ResourceWithConfiguration::getResource)
                .flatMap(resource -> getKiePMMLModelsFromResourceWithSources(kbuilderImpl, resource).stream())
                .collect(Collectors.toList());
    }

    /**
     * @param kbuilderImpl
     * @param resourceWithConfigurations
     * @return
     * @throws KiePMMLException if any KiePMMLInternalException has been thrown during execution
     * @throws ExternalException if any other kind of Exception has been thrown during execution
     */
    public static List<KiePMMLModel> getKiePMMLModelsCompiledFromResourcesWithConfigurations(KnowledgeBuilderImpl kbuilderImpl, Collection<ResourceWithConfiguration> resourceWithConfigurations) {
        return resourceWithConfigurations.stream()
                .map(ResourceWithConfiguration::getResource)
                .flatMap(resource -> getKiePMMLModelsCompiledFromResource(kbuilderImpl, resource).stream())
                .collect(Collectors.toList());
    }

    /**
     * @param kbuilderImpl
     * @param resource
     * @return
     * @throws KiePMMLException if any KiePMMLInternalException has been thrown during execution
     * @throws ExternalException if any other kind of Exception has been thrown during execution
     */
    public static List<KiePMMLModel> getKiePMMLModelsCompiledFromResource(KnowledgeBuilderImpl kbuilderImpl,
                                                                          Resource resource) {
        PMMLCompiler pmmlCompiler = kbuilderImpl.getCachedOrCreate(PMML_COMPILER_CACHE_KEY,
                                                                   PMMLCompilerService::getCompiler);
        try {
            String packageName = getFactoryClassNamePackageName(resource)[1];
            return pmmlCompiler.getKiePMMLModels(packageName, resource.getInputStream(),
                                                 getFileName(resource.getSourcePath()),
                                                 new HasKnowledgeBuilderImpl(kbuilderImpl));
        } catch (IOException e) {
            throw new ExternalException("ExternalException", e);
        }
    }

    /**
     * @param kbuilderImpl
     * @param resource
     * @return
     */
    public static List<KiePMMLModel> getKiePMMLModelsFromResourceWithSources(KnowledgeBuilderImpl kbuilderImpl,
                                                                             Resource resource) {
        PMMLCompiler pmmlCompiler = kbuilderImpl.getCachedOrCreate(PMML_COMPILER_CACHE_KEY,
                                                                   PMMLCompilerService::getCompiler);
        String[] classNamePackageName = getFactoryClassNamePackageName(resource);
        String factoryClassName = classNamePackageName[0];
        String packageName = classNamePackageName[1];
        try {
            final List<KiePMMLModel> toReturn = pmmlCompiler.getKiePMMLModelsWithSources(factoryClassName, packageName,
                                                                                resource.getInputStream(),
                                                                                getFileName(resource.getSourcePath()),
                                                                                new HasKnowledgeBuilderImpl(kbuilderImpl));
            populateWithPMMLRuleMappers(toReturn, resource);
            return toReturn;
        } catch (IOException e) {
            throw new ExternalException("ExternalException", e);
        }
    }

    static void populateWithPMMLRuleMappers(final  List<KiePMMLModel> toReturn, final Resource resource) {
        for (KiePMMLModel kiePMMLModel : toReturn) {
            final List<String> generatedRuleMappers = new ArrayList<>();
            addPMMLRuleMapper(kiePMMLModel, generatedRuleMappers, resource.getSourcePath());
            addPMMLRuleMappers(kiePMMLModel, generatedRuleMappers, resource.getSourcePath());
        }
    }

    static void addPMMLRuleMapper(final KiePMMLModel kiePMMLModel, final List<String> generatedRuleMappers,
                                  final String sourcePath) {
        if (!(kiePMMLModel instanceof HasSourcesMap)) {
            String errorMessage = String.format("Expecting HasSourcesMap instance, retrieved %s inside %s",
                                                kiePMMLModel.getClass().getName(),
                                                sourcePath);
            throw new KiePMMLException(errorMessage);
        }
        if (kiePMMLModel instanceof HasRule) {
            String pkgUUID = ((HasRule)kiePMMLModel).getPkgUUID();
            String rulesFileName = kiePMMLModel.getKModulePackageName() + "." + RULES_FILE_NAME + pkgUUID;
            String pmmlRuleMapper = kiePMMLModel.getKModulePackageName() + "." + KIE_PMML_RULE_MAPPER_CLASS_NAME;
            String ruleMapperSource = PMMLRuleMapperFactory.getPMMLRuleMapperSource(rulesFileName);
            ((HasRule) kiePMMLModel).addSourceMap(pmmlRuleMapper, ruleMapperSource);
            generatedRuleMappers.add(pmmlRuleMapper);
        }
        if (kiePMMLModel instanceof HasNestedModels) {
            for (KiePMMLModel nestedModel : ((HasNestedModels) kiePMMLModel).getNestedModels()) {
                addPMMLRuleMapper(nestedModel, generatedRuleMappers, sourcePath);
            }
        }
    }

    static void addPMMLRuleMappers(final KiePMMLModel kiePMMLModel, final List<String> generatedRuleMappers,
                                   final String sourcePath) {
        if (!(kiePMMLModel instanceof HasSourcesMap)) {
            String errorMessage = String.format("Expecting HasSourcesMap instance, retrieved %s inside %s",
                                                kiePMMLModel.getClass().getName(),
                                                sourcePath);
            throw new KiePMMLException(errorMessage);
        }
        if (generatedRuleMappers.isEmpty()) {
            return;
        }
        String predictionRuleMapper = kiePMMLModel.getKModulePackageName() + "." + KIE_PMML_RULE_MAPPERS_CLASS_NAME;
        String ruleMapperSource =
                PMMLRuleMappersFactory.getPMMLRuleMappersSource(kiePMMLModel.getKModulePackageName(),
                                                                generatedRuleMappers);
        ((HasSourcesMap) kiePMMLModel).addSourceMap(predictionRuleMapper, ruleMapperSource);
    }

    static PMMLCompiler getCompiler() {
        // to retrieve model implementations
        return new PMMLCompilerImpl();
    }

    static String getFileName(final String fullPath) {
        String toReturn = fullPath;
        if (fullPath.contains(File.separator)) {
            toReturn = fullPath.substring(fullPath.lastIndexOf(File.separator) + 1);
        } else if (fullPath.contains("/")) {
            toReturn = fullPath.substring(fullPath.lastIndexOf('/') + 1);
        }
        return toReturn;
    }
}


text:
package org.apache.commons.httpclient.contrib.proxy;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Properties;

import org.apache.commons.httpclient.ProxyHost;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A utility class that gives applets the ability to detect proxy host settings.
 * This was adapted from a post from Chris Forster on 20030227 to a Sun Java
 * forum here:
 * http://forum.java.sun.com/thread.jspa?threadID=364342&tstart=120
 *
 * The algorithm - which relies on Sun java plugin internal classes in some
 * cases - was maintained, but the following changes were made:
 *
 * 1. Logging was used to allow control of debug type messages.
 * 2. Reflection is used instead of direct references to Sun internal classes
 *    to avoid the need to have these classes in the CLASSPATH to compile.
 * 3. Removed the use of global variables to allow this class to be used in
 *    a multi-threaded environment.
 * 4. Add the use of exception to indicate to the caller when proxy detection
 *    failed as opposed to when no proxy is configured.
 *
 * <p>
 * DISCLAIMER: HttpClient developers DO NOT actively support this component.
 * The component is provided as a reference material, which may be inappropriate
 * for use without additional customization.
 * </p>
 */
public class PluginProxyUtil {

    /** Log object for this class */
    private static final Log LOG = LogFactory.getLog(PluginProxyUtil.class);

    /**
     * This is used internally to indicate that no proxy detection succeeded
     * and no proxy setting is to be used - failover is unnecessary
     */
    private static final ProxyHost NO_PROXY_HOST = new ProxyHost("",80);

    /**
     * The system property that is used to convey proxy information in some VM's
     */
    private static final String PLUGIN_PROXY_CONFIG_PROP =
                                                "javaplugin.proxy.config.list";

    /**
     * Returns the Proxy Host information using settings from the java plugin.
     *
     * @param sampleURL the url target for which proxy host information is
     *                  required
     * @return the proxy host info (name and port) or null if a direct
     *         connection is allowed to the target url.
     * @throws ProxyDetectionException if detection failed
     */
    public static ProxyHost detectProxy(URL sampleURL)
        throws ProxyDetectionException
    {

        ProxyHost result = null;
        String javaVers = System.getProperty("java.runtime.version");

        if (LOG.isDebugEnabled()) {
            LOG.debug("About to attempt auto proxy detection under Java " +
                      "version:"+javaVers);
        }

        // If specific, known detection methods fail may try fallback
        // detection method
        boolean invokeFailover = false;

        if (javaVers.startsWith("1.3"))  {
            result = detectProxySettingsJDK13(sampleURL);
            if (result == null) {
                invokeFailover = true;
            }
        } else if (javaVers.startsWith("1.4"))  {
            result = detectProxySettingsJDK14(sampleURL);
            if (result == null) {
                invokeFailover = true;
            }
        } else if (javaVers.startsWith("1.5"))  {
            invokeFailover = true;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Sun Plugin reported java version not 1.3.X, " +
                          "1.4.X or 1.5.X - trying failover detection...");
            }
            invokeFailover = true;
        }
        if (invokeFailover) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Using failover proxy detection...");
            }
            result = getPluginProxyConfigSettings();
        }
        if (NO_PROXY_HOST.equals(result)) {
            result = null;
        }
        return result;
    }

    /**
     * Use Sun-specific internal plugin proxy classes for 1.3.X
     * Look around for the 1.3.X plugin proxy detection class. Without it,
     * cannot autodetect...
     *
     * @param sampleURL the URL to check proxy settings for
     * @return ProxyHost the host and port of the proxy that should be used
     * @throws ProxyDetectionException if detection failed
     */
    private static ProxyHost detectProxySettingsJDK13(URL sampleURL)
        throws ProxyDetectionException
    {
        ProxyHost result = null;
        try {
            // Attempt to discover proxy info by asking internal plugin
            // code to locate proxy path to server sampleURL...
            Class pluginProxyHandler =
                Class.forName("sun.plugin.protocol.PluginProxyHandler");
            Method getDefaultProxyHandlerMethod =
                pluginProxyHandler.getDeclaredMethod("getDefaultProxyHandler",
                                                     null);
            Object proxyHandlerObj =
                getDefaultProxyHandlerMethod.invoke(null, null);
            if (proxyHandlerObj != null) {
                Class proxyHandlerClass = proxyHandlerObj.getClass();
                Method getProxyInfoMethod =
                    proxyHandlerClass.getDeclaredMethod("getProxyInfo",
                                                        new Class[]{URL.class});
                Object proxyInfoObject =
                    getProxyInfoMethod.invoke(proxyHandlerObj,
                                              new Object[] { sampleURL });
                if (proxyInfoObject != null) {
                    Class proxyInfoClass = proxyInfoObject.getClass();
                    Method getProxyMethod =
                        proxyInfoClass.getDeclaredMethod("getProxy", null);
                    boolean useProxy =
                        (getProxyMethod.invoke(proxyInfoObject, null) != null);
                    if (useProxy) {
                        String proxyIP =
                            (String)getProxyMethod.invoke(proxyInfoObject, null);
                        Method getProxyPortMethod =
                            proxyInfoClass.getDeclaredMethod("getPort", null);
                        Integer portInteger =
                            (Integer)getProxyPortMethod.invoke(proxyInfoObject, null);
                        int proxyPort = portInteger.intValue();
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("1.3.X: proxy=" + proxyIP+
                                      " port=" + proxyPort);
                        }
                        result = new ProxyHost(proxyIP, proxyPort);
                    } else {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("1.3.X reported NULL for " +
                                      "proxyInfo.getProxy (no proxy assumed)");
                        }
                        result = NO_PROXY_HOST;
                    }
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("NULL proxyInfo in 1.3.X auto proxy " +
                                       "detection, (no proxy assumed)");
                    }
                    result = NO_PROXY_HOST;
                }
            } else {
                throw new ProxyDetectionException(
                  "Sun Plugin 1.3.X failed to provide a default proxy handler");
            }
        } catch (Exception e) {
            LOG.warn("Sun Plugin 1.3.X proxy detection class not " +
                     "found, will try failover detection, e:"+e);
        }
        return result;
    }

    /**
     * Returns the proxy information for the specified sampleURL using JRE 1.4
     * specific plugin classes.
     *
     * Notes:
     *     Plugin 1.4 Final added
     *     com.sun.java.browser.net.* classes ProxyInfo & ProxyService...
     *     Use those with JREs => 1.4
     *
     * @param sampleURL the URL to check proxy settings for
     * @return ProxyHost the host and port of the proxy that should be used
     */
    private static ProxyHost detectProxySettingsJDK14(URL sampleURL) {
        ProxyHost result = null;
        try {
            // Look around for the 1.4.X plugin proxy detection class...
            // Without it, cannot autodetect...
            Class ProxyServiceClass =
                Class.forName("com.sun.java.browser.net.ProxyService");
            Method getProxyInfoMethod =
                ProxyServiceClass.getDeclaredMethod("getProxyInfo",
                                                    new Class[] {URL.class});
            Object proxyInfoArrayObj =
                getProxyInfoMethod.invoke(null, new Object[] {sampleURL});
            if (proxyInfoArrayObj == null
                    || Array.getLength(proxyInfoArrayObj) == 0) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("1.4.X reported NULL proxy (no proxy assumed)");
                }
                result = NO_PROXY_HOST;
            } else {
                Object proxyInfoObject = Array.get(proxyInfoArrayObj, 0);
                Class proxyInfoClass = proxyInfoObject.getClass();
                Method getHostMethod =
                    proxyInfoClass.getDeclaredMethod("getHost",null);
                String proxyIP =
                    (String)getHostMethod.invoke(proxyInfoObject, null);
                Method getPortMethod =
                    proxyInfoClass.getDeclaredMethod("getPort",null);
                Integer portInteger =
                    (Integer)getPortMethod.invoke(proxyInfoObject, null);
                int proxyPort = portInteger.intValue();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("1.4.X Proxy info geProxy:"+proxyIP+
                              " get Port:"+proxyPort);
                }
                result = new ProxyHost(proxyIP, proxyPort);
            }
        } catch (Exception e) {
            LOG.warn("Sun Plugin 1.4.X proxy detection class not found, " +
                     "will try failover detection, e:"+e);
        }
        return result;
    }

    /**
     * Returns the proxy host information found by inspecting the system
     * property "javaplugin.proxy.config.list".
     *
     * @return ProxyHost the host and port of the proxy that should be used
     * @throws ProxyDetectionException if an exception is encountered while
     *                                 parsing the value of
     *                                 PLUGIN_PROXY_CONFIG_PROP
     */
    private static ProxyHost getPluginProxyConfigSettings()
        throws ProxyDetectionException
    {
        ProxyHost result = null;
        try {
            Properties properties = System.getProperties();
            String proxyList =
                properties.getProperty("javaplugin.proxy.config.list");
            if (LOG.isDebugEnabled()) {
                LOG.debug("Plugin Proxy Config List Property:"+proxyList);
            }
            boolean useProxy = (proxyList != null);
            if (useProxy) {
                proxyList = proxyList.toUpperCase();
                //  Using HTTP proxy as proxy for HTTP proxy tunnelled SSL
                //  socket (should be listed FIRST)....
                //  1/14/03 1.3.1_06 appears to omit HTTP portion of
                //  reported proxy list... Mod to accomodate this...
                //  Expecting proxyList of "HTTP=XXX.XXX.XXX.XXX:Port" OR
                //  "XXX.XXX.XXX.XXX:Port" & assuming HTTP...
                String proxyIP="";
                if (proxyList.indexOf("HTTP=") > -1) {
                    proxyIP =
                        proxyList.substring(proxyList.indexOf("HTTP=")+5,
                                            proxyList.indexOf(":"));
                } else {
                    proxyIP = proxyList.substring(0, proxyList.indexOf(":"));
                }
                int endOfPort = proxyList.indexOf(",");
                if (endOfPort < 1) endOfPort = proxyList.length();
                String portString =
                    proxyList.substring(proxyList.indexOf(":")+1,endOfPort);
                int proxyPort = Integer.parseInt(portString);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("proxy " + proxyIP+" port " + proxyPort);
                }
                result = new ProxyHost(proxyIP, proxyPort);
            } else {
                LOG.debug("No configured plugin proxy list");
                result = NO_PROXY_HOST;
            }
        } catch (Exception e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Exception during failover auto proxy detection, " +
                          ", e:"+e);
                throw new ProxyDetectionException(
                        "Encountered unexpected exception while attempting " +
                        "to parse proxy information stored in "+
                        PLUGIN_PROXY_CONFIG_PROP, e);
            }
        }
        return result;
    }
}


text:
package goka

import (
	"testing"
)

func TestGokaHandler(t *testing.T) {
}


text:
@implementation MCAnimationProxy

#pragma mark - Methods

+ (NSString *)propertyNameForSelector:(SEL)selector {
	[NSException raise:NSInternalInconsistencyException format:@"Use a concrete subclass of MCAnimationProxy."];
	return nil;
}

- (POPPropertyAnimation *)propertyAnimation {
	[NSException raise:NSInternalInconsistencyException format:@"Use a concrete subclass of MCAnimationProxy."];
	return nil;
}

#pragma mark - Methods

- (void)completeInvocationWithPropertyName:(NSString *)propertyName andValue:(id)value {
	if ([propertyName hasPrefix:@"pop_"]) {
		propertyName = [propertyName substringFromIndex:4];
	}

    // setup property
	POPAnimatableProperty *property = [self __animatablePropertyForPropertyName:propertyName];
    if (!property) {
		[NSException raise:NSInternalInconsistencyException format:@"Property '%@' is not animatable.", propertyName];
	}

	// setup animation
	POPPropertyAnimation *animation = [self.object pop_animationForKey:propertyName];

	if (!animation) {
		animation = [self propertyAnimation];
		animation.property = property;
	}

	if (value) {
		animation.toValue = value;
	}

	MCAnimationGroup *group = [NSObject mc_activeAnimationGroup];
	if (group) {
		[group addAnimation:animation];
	}

	[self.object pop_addAnimation:animation forKey:propertyName];
}

#pragma mark - Private

+ (NSMutableDictionary *)__animatablePropertiesByClassName {
	static NSMutableDictionary *__propertiesByClassName = nil;
	if (!__propertiesByClassName) {
		NSDictionary *mapping = @{
			@"CALayer": @{
				@"backgroundColor": kPOPLayerBackgroundColor,
				@"bounds": kPOPLayerBounds,
				@"opacity": kPOPLayerOpacity,
				@"position": kPOPLayerPosition,
				@"zPosition": kPOPLayerZPosition,

				@"positionX": kPOPLayerPositionX,
				@"positionY": kPOPLayerPositionY,
				@"rotation": kPOPLayerRotation,
				@"rotationX": kPOPLayerRotationX,
				@"rotationY": kPOPLayerRotationY,
				@"scaleX": kPOPLayerScaleX,
				@"scaleY": kPOPLayerScaleY,
				@"scaleXY": kPOPLayerScaleXY,
				@"translationX": kPOPLayerTranslationX,
				@"translationXY": kPOPLayerTranslationXY,
				@"translationY": kPOPLayerTranslationY,
				@"translationZ": kPOPLayerTranslationZ,
				@"size": kPOPLayerSize,
			},

			@"CAShapeLayer": @{
				@"strokeColor": kPOPShapeLayerStrokeColor,
				@"strokeStart": kPOPShapeLayerStrokeStart,
				@"strokeEnd": kPOPShapeLayerStrokeEnd
			},

			@"NSLayoutConstraint": @{
				@"constant": kPOPLayoutConstraintConstant
			},

			@"UIView": @{
				@"alpha": kPOPViewAlpha,
				@"backgroundColor": kPOPViewBackgroundColor,
				@"bounds": kPOPViewBounds,
				@"center": kPOPViewCenter,
				@"frame": kPOPViewFrame,
				@"scaleX": kPOPViewScaleX,
				@"scaleY": kPOPViewScaleY,
				@"scaleXY": kPOPViewScaleXY,
			},

			@"UIScrollView": @{
				@"contentOffset": kPOPScrollViewContentOffset,
				@"contentSize": kPOPScrollViewContentSize
			},

			@"UINavigationBar": @{
				@"barTintColor": kPOPNavigationBarBarTintColor
			},

			@"UIToolbar": @{
				@"barTintColor": kPOPNavigationBarBarTintColor
			},

			@"UITabBar": @{
				@"barTintColor": kPOPTabBarBarTintColor
			},
		};

		__propertiesByClassName = [NSMutableDictionary dictionary];
		for (NSString *className in mapping) {
			__propertiesByClassName[className] = [mapping[className] mutableCopy];
		}
	}

	return __propertiesByClassName;
}

- (POPAnimatableProperty *)__animatablePropertyForPropertyName:(NSString *)propertyName {
    NSDictionary *animatableProperties = [[self class] __animatablePropertiesByClassName];

    Class class = [self.object class];

    while (class != [NSObject class]) {
        NSString *className = NSStringFromClass(class);
        NSDictionary *classProperties = [animatableProperties objectForKey:className];
        if (classProperties) {
            id property = [classProperties objectForKey:propertyName];
            if ([property isKindOfClass:[NSString class]]) {
                return [POPAnimatableProperty propertyWithName:property];
            }
            else if ([property isKindOfClass:[POPAnimatableProperty class]]) {
                return property;
            }
        }

        class = [class superclass];
    }

	return nil;
}

@end

@implementation NSObject (MCAnimationProxy)

+ (void)pop_addAnimatablePropertyWithName:(NSString *)propertyName readBlock:(void (^)(id, CGFloat *))readBlock writeBlock:(void (^)(id, const CGFloat *))writeBlock threshold:(CGFloat)threshold {
    [self pop_registerAnimatablePropertyWithName:propertyName readBlock:readBlock writeBlock:writeBlock threshold:threshold];
}

+ (void)pop_registerAnimatablePropertyWithName:(NSString *)propertyName readBlock:(void (^)(id, CGFloat *))readBlock writeBlock:(void (^)(id, const CGFloat *))writeBlock threshold:(CGFloat)threshold {
    NSString *className = NSStringFromClass(self);
	NSString *domainName = [NSString stringWithFormat:@"%@.%@", className, propertyName];
	POPAnimatableProperty *property = [POPAnimatableProperty propertyWithName:domainName initializer: ^(POPMutableAnimatableProperty *prop) {
	    prop.readBlock = readBlock;
	    prop.writeBlock = writeBlock;
	    prop.threshold = threshold;
	}];

    NSMutableDictionary *animatableProperties = [MCAnimationProxy __animatablePropertiesByClassName];

    NSMutableDictionary *classProperties = [animatableProperties objectForKey:className];
    if (!classProperties) {
        classProperties = [NSMutableDictionary dictionary];
        animatableProperties[className] = classProperties;
    }

    classProperties[propertyName] = property;
}

@end


text:
package com.boot.subsidios.repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.time.LocalDate;
import java.util.Map;

import com.boot.subsidios.model.Imputacion;

public class ImputacionStub {
	private static Map<Long, Imputacion> imputaciones = new HashMap<Long, Imputacion>();
	private static Long idIndex = 3L;
	private static LocalDate today = LocalDate.now();

	//Popular imputaciones iniciales
	static {
		//long id, LocalDate fecha, float monto, String descripcion
		Imputacion a = new Imputacion(1,today.minusDays(5),200, "Descripcion 1");
		imputaciones.put(1L, a);
		Imputacion b = new Imputacion(2, today.plusDays(5), 150, "Descripcion 2");
		imputaciones.put(2L, b);
		Imputacion c = new Imputacion(3, today.plusDays(10), 300, "Descripcion 3");
		imputaciones.put(3L, c);

	}

	public static List<Imputacion> list() {
		return new ArrayList<Imputacion>(imputaciones.values());
	}

	public static Imputacion create(Imputacion imputacion) {
		idIndex += idIndex;
		imputacion.setId(idIndex);
		imputaciones.put(idIndex, imputacion);
		return imputacion;
	}

	public static Imputacion get(Long id) {
		return imputaciones.get(id);
	}

	public static Imputacion update(Long id, Imputacion imputacion) {
		imputaciones.put(id, imputacion);
		return imputacion;
	}

	public static Imputacion delete(Long id) {
		return imputaciones.remove(id);
	}

}