text:
import nn
import math
import numpy
import priority
import agent
import entities
import decisions
import random
import itertools
import vote

class LearningMechanism(object):
    def __init__(self, agents, cfg):
        self.agents = agents

    def learn(self, fitnesses):
        raise NotImplementedException()

class EvolutionarySelectionPhenotype(object):
    def __init__(self, phenotype, fitness):
        self.phenotype = phenotype
        self.fitness = fitness

class Evolution(LearningMechanism):
    def __init__(self, agents, cfg):
        LearningMechanism.__init__(self, agents, cfg)
        config = EvolutionConfig.from_dict(cfg)
        self._phenotype = config.phenotype
        self._genotype = config.genotype
        self._elitism = config.elitism
        self.selection_mechanism = config.selection_mechanism
        self._crossover_rate = config.crossover_rate
        self._mutation_rate = config.mutation_rate
        self._genome_mutation_rate = config.genome_mutation_rate

    def learn(self, fitnesses):

        # sorted
        fitnesses = [(a.decision_mechanism, fitnesses[a], a) for a in sorted(
                fitnesses.iterkeys(), key=lambda k: fitnesses[k]
        ) if a in self.agents]
            # returns an ordered list of (phenotype, fitness, agent) tuples

        # keep elites
        elites, rest = fitnesses[:self._elitism], fitnesses[self._elitism:]
            # elites are left untouched
        selected = self.selection_mechanism(
            [EvolutionarySelectionPhenotype(p, f) for p, f, __ in rest],
            len(rest)
        ) # select n best non-elites

        # Mutate
        genotypes = [p.phenotype.genotype for p in selected]

        ## crossover
        for (a, b) in itertools.combinations(range(len(genotypes)), 2):
            genotypes[a], genotypes[b] = self._genotype.crossover(
                genotypes[a], genotypes[b], self._crossover_rate
            )

        ## mutation
        for g in genotypes:
            g.mutate(self._mutation_rate, self._genome_mutation_rate)

        # Create new phenotypes
        new_phenotypes = [self._phenotype.from_genotype(g) for g in genotypes]

        # Distribute new phenotypes to non-elite agents
        for (__, ___, a), p in zip(rest, new_phenotypes):
            a.add_voting_mechanism(p)

    @staticmethod
    def rank_selection(sorted_phenotypes, num):
        """Linear rank selection.
        Based on roulette wheel. Rank all elements by
        fitness value. Assign 1 ``lottery ticket'' to the lowest ranking member,
        2 to the second and so on up to N tickets for the best member. Randomly
        select based on the weighed probabilities described by the lottery
        tickets.

        Arguments:
            sorted_phenotypes:  TODO
            num:                TODO

        Returns:
            TODO
        """

        wheel = {}
        sum = 0
        total = 0
        for n in xrange(len(sorted_phenotypes)):
            wheel[sorted_phenotypes[-n]] = n + sum
            sum += n
            total += n + sum
        selected = [None] * num
        for i in xrange(num):
            r = random.random() * total
            for p in wheel:
                if r > wheel[p]:
                    selected[i] = p
        return selected

class EvolutionConfig(object):
    SELECTION_MECHANISMS = {
        "rank": Evolution.rank_selection,
        "rank selection": Evolution.rank_selection,
        "default": Evolution.rank_selection
    }

    @classmethod
    def from_dict(c, dict):
        obj = c()
        obj.phenotype = dict["phenotype class"]
        obj.genotype = dict["genotype class"]
        obj.elitism = int(dict["elitism"])
        obj.selection_mechanism = EvolutionConfig.SELECTION_MECHANISMS.get(
            dict["selection mechanism"],
            EvolutionConfig.SELECTION_MECHANISMS["default"]
        )
        obj.crossover_rate = float(dict["crossover rate"])
        obj.mutation_rate = float(dict["mutation rate"])
        obj.genome_mutation_rate = float(dict["genome mutation rate"])
        return obj

class Phenotype(object):
    def __init__(self, genotype):
        self.genotype = genotype

    @classmethod
    def from_genotype(c, genotype):
        return c(genotype)

class Genotype(object):
    length = 0

    def __init__(self, genome):
        self.genome = genome

    @classmethod
    def random(c):
        return c(
            ["0" if random.random() > 0.5 else "1" for __ in xrange(c.length)]
        )

    def mutate(self, mutation_rate, genome_mutation_rate):
        if random.random() < mutation_rate:
            point = int(random.random() * len(self.genome))
            self.genome[point] = "0" if self.genome[point] == "1" else "1"

    def __len__(self):
        return self.length

    @classmethod
    def crossover(c, first, second, crossover_rate):
        assert len(first) == len(second), "Lengths are not the same."
        point = int(random.random() * len(first))
        return (
            c(first.genome[:point] + second.genome[point:]),
            c(second.genome[:point] + first.genome[point:])
        ) if random.random() < crossover_rate else (first, second)

# Concrete decision making

class FishermanVotingRules(decisions.VotingDecisionMechanism, Phenotype):
    data_name = "fisherman"

    DIST_PROB = "Distance Probability"
    COMPLAIN_10 = "Always complain 10"
    APPROVE_ALL = "Never complain"

    def __init__(self, genotype):
        Phenotype.__init__(self, genotype)
        self.rule = genotype.to_rule()

        # Rules:
        # - distance proportional probabilistic decision
        # - always complain 10 random
        # - never complain

    def _dist_prob(self, agent, coastal_plan, world_map, num_max_complaints):
        vote_strength = {}
        for cell in coastal_plan.aquaculture_sites():
            norm_distance = world_map.get_cell_distance(agent.home, cell) / \
                world_map.get_max_distance()
            value = random.random() * norm_distance
            complain = value > 0.5
            if complain:
                vote_strength[vote.Vote.complaint(cell)] = value

        return sorted(
            vote_strength.iterkeys(),
            key=lambda e: vote_strength[e],
            reverse=True
        )[:num_max_complaints]

    def _complain_10(self, agent, coastal_plan, world_map, num_max_complaints):
        return [vote.Vote.complaint(c) for c in
            random.sample(coastal_plan, num_max_complaints)]

    def _approve_all(self, agent, coastal_plan, world_map, num_max_complaints):
        return []

    rule_to_method = {
        DIST_PROB: _dist_prob,
        COMPLAIN_10: _complain_10,
        APPROVE_ALL: _approve_all
    }

    def decide_votes(self, agent, coastal_plan, world_map, num_max_complaints):
        return self.rule_to_method[self.rule](
            self, agent, coastal_plan, world_map, num_max_complaints
        )

    @classmethod
    def new(c, agent, config, world):
        agent.add_voting_mechanism(c(FishermanRulesGenotype.random()))

class FishermanRulesGenotype(Genotype):
    length = 3

    def to_rule(self):
        return {
            0: FishermanVotingRules.DIST_PROB,
            1: FishermanVotingRules.COMPLAIN_10,
            2: FishermanVotingRules.APPROVE_ALL,
            3: FishermanVotingRules.DIST_PROB
        }[int("".join(self.genome), 2) / 2]

class FishermanVotingNN(decisions.VotingDecisionMechanism, Phenotype):
    data_name = "fisherman"

    inputs = [
            "distance",
            "home conditions",
            "targeted conditions"]
    hiddens = ["A", "B", "C", "D", "E", "F"]
    outputs = ["vote"]

    def __init__(self, genotype):
        Phenotype.__init__(self, genotype)
        self.connections = [
            # All inputs to all hidden neurons
            (a, b) for a in self.inputs for b in self.hiddens
        ] + [
            # All hidden neurons to all output neurons
            (a, b) for a in self.hiddens for b in self.outputs
        ] + [
            # All hidden neurons to themselves
            (a, a) for a in self.hiddens
        ] + [
            # Bias node to hidden layer nodes
            ("bias", a) for a in self.hiddens
        ]
        self.edges = zip(self.connections, self.genotype.to_number_list())
        self.network = nn.LabeledNeuralNetwork(
            FishermanVotingNN.inputs,
            FishermanVotingNN.outputs,
            FishermanVotingNN.hiddens,
            self.edges
        )

    def decide_votes(self, agent, coastal_plan, world_map, num_max_complaints):
        vote_strength = {}
        for cell in coastal_plan.aquaculture_sites():
            home = agent.home
            distance = world_map.get_cell_distance(home, cell) / \
                world_map.get_max_distance()
            cond = agent.slot_knowledge[cell] if \
                cell in agent.slot_knowledge else 0.0
            values = {
                "distance":             distance,
                "home conditions":      agent.slot_knowledge[home],
                "targeted conditions":  cond
            }
            self.network.set_input_values(values)
            self.network.update()
            output = self.network.get_output_values()
            complain = output["vote"] > 0.5
            if complain:
                vote_strength[vote.Vote.complaint(cell)] = output["vote"]

        return sorted(
            vote_strength.iterkeys(),
            key=lambda e: vote_strength[e],
            reverse=True
        )[:num_max_complaints]

    @classmethod
    def new(c, agent, config, world):
        agent.add_voting_mechanism(
            c.from_genotype(FishermanNNGenotype.random())
        )

class FishermanNNGenotype(Genotype):
    phenotype_class = FishermanVotingNN
    precision = 8  # bits per 1
    weight_range = (-1, 1)
    length = (
        # Input to hidden layer
        len(phenotype_class.inputs)  * len(phenotype_class.hiddens) +
        # Hidden layer to outputs
        len(phenotype_class.hiddens) * len(phenotype_class.outputs) +
        # Recurrent hidden layer-connections
        len(phenotype_class.hiddens) +
        # Bias node to hidden layer nodes
        len(phenotype_class.hiddens)
    ) * (weight_range[1] - weight_range[0]) * precision

    def to_number_list(self):
        def sep(str, acc):
            if len(str) < self.precision: return acc
            return sep(str[self.precision:], acc + [str[:self.precision]])
        return [self.weight_range[0] + int(''.join(e), 2) / 2.0 ** self.precision * (self.weight_range[1] - self.weight_range[0]) for e in sep(self.genome, [])]


text:
package com.sien.aimanager.fragment;

import android.animation.ObjectAnimator;
import android.view.View;
import android.widget.Button;

import com.sien.aimanager.R;
import com.sien.aimanager.activity.LoginActivity;
import com.sien.aimanager.control.WeLoginHelper;
import com.sien.lib.baseapp.beans.APPOperateEventBundle;
import com.sien.lib.baseapp.events.BaseAppEvents;
import com.sien.lib.baseapp.utils.CPScreenUtil;
import com.sien.lib.baseapp.utils.RepeatClickUtil;
import com.sien.lib.baseapp.utils.ToastUtil;
import com.sien.lib.databmob.utils.CPDeviceUtil;
import com.sien.lib.databmob.utils.EventPostUtil;
//import com.umeng.analytics.MobclickAgent;

/**
 * @author sien
 * @date 2016/11/4
 * @descript 登录fragment第一步
 */
public class LoginFragment1 {
    public static final String TAG = "LoginFragment1";
    private View loginBtn;
    private Button wxloginBtn;

    private WeLoginHelper helper;

    private LoginActivity context;
    private View rootView;
    private View icon_phone;

    public LoginFragment1(LoginActivity context) {
        this.context = context;
        onCreateView();
        onViewCreated();
    }

    public void onCreateView() {
        rootView = context.findView(R.id.login1);
        icon_phone = context.findView(R.id.iv_login1_phone_icon);
    }

    public void onViewCreated() {
        initViews();
        initial();
    }

    public void show(boolean transition) {
        rootView.setVisibility(View.VISIBLE);
        if (!transition) {
            return;
        }
        long duration = 300l;
        ObjectAnimator.ofFloat(icon_phone, "translationX", (float) (CPScreenUtil.dip2px(context, 7 - 76)), 0).start();
        ObjectAnimator.ofFloat(loginBtn, "alpha", 0f, 1.0f).setDuration(duration).start();
        ObjectAnimator.ofFloat(wxloginBtn, "alpha", 0f, 1.0f).setDuration(duration).start();
    }

    public void hide() {
        rootView.setVisibility(View.GONE);
    }

    public boolean isShowing() {
        return context.findViewById(R.id.login1).getVisibility() == View.VISIBLE;
    }

    public void onDestroy() {
        helper = null;
        context = null;
    }

    public void initViews() {
        loginBtn = context.findView(R.id.login_btn);
        wxloginBtn = context.findView(R.id.login_wx);
        context.findView(R.id.btn_login_close).setOnClickListener(clickListener);
    }

    public void initial() {
        loginBtn.setOnClickListener(clickListener);
        wxloginBtn.setOnClickListener(clickListener);
    }

    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int vid = v.getId();
            if (vid == R.id.login_btn) {
//                if (!RepeatClickUtil.isRepeatClick()) {
//                }
                doFragmentChange(1);
            } else if (vid == R.id.login_wx) {
                //调用微信登录
                if (!RepeatClickUtil.isRepeatClick()) {
                    callWechatLogin();
                }
            } else if (vid == R.id.btn_login_close) {
                if (!RepeatClickUtil.isRepeatClick()) {

                    //统计"X"关闭按钮的点击
//                    MobclickAgent.onEvent(context,"062");

                    context.finish();
                }
            }
        }
    };

    /*调用微信登录*/
    private void callWechatLogin() {
        //检测是否安装微信应用
        if (!CPDeviceUtil.isWeixinAvilible(context)){
            ToastUtil.getInstance().showMessage(context,"抱歉,您未安装微信", ToastUtil.LENGTH_SHORT);
            return;
        }

        helper = new WeLoginHelper(context);
        helper.authLogin();
    }

    //fragment跳转
    private void doFragmentChange(int index) {
        APPOperateEventBundle bundle = new APPOperateEventBundle();
        bundle.putString(APPOperateEventBundle.EVENTACTION, "fragmentChange");
        bundle.putInt("fragmentIndex", index);
        EventPostUtil.post(new BaseAppEvents.APPOperateEvent(BaseAppEvents.STATUS_SUCCESS, bundle));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package us.coastalhacking.corvus.annotations.ui.e3;

import us.coastalhacking.corvus.annotations.ui.common.AnnotationController;
import us.coastalhacking.corvus.annotations.ui.common.MarkerDTO;

public class AddControlHandler extends AbstractAnnotationHandler {

	@Override
	protected void doExecute(MarkerDTO dto) {
		AnnotationController.addControl(dto);

	}

}


text:
import {SignalRef} from 'vega';
import {FieldName} from '../channeldef';
import {Config} from '../config';
import {Encoding} from '../encoding';
import {ParameterPredicate} from '../predicate';
import {ExprRef} from '../expr';
import {Projection} from '../projection';
import {TopLevelSelectionParameter} from '../selection';
import {GenericSpec, NormalizedSpec} from '../spec';
import {GenericLayerSpec, NormalizedLayerSpec} from '../spec/layer';
import {GenericUnitSpec, NormalizedUnitSpec} from '../spec/unit';
import {Dict} from '../util';
import {RepeaterValue} from './repeater';

export type Normalize<S extends GenericSpec<any, any, any, any>, NS extends NormalizedSpec> = (
  spec: S,
  params: NormalizerParams
) => NS;

export interface ExtraNormalizer<
  S extends GenericSpec<any, any, any, FieldName>, // Input type
  O extends NormalizedSpec, // Output Type
  SN extends GenericSpec<any, any, any, FieldName> = S // input to additional normalization
> {
  name: string;
  hasMatchingType: (spec: GenericSpec<any, any, any, any>, config: Config) => spec is S;

  run(spec: S, params: NormalizerParams, normalize: Normalize<SN, O>): O;
}

export type NonFacetUnitNormalizer<S extends GenericUnitSpec<any, any>> = ExtraNormalizer<
  S,
  NormalizedUnitSpec | NormalizedLayerSpec,
  GenericUnitSpec<any, any> | GenericLayerSpec<any>
>;

export type NormalizeLayerOrUnit = Normalize<
  GenericUnitSpec<any, any> | GenericLayerSpec<any>,
  NormalizedUnitSpec | NormalizedLayerSpec
>;

export interface NormalizerParams {
  config: Config<SignalRef>;
  parentEncoding?: Encoding<FieldName>;
  parentProjection?: Projection<ExprRef>;
  repeater?: RepeaterValue;
  repeaterPrefix?: string;
  selections?: TopLevelSelectionParameter[];
  emptySelections?: Dict<boolean>;
  selectionPredicates?: Dict<ParameterPredicate[]>;
  path?: string[];
}


text:
struct Sales_data {
    std::string bookName;
    std::string bookISBN;
    unsigned SaleNum = 0;
    double rev = 0.0;
    double rate = 0.0;
};

int main(int argc, char const *argv[])
{
    return 0;
}


text:
package cn.shiyanjun.platform.scheduled.api;

import cn.shiyanjun.platform.api.LifecycleAware;

public interface SchedulingManager extends LifecycleAware {

	ComponentManager getComponentManager();
	RecoveryManager getRecoveryManager();
}


text:
package won.protocol.model;

import java.net.URI;

import won.protocol.vocabulary.WON;

/**
 * User: fkleedorfer Date: 02.11.12
 */
public enum ConnectionEventType {
    // in general, be permissive about messages where possible. Don't care about
    // duplicate messages
    // close may always be called. It always closes the connnection.
    OWNER_CLOSE("OwnerClose", ConnectionState.SUGGESTED, ConnectionState.REQUEST_SENT, ConnectionState.REQUEST_RECEIVED,
                    ConnectionState.CONNECTED, ConnectionState.CLOSED),
    PARTNER_CLOSE("PartnerClose", ConnectionState.SUGGESTED, ConnectionState.REQUEST_SENT,
                    ConnectionState.REQUEST_RECEIVED, ConnectionState.CONNECTED, ConnectionState.CLOSED),
    OWNER_CONNECT("OwnerConnect", ConnectionState.SUGGESTED, ConnectionState.REQUEST_RECEIVED, ConnectionState.CLOSED),
    PARTNER_CONNECT("PartnerConnect", ConnectionState.SUGGESTED, ConnectionState.REQUEST_SENT, ConnectionState.CLOSED),
    OWNER_MESSAGE("OwnerMessage", ConnectionState.CONNECTED),
    PARTNER_MESSAGE("PartnerMessage", ConnectionState.CONNECTED), MATCHER_HINT("Hint");
    private String name;
    private ConnectionState[] permittingStates;

    ConnectionEventType(String name, ConnectionState... permittingStates) {
        this.permittingStates = permittingStates;
        this.name = name;
    }

    public boolean isMessageAllowed(ConnectionState stateToCheck) {
        for (ConnectionState st : this.permittingStates) {
            if (st.equals(stateToCheck))
                return true;
        }
        return false;
    }

    public URI getURI() {
        return URI.create(WON.BASE_URI + name);
    }
}


text:
"use strict";

const utils = require("../utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
    meta: {
        type: "suggestion",
        docs: {
            description: "disallow setup/teardown module hooks",
            category: "Possible Errors",
            url: "https://github.com/platinumazure/eslint-plugin-qunit/blob/master/docs/rules/no-setup-teardown.md"
        },
        fixable: "code",
        messages: {
            noSetupTeardown: "Use {{preferred}} instead of {{forbidden}}."
        },
        schema: []
    },

    create: function (context) {
        const replacements = {
            setup: "beforeEach",
            teardown: "afterEach"
        };

        function checkModuleHook(propertyNode) {
            if (replacements.hasOwnProperty(propertyNode.key.name)) {
                context.report({
                    node: propertyNode,
                    messageId: "noSetupTeardown",
                    data: {
                        forbidden: propertyNode.key.name,
                        preferred: replacements[propertyNode.key.name]
                    },
                    fix(fixer) {
                        return fixer.replaceText(propertyNode.key, replacements[propertyNode.key.name]);
                    }
                });
            }
        }

        function isInModule(propertyNode) {
            return propertyNode &&
                propertyNode.parent &&          // ObjectExpression
                propertyNode.parent.parent &&   // CallExpression?
                propertyNode.parent.parent.type === "CallExpression" &&
                utils.isModule(propertyNode.parent.parent.callee);
        }

        return {
            "Property": function (node) {
                if (utils.isModuleHookPropertyKey(node.key) && isInModule(node)) {
                    checkModuleHook(node);
                }
            }
        };
    }
};


text:
package com.rust.method;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by br7roy
 * on 2017-04-15
 */
public class IntMethod {
    private static Map<Class, Object> goodMap = new HashMap<Class, Object>();

    private ResultSet resultSet;
    private int anInt;

    private IntMethod(ResultSet resultSet, int anInt) {

        this.resultSet = resultSet;
        this.anInt = anInt;
    }

    {
        init(this.resultSet, this.anInt);

    }

    private static void init(ResultSet resultSet, int i) {
        try {
            goodMap.put(Integer.class, resultSet.getInt(i));
            goodMap.put(Double.class, resultSet.getDouble(i));
            goodMap.put(Date.class, resultSet.getDate(i));
            goodMap.put(String.class, resultSet.getString(i));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static Object map2Result(Class cls) {
        return goodMap.get(cls);
    }

    private Object crtObj(ResultSet resultSet, Class cls) {
        try {
            Class aClass = Class.forName("com.rust.gameService.Impl.GamePlayer");
            System.out.println(aClass);

            Object object = aClass.newInstance();

            Method[] methods = aClass.getDeclaredMethods();

            Map<String, Method> methodMap = new HashMap<String, Method>();

            for (Method method : methods) {

                methodMap.put(method.getName(), method);

            }
            System.out.println("methodMap:" + methodMap);

            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();

            int count = resultSetMetaData.getColumnCount();

            for (int i = 0; i < count; i++) {
                String columnName = resultSetMetaData.getColumnName(i);

                Method method = methodMap.get("get" + columnName.toLowerCase());

                if (method == null) {
                    continue;
                }
                Class[] classes = method.getParameterTypes();

                Object obj = "";

                Class type = classes[0];

                new IntMethod(resultSet, i);

                method.invoke(object, map2Result(type));
            }
            return object;

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException | InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("出错了");
        return null;
    }

    public static void main(String[] args) {

    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>The nodefinder application</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc">

Modules

nodefinder

nodefinder_app

nodefinder_ec2

nodefinder_ec2_api

nodefinder_ec2_api_aws

nodefinder_ec2_api_http

nodefinder_ec2_api_httpc

nodefinder_ec2_api_xml

nodefinder_multicast

nodefinder_string

nodefinder_sup


text:
<?php

namespace Brasa\TurnoBundle\Repository;

use Doctrine\ORM\EntityRepository;

class TurPedidoDetalleRecursoRepository extends EntityRepository {
    public function listaDql($codigoPedidoDetalle) {
        $dql   = "SELECT pdr FROM BrasaTurnoBundle:TurPedidoDetalleRecurso pdr WHERE pdr.codigoPedidoDetalleFk = " . $codigoPedidoDetalle;
        $dql .= " ORDER BY pdr.posicion";
        return $dql;
    }

    public function eliminarSeleccionados($arrSeleccionados) {
        if(count($arrSeleccionados) > 0) {
            $em = $this->getEntityManager();
            foreach ($arrSeleccionados AS $codigo) {
                $ar = $em->getRepository('BrasaTurnoBundle:TurPedidoDetalleRecurso')->find($codigo);
                $em->remove($ar);
            }
            $em->flush();
        }

    }
}


text:
from google.datacatalog_connectors.rdbms.scrape import \
    base_metadata_enricher, metadata_scraper

from google.datacatalog_connectors.saphana.scrape import \
    query_assembler

class MetadataScraper(metadata_scraper.MetadataScraper):

    # We use hdbcli over pyhdb since pyhdb is not actively maintained
    # and does not support database arg
    # see: https://stackoverflow.com/questions/63772666/how-to-specifies-database-name-in-pyhdb # noqa
    def _create_rdbms_connection(self, connection_args):
        # import at the method level, because this flow is conditional
        # if the connector reads from a CSV file, this is not used.
        from hdbcli.dbapi import connect

        port = connection_args.get('port')

        if port is None:
            port = 39015

        con = connect(databasename=connection_args['database'],
                      address=connection_args['host'],
                      port=port,
                      user=connection_args['user'],
                      password=connection_args['pass'])
        return con

    def _get_metadata_enricher(self):
        return base_metadata_enricher.BaseMetadataEnricher

    def _get_query_assembler(self):
        return query_assembler.QueryAssembler()


text:
// +build windows

/*
 * MinIO Cloud Storage, (C) 2015 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package disk

import (
	"path/filepath"
	"syscall"
	"unsafe"
)

var (
	// GetVolumeInformation provides windows drive volume information.
	GetVolumeInformation = kernel32.NewProc("GetVolumeInformationW")
)

// getFSType returns the filesystem type of the underlying mounted filesystem
func getFSType(path string) string {
	volumeNameSize, nFileSystemNameSize := uint32(260), uint32(260)
	var lpVolumeSerialNumber uint32
	var lpFileSystemFlags, lpMaximumComponentLength uint32
	var lpFileSystemNameBuffer, volumeName [260]uint16
	var ps = syscall.StringToUTF16Ptr(filepath.VolumeName(path))

	// Extract values safely
	// BOOL WINAPI GetVolumeInformation(
	// _In_opt_  LPCTSTR lpRootPathName,
	// _Out_opt_ LPTSTR  lpVolumeNameBuffer,
	// _In_      DWORD   nVolumeNameSize,
	// _Out_opt_ LPDWORD lpVolumeSerialNumber,
	// _Out_opt_ LPDWORD lpMaximumComponentLength,
	// _Out_opt_ LPDWORD lpFileSystemFlags,
	// _Out_opt_ LPTSTR  lpFileSystemNameBuffer,
	// _In_      DWORD   nFileSystemNameSize
	// );

	_, _, _ = GetVolumeInformation.Call(uintptr(unsafe.Pointer(ps)),
		uintptr(unsafe.Pointer(&volumeName)),
		uintptr(volumeNameSize),
		uintptr(unsafe.Pointer(&lpVolumeSerialNumber)),
		uintptr(unsafe.Pointer(&lpMaximumComponentLength)),
		uintptr(unsafe.Pointer(&lpFileSystemFlags)),
		uintptr(unsafe.Pointer(&lpFileSystemNameBuffer)),
		uintptr(nFileSystemNameSize))

	return syscall.UTF16ToString(lpFileSystemNameBuffer[:])
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the jonasarts Pagination bundle package.
 *
 * (c) Jonas Hauser <symfony@jonasarts.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace jonasarts\Bundle\PaginationBundle\Pagination;

use Symfony\Component\HttpFoundation\Request;

use Hasch\Framework\Helper\FilterHelper;
use Hasch\Security\Model\UserInterface;
use jonasarts\Bundle\RegistryBundle\Registry\AbstractRegistry;

/**
 * PaginationData, use for
 * - configuration before request (request -> configuration)
 * - pass configuration to paginator (configuration -> doctrine)
 * - get additional geometry after loading entities (doctrine -> geometry)
 *
 * Avail configuration values (to set before passing AbstractEntityRepository.paginate())
 * - getPageSizes (get/set)
 * - getPageIndex (get/set)
 * - getPageSize  (get/set)
 * - getRangeSize (get/set)
 *
 * Avail doctrine result values (set by AbstractEntityRepository.paginate())
 * - setPageRecords
 * - setTotalRecords
 * - setTotalPages
 *
 * Class calculates pagination 'geometry' after doctrine paginator has loaded the entities automatically on
 * - getPages
 * - getPaginationRangeStartPage
 * - getPaginationRangeEndPage
 * - paginationRangeIncludesFirst
 * - paginationRangeIncludesLast
 *
 *
 * Additional data fields
 *
 * - for UI values
 * -- sortField
 * -- sortDirection
 *
 * - for sql
 * -- sqlSortField : string
 * -- sqlSortDirection : string
 * -- sqlSearchString : string
 * -- sqlFilter : array
 *
 */
class PaginationData
{
    /**
     * @var array
     */
    private $data;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->data = array(
            'page_sizes' => array(10, 20, 50, 100),
            'page_index' => 0,
            'page_size' => 0,
            'range_size' => 0,

            'page_records' => 0,
            'total_records' => 0,
            'total_pages' => 0,

            'sort_field' => null,
            'sort_direction' => null,
        );

        $this->data['sqlSortField'] = null;
        $this->data['sqlSortDirection'] = null;
        $this->data['sqlSearchString'] = null;
        $this->data['sqlFilter'] = array();

        $this->resetPaginationData();
    }

    /**
     * @return array
     */
    public function asArray(): array
    {
        return $this->data;
    }

    /**
     * pagination configuration values
     */

    /**
     * Array with possible paginator range sizes. (Ex.: 10, 20, 50, 100)
     *
     * @return array
     */
    public function getPageSizes(): array
    {
        return $this->data['page_sizes'];
    }

    /**
     * @param array $pageSize
     * @return self
     */
    public function setPageSizes(array $pageSizes): self
    {
        $this->data['page_sizes'] = $pageSizes;

        return $this;
    }

    /**
     * The current page shown in the paginator
     *
     * Ex.: 1
     *
     * @return int
     */
    public function getPageIndex(): int
    {
        return $this->data['page_index'];
    }

    /**
     * @param int $pageIndex
     * @return self
     */
    public function setPageIndex(int $pageIndex): self
    {
        $this->data['page_index'] = $pageIndex;

        return $this;
    }

    /**
     * The current page range size (how many items per page)
     *
     * Ex.: 20
     *
     * @return int
     */
    public function getPageSize(): int
    {
        return $this->data['page_size'];
    }

    /**
     * @param int $pageSize
     * @return self
     */
    public function setPageSize(int $pageSize): self
    {
        $this->data['page_size'] = $pageSize;

        return $this;
    }

    /**
     * The current range size to show in selector (how many pages are visible in the page selector)
     *
     * Ex. :
     * - 3 -> 4 5 6       (prev) (next) (current)
     * - 5 => 4 5 6 7 8
     *
     * Best to use odd values !
     *
     * @return int
     */
    public function getRangeSize(): int
    {
        return $this->data['range_size'];
    }

    /**
     * @param int $pageRange
     * @return self
     */
    public function setRangeSize(int $pageRange): self
    {
        $this->data['range_size'] = $pageRange;

        return $this;
    }

    /**
     * doctrine result values
     */

    public function getPageRecords(): int
    {
        return $this->data['page_records'];
    }

    public function setPageRecords(int $value): self
    {
        $this->data['page_records'] = $value;

        return $this;
    }

    public function getTotalRecords(): int
    {
        return $this->data['total_records'];
    }

    public function setTotalRecords(int $value): self
    {
        $this->data['total_records'] = $value;

        return $this;
    }

    public function getTotalPages(): int
    {
        return $this->data['total_pages'];
    }

    public function setTotalPages(int $value): self
    {
        $this->data['total_pages'] = $value;

        return $this;
    }

    /**
     * ui sort
     */

    public function getSortField(): ?string
    {
        return $this->data['sort_field'];
    }

    public function setSortField(?string $field): self
    {
        $this->data['sort_field'] = $field;

        return $this;
    }

    public function getSortDirection(): ?string
    {
        return $this->data['sort_direction'];
    }

    public function setSortDirection(?string $sort): self
    {
        $this->data['sort_direction'] = $sort;

        return $this;
    }

    /**
     * sql sort
     */

    public function getSqlSortField(): ?string
    {
        return $this->data['sqlSortField'];
    }

    public function setSqlSortField(?string $field): self
    {
        $this->data['sqlSortField'] = $field;

        return $this;
    }

    public function getSqlSortDirection(): ?string
    {
        return $this->data['sqlSortDirection'];
    }

    public function setSqlSortDirection(?string $sort): self
    {
        $this->data['sqlSortDirection'] = $sort;

        return $this;
    }

    public function getSqlSearchString(): ?string
    {
        return $this->data['sqlSearchString'];
    }

    public function setSqlSearchString(?string $s): self
    {
        $this->data['sqlSearchString'] = $s;

        return $this;
    }

    public function getSqlFilter(): array
    {
        return $this->data['sqlFilter'];
    }

    public function setSqlFilter(array $filter): self
    {
        $this->data['sqlFilter'] = $filter;

        return $this;
    }

    /**
     * get calculated pagination data values
     */

    public function resetPaginationData()
    {
        $this->data['pages'] = null;

        $this->data['paginationRangeStartPage'] = 0;
        $this->data['paginationRangeEndPage'] = 0;
        $this->data['paginationRangeIncludesFirst'] = true;
        $this->data['paginationRangeIncludesLast'] = true;
    }

    public function getPages(): ?array
    {
        $this->calculatePaginationData();

        return $this->data['pages'];
    }

    public function getPaginationRangeStartPage(): ?int
    {
        $this->calculatePaginationData();

        return $this->data['paginationRangeStartPage'];
    }

    public function getPaginationRangeEndPage(): ?int
    {
        $this->calculatePaginationData();

        return $this->data['paginationRangeEndPage'];
    }

    public function paginationRangeIncludesFirst(): ?bool
    {
        $this->calculatePaginationData();

        return $this->data['paginationRangeIncludesFirst'];
    }

    public function paginationRangeIncludesLast(): ?bool
    {
        $this->calculatePaginationData();

        return $this->data['paginationRangeIncludesLast'];
    }

    /* get pagination from data */

    /**
     * Calculate some 'geometry' paginaton data, after doctrine paginator has loaded the entities !
     *
     * @return void
     */
    private function calculatePaginationData()
    {
        // already calculated ?
        if (!empty($this->data['pages'])) {
            return;
        }

        // data passed from doctrine query

        //$pageRecords = $this->getPageRecords();
        $totalRecords = $this->getTotalRecords();
        $totalPages = $this->getTotalPages();

        // data from configuration
        $pageIndex = $this->getPageIndex(); // int : current page index
        $rangeSize = $this->getRangeSize(); // int : current range size

        if ($totalRecords == 0) {
            $this->data['pages'] = array(0);

            return;
        }

        if ($rangeSize < 3) {
            throw new \Exception('PaginationData.rangeSize too small');
        }

        // calculation

        if ($rangeSize % 2 <> 0) {
            $halfRangeSize = intval(($rangeSize - 1) / 2);
        } else {
            $halfRangeSize = intval($rangeSize / 2);
        }

        $paginationRangeStartPage = $pageIndex - $halfRangeSize < 0 ? 0 : $pageIndex - $halfRangeSize;
        $paginationRangeEndPage = $pageIndex + $halfRangeSize > $totalPages - 1 ? $totalPages - 1 : $pageIndex + $halfRangeSize;

        while (
            ($paginationRangeEndPage - $paginationRangeStartPage + 1 < $rangeSize &&
                $paginationRangeStartPage != 0) ||
            ($paginationRangeEndPage - $paginationRangeStartPage + 1 < $rangeSize &&
                $paginationRangeEndPage != $totalPages - 1)
            ) {

            while (
                $paginationRangeEndPage - $paginationRangeStartPage + 1 < $rangeSize &&
                $paginationRangeStartPage != 0
                ) {
                // prepend one
                $paginationRangeStartPage--;
            }

            while (
                $paginationRangeEndPage - $paginationRangeStartPage + 1 < $rangeSize &&
                $paginationRangeEndPage != $totalPages - 1
                ) {
                // append one
                $paginationRangeEndPage++;
            }

        }

        // update pagination 'geometry' data
        $this->data['paginationRangeStartPage'] = $paginationRangeStartPage;
        $this->data['paginationRangeEndPage'] = $paginationRangeEndPage;
        $this->data['paginationRangeIncludesFirst'] = $paginationRangeStartPage == 0;
        $this->data['paginationRangeIncludesLast'] = $paginationRangeEndPage == ($totalPages - 1);

        $this->data['pages'] = array();
        for ($i = $paginationRangeStartPage; $i <= $paginationRangeEndPage; $i++) {
            $this->data['pages'][] = $i;
        }
    }
}


text:
class FileImport < Import
  def total_results
    file.length
  end

  def get_data(options={})
    offset = options[:offset].to_i
    result = get_text(offset)
  end

  def get_text(offset = 0, rows = 500)
    text = file.slice(offset...(offset + rows))
    items = text.map do |line|
      line = ActiveSupport::Multibyte::Unicode.tidy_bytes(line)
      raw_doi, raw_published_on, raw_title = line.strip.split(" ", 3)
      next if raw_doi.nil?

      doi = get_id_hash(raw_doi.strip).values.first
      if raw_published_on
        # date_parts is an array of non-null integers: [year, month, day]
        # everything else should be nil and thrown away with compact
        date_parts = raw_published_on.split("-")
        date_parts = date_parts.map { |x| x.to_i > 0 ? x.to_i : nil }.compact
      else
        date_parts = []
      end
      title = raw_title ? raw_title.strip.chomp('.') : ""

      { "doi" => doi,
        "issued" => { "date-parts" => [date_parts] },
        "title" => [title],
        "type" => "article-journal",
        "member" => member }
    end

    { "items" => items }
  end

  def parse_data(result)
    items = result.fetch('items', nil)

    Array(items).map do |item|
      doi = item.fetch("doi", nil)
      title = item.fetch("title", []).first
      date_parts = item["issued"]["date-parts"][0]
      year, month, day = date_parts[0], date_parts[1], date_parts[2]
      type = item.fetch("type", nil)
      work_type_id = WorkType.where(name: type).pluck(:id).first
      member_id = item.fetch("member", nil)
      publisher = Publisher.where(member_id: member_id).first

      csl = {
        "issued" => item.fetch("issued", []),
        "title" => title,
        "type" => type,
        "DOI" => doi,
        "publisher" => publisher
      }

      { doi: doi,
        title: title,
        year: year,
        month: month,
        day: day,
        publisher_id: member_id,
        work_type_id: work_type_id,
        tracked: true,
        csl: csl }
    end
  end
end


text:
define(['exports', 'core-js', 'aurelia-path', 'aurelia-metadata'], function (exports, _coreJs, _aureliaPath, _aureliaMetadata) {
  'use strict';

  exports.__esModule = true;

  var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

  var TemplateDependency = function TemplateDependency(src, name) {
    _classCallCheck(this, TemplateDependency);

    this.src = src;
    this.name = name;
  };

  exports.TemplateDependency = TemplateDependency;

  var TemplateRegistryEntry = (function () {
    function TemplateRegistryEntry(address) {
      _classCallCheck(this, TemplateRegistryEntry);

      this.address = address;
      this.template = null;
      this.dependencies = null;
      this.resources = null;
      this.factory = null;
    }

    TemplateRegistryEntry.prototype.setTemplate = function setTemplate(template) {
      var address = this.address;
      var useResources = undefined;
      var current = undefined;
      var src = undefined;

      this.template = template;
      useResources = template.content.querySelectorAll('require');
      this.dependencies = new Array(useResources.length);

      if (useResources.length === 0) {
        return;
      }

      for (var i = 0, ii = useResources.length; i < ii; ++i) {
        current = useResources[i];
        src = current.getAttribute('from');

        if (!src) {
          throw new Error('<require> element in ' + address + ' has no "from" attribute.');
        }

        this.dependencies[i] = new TemplateDependency(_aureliaPath.relativeToFile(src, address), current.getAttribute('as'));

        if (current.parentNode) {
          current.parentNode.removeChild(current);
        }
      }
    };

    TemplateRegistryEntry.prototype.addDependency = function addDependency(src, name) {
      if (typeof src === 'string') {
        this.dependencies.push(new TemplateDependency(_aureliaPath.relativeToFile(src, this.address), name));
      } else if (typeof src === 'function') {
        var origin = _aureliaMetadata.Origin.get(src);
        this.dependencies.push(new TemplateDependency(origin.moduleId, name));
      }
    };

    TemplateRegistryEntry.prototype.setResources = function setResources(resources) {
      this.resources = resources;
    };

    TemplateRegistryEntry.prototype.setFactory = function setFactory(factory) {
      this.factory = factory;
    };

    _createClass(TemplateRegistryEntry, [{
      key: 'templateIsLoaded',
      get: function get() {
        return this.template !== null;
      }
    }, {
      key: 'isReady',
      get: function get() {
        return this.factory !== null;
      }
    }]);

    return TemplateRegistryEntry;
  })();

  exports.TemplateRegistryEntry = TemplateRegistryEntry;

  var Loader = (function () {
    function Loader() {
      _classCallCheck(this, Loader);

      this.templateRegistry = {};
    }

    Loader.prototype.loadModule = function loadModule(id) {
      throw new Error('Loaders must implement loadModule(id).');
    };

    Loader.prototype.loadAllModules = function loadAllModules(ids) {
      throw new Error('Loader must implement loadAllModules(ids).');
    };

    Loader.prototype.loadTemplate = function loadTemplate(url) {
      throw new Error('Loader must implement loadTemplate(url).');
    };

    Loader.prototype.loadText = function loadText(url) {
      throw new Error('Loader must implement loadText(url).');
    };

    Loader.prototype.applyPluginToUrl = function applyPluginToUrl(url, pluginName) {
      throw new Error('Loader must implement applyPluginToUrl(url, pluginName).');
    };

    Loader.prototype.addPlugin = function addPlugin(pluginName, implementation) {
      throw new Error('Loader must implement addPlugin(pluginName, implementation).');
    };

    Loader.prototype.getOrCreateTemplateRegistryEntry = function getOrCreateTemplateRegistryEntry(id) {
      var entry = this.templateRegistry[id];

      if (entry === undefined) {
        this.templateRegistry[id] = entry = new TemplateRegistryEntry(id);
      }

      return entry;
    };

    return Loader;
  })();

  exports.Loader = Loader;
});


text:
/**
 * @module JSON Object Signing and Encryption (JOSE)
 */
const JWK = require('./jose/JWK')
const JWKSet = require('./jose/JWKSet')
const JWT = require('./jose/JWT')
const JWD = require('./jose/JWD')
const Base64URLSchema = require('./schemas/Base64URLSchema')
const JOSEHeaderSchema = require('./schemas/JOSEHeaderSchema')
const JWKSchema = require('./schemas/JWKSchema')
const JWKSetSchema = require('./schemas/JWKSetSchema')
const JWTClaimsSetSchema = require('./schemas/JWTClaimsSetSchema')
const JWTSchema = require('./schemas/JWTSchema')

/**
 * Export
 */
module.exports = {
  JWK,
  JWKSet,
  JWT,
  JWD,
  Base64URLSchema,
  JOSEHeaderSchema,
  JWKSchema,
  JWKSetSchema,
  JWTClaimsSetSchema,
  JWTSchema
}


text:
package com.rackspacecloud.blueflood.inputs.handlers;

import com.github.tlrx.elasticsearch.test.EsSetup;
import com.rackspacecloud.blueflood.http.HttpClientVendor;
import com.rackspacecloud.blueflood.io.EventElasticSearchIO;
import com.rackspacecloud.blueflood.io.EventsIO;
import com.rackspacecloud.blueflood.outputs.handlers.HttpMetricDataQueryServer;
import com.rackspacecloud.blueflood.service.*;
import com.rackspacecloud.blueflood.types.Event;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

import static org.mockito.Mockito.spy;

public class HttpAnnotationsEndToEndTest {
    private static HttpIngestionService httpIngestionService;
    private static HttpClientVendor vendor;
    private static DefaultHttpClient client;
    private static Collection<Integer> manageShards = new HashSet<Integer>();
    private static int httpPort;
    private static int queryPort;
    private static ScheduleContext context;
    private static EventsIO eventsSearchIO;
    private static HttpQueryService httpQueryService;
    private final String tenant_id = "333333";
    private static EsSetup esSetup;
    //A time stamp 2 days ago
    private final long baseMillis = Calendar.getInstance().getTimeInMillis() - 172800000;

    @BeforeClass
    public static void setUp() throws Exception {
        System.setProperty(CoreConfig.EVENTS_MODULES.name(), "com.rackspacecloud.blueflood.io.EventElasticSearchIO");
        Configuration.getInstance().init();
        httpPort = Configuration.getInstance().getIntegerProperty(HttpConfig.HTTP_INGESTION_PORT);
        queryPort = Configuration.getInstance().getIntegerProperty(HttpConfig.HTTP_METRIC_DATA_QUERY_PORT);
        manageShards.add(1); manageShards.add(5); manageShards.add(6);
        context = spy(new ScheduleContext(System.currentTimeMillis(), manageShards));

        esSetup = new EsSetup();
        esSetup.execute(EsSetup.deleteAll());
        esSetup.execute(EsSetup.createIndex(EventElasticSearchIO.EVENT_INDEX)
                .withSettings(EsSetup.fromClassPath("index_settings.json"))
                .withMapping("graphite_event", EsSetup.fromClassPath("events_mapping.json")));
        eventsSearchIO = new EventElasticSearchIO(esSetup.client());
        HttpMetricsIngestionServer server = new HttpMetricsIngestionServer(context);
        server.setHttpEventsIngestionHandler(new HttpEventsIngestionHandler(eventsSearchIO));

        httpIngestionService = new HttpIngestionService();
        httpIngestionService.setMetricsIngestionServer(server);
        httpIngestionService.startService(context);

        httpQueryService = new HttpQueryService();
        HttpMetricDataQueryServer queryServer = new HttpMetricDataQueryServer();
        queryServer.setEventsIO(eventsSearchIO);
        httpQueryService.setServer(queryServer);
        httpQueryService.startService();

        vendor = new HttpClientVendor();
        client = vendor.getClient();
    }

    @Test
    public void testAnnotationsEndToEndHappyCase() throws Exception {
        final int batchSize = 1;
        String event = createTestEvent(batchSize);
        HttpResponse response = postEvent(event, tenant_id);
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
        Thread.sleep(1000);

        Map<String,String> parameterMap = new HashMap<String, String>();
        parameterMap.put(Event.fromParameterName, String.valueOf(baseMillis - 86400000));
        parameterMap.put(Event.untilParameterName, String.valueOf(baseMillis + (86400000*3)));
        HttpGet get = new HttpGet(getAnnotationsQueryURI(parameterMap));
        response = client.execute(get);

        String responseString = EntityUtils.toString(response.getEntity());
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
        Assert.assertFalse(responseString.equals("[]"));
        Assert.assertTrue(responseString.contains("deployment 0"));
    }

    private HttpResponse postEvent(String requestBody, String tenantId) throws Exception {
        URIBuilder builder = new URIBuilder().setScheme("http").setHost("127.0.0.1")
                .setPort(httpPort).setPath("/v2.0/" + tenantId + "/events");
        HttpPost post = new HttpPost(builder.build());
        HttpEntity entity = new StringEntity(requestBody,
                ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        post.setHeader(Event.FieldLabels.tenantId.name(), tenantId);
        post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
        HttpResponse response = client.execute(post);
        return response;
    }

    private static String createTestEvent(int batchSize) throws Exception {
        StringBuilder events = new StringBuilder();
        for (int i=0; i<batchSize; i++) {
            Event event = new Event();
            event.setWhat("deployment "+i);
            event.setWhen(Calendar.getInstance().getTimeInMillis());
            event.setData("deploying prod "+i);
            event.setTags("deployment "+i);
            events.append(new ObjectMapper().writeValueAsString(event));
        }
        return events.toString();
    }

    private URI getAnnotationsQueryURI(Map<String, String> parameterMap) throws URISyntaxException {
        URIBuilder builder = new URIBuilder().setScheme("http").setHost("127.0.0.1")
                .setPort(queryPort).setPath("/v2.0/" + tenant_id + "/events/getEvents");

        Set<String> parameters = parameterMap.keySet();
        Iterator<String> setIterator = parameters.iterator();
        while (setIterator.hasNext()){
            String paramName = setIterator.next();
            builder.setParameter(paramName, parameterMap.get(paramName));
        }
        return builder.build();
    }

    @AfterClass
    public static void tearDownClass() throws Exception{
        Configuration.getInstance().setProperty(CoreConfig.EVENTS_MODULES.name(), "");
        System.clearProperty(CoreConfig.EVENTS_MODULES.name());
        if (esSetup != null) {
            esSetup.terminate();
        }

        if (vendor != null) {
            vendor.shutdown();
        }

        if (httpIngestionService != null) {
            httpIngestionService.shutdownService();
        }

        if (httpQueryService != null) {
            httpQueryService.stopService();
        }
    }
}


text:
package com.ayros.historycleaner.helpers;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.ayros.historycleaner.Globals;

public class Logger
{
	private static boolean debugMode = false;
	private static boolean hasCheckedForDebug = false;

	private static boolean logToFile = false;
	private static boolean hasCheckedForLogToFile = false;

	public static void error(String message)
	{
		System.err.println("ERROR: " + message);
		if (isLogToFileMode())
		{
			logToFile("ERROR: " + message);
		}
	}

	public static void errorST(String message)
	{
		error(message);
		printStack();
	}

	public static void errorST(String message, Exception e)
	{
		error(message);

		if (isLogToFileMode())
		{
			logToFile("Exception: " + e.toString());
		}

		System.err.print("Stack Trace: ");
		e.printStackTrace();
	}

	public static void debug(String message)
	{
		if (isDebugMode())
		{
			System.out.println("DEBUG: " + message);
			if (isLogToFileMode())
			{
				logToFile("DEBUG: " + message);
			}
		}
	}

	public static boolean isDebugMode()
	{
		if (debugMode || hasCheckedForDebug)
		{
			return debugMode;
		}
		else
		{
			String filesDir = Globals.getContext().getApplicationContext().getFilesDir().getAbsolutePath();

			File checkFile = new File(filesDir + "/debugmode.txt");

			hasCheckedForDebug = true;
			debugMode = checkFile.exists();

			System.out.println("Is Debug Mode: " + debugMode);

			return debugMode;
		}
	}

	public static boolean isLogToFileMode()
	{
		if (logToFile || hasCheckedForLogToFile)
		{
			return logToFile;
		}
		else
		{
			String filesDir = Globals.getContext().getApplicationContext().getFilesDir().getAbsolutePath();

			File checkFile = new File(filesDir + "/logtofile.txt");

			hasCheckedForLogToFile = true;
			logToFile = checkFile.exists();

			System.out.println("Is Log-To-File Mode: " + logToFile);

			return logToFile;
		}
	}

	private static void logToFile(String msg)
	{
		String filesDir = Globals.getContext().getApplicationContext().getFilesDir().getAbsolutePath();

		FileWriter logWriter = null;
		try
		{
			logWriter = new FileWriter(filesDir + "/log.txt", true);
			logWriter.write(msg);
			logWriter.write('\n');
			logWriter.flush();
		}
		catch (IOException e)
		{
		}
		finally
		{
			try
			{
				if (logWriter != null)
				{
					logWriter.close();
				}
			}
			catch (IOException e)
			{
			}
		}
	}

	public static void printStack()
	{
		Thread.dumpStack();
	}
}


text:
package org.opensingular.requirement.module.admin.healthsystem.extension;

import org.apache.wicket.markup.html.panel.Panel;
import org.opensingular.requirement.module.admin.healthsystem.panel.IndexPanel;

public class IndexFormsAdminEntry implements AdministrationEntryExtension {
    @Override
    public String name() {
        return "Index Forms";
    }

    @Override
    public Panel makePanel(String id) {
        return new IndexPanel(id);
    }
}


text:
namespace arrow {

namespace py {

class OwnedRef;

// \brief Get an arrow DataType instance from Arrow's Type::type enum
// \param[in] type One of the values of Arrow's Type::type enum
// \return A shared pointer to DataType
ARROW_PYTHON_EXPORT std::shared_ptr<DataType> GetPrimitiveType(Type::type type);

// \brief Construct a np.float16 object from a npy_half value.
ARROW_PYTHON_EXPORT PyObject* PyHalf_FromHalf(npy_half value);

// \brief Convert a Python object to a npy_half value.
ARROW_PYTHON_EXPORT Status PyFloat_AsHalf(PyObject* obj, npy_half* out);

namespace internal {

// \brief Import a Python module
// \param[in] module_name The name of the module
// \param[out] ref The OwnedRef containing the module PyObject*
ARROW_PYTHON_EXPORT
Status ImportModule(const std::string& module_name, OwnedRef* ref);

// \brief Import an object from a Python module
// \param[in] module A Python module
// \param[in] name The name of the object to import
// \param[out] ref The OwnedRef containing the \c name attribute of the Python module \c
// module
ARROW_PYTHON_EXPORT
Status ImportFromModule(PyObject* module, const std::string& name, OwnedRef* ref);

// \brief Check whether obj is an integer, independent of Python versions.
inline bool IsPyInteger(PyObject* obj) {
#if PYARROW_IS_PY2
  return PyLong_Check(obj) || PyInt_Check(obj);
#else
  return PyLong_Check(obj);
#endif
}

// \brief Use pandas missing value semantics to check if a value is null
ARROW_PYTHON_EXPORT
bool PandasObjectIsNull(PyObject* obj);

// \brief Check whether obj is a floating-point NaN
ARROW_PYTHON_EXPORT
bool PyFloat_IsNaN(PyObject* obj);

inline bool IsPyBinary(PyObject* obj) {
  return PyBytes_Check(obj) || PyByteArray_Check(obj);
}

// \brief Convert a Python integer into a C integer
// \param[in] obj A Python integer
// \param[out] out A pointer to a C integer to hold the result of the conversion
// \return The status of the operation
template <typename Int>
Status CIntFromPython(PyObject* obj, Int* out, const std::string& overflow_message = "");

// \brief Convert a Python unicode string to a std::string
ARROW_PYTHON_EXPORT
Status PyUnicode_AsStdString(PyObject* obj, std::string* out);

// \brief Convert a Python bytes object to a std::string
ARROW_PYTHON_EXPORT
std::string PyBytes_AsStdString(PyObject* obj);

// \brief Call str() on the given object and return the result as a std::string
ARROW_PYTHON_EXPORT
Status PyObject_StdStringStr(PyObject* obj, std::string* out);

// \brief Return the repr() of the given object (always succeeds)
ARROW_PYTHON_EXPORT
std::string PyObject_StdStringRepr(PyObject* obj);

// \brief Cast the given size to int32_t, with error checking
inline Status CastSize(Py_ssize_t size, int32_t* out,
                       const char* error_msg = "Maximum size exceeded (2GB)") {
  // size is assumed to be positive
  if (size > std::numeric_limits<int32_t>::max()) {
    return Status::Invalid(error_msg);
  }
  *out = static_cast<int32_t>(size);
  return Status::OK();
}

inline Status CastSize(Py_ssize_t size, int64_t* out, const char* error_msg = NULLPTR) {
  // size is assumed to be positive
  *out = static_cast<int64_t>(size);
  return Status::OK();
}

// \brief Print the Python object's __str__ form along with the passed error
// message
ARROW_PYTHON_EXPORT
Status InvalidValue(PyObject* obj, const std::string& why);

ARROW_PYTHON_EXPORT
Status IntegerScalarToDoubleSafe(PyObject* obj, double* result);
ARROW_PYTHON_EXPORT
Status IntegerScalarToFloat32Safe(PyObject* obj, float* result);

// \brief Print Python object __repr__
void DebugPrint(PyObject* obj);

}  // namespace internal
}  // namespace py
}  // namespace arrow

#endif  // ARROW_PYTHON_HELPERS_H


text:
package com.amazonaws.services.codepipeline.model.transform;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.codepipeline.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.protocol.json.*;

/**
 * PutJobFailureResultRequest Marshaller
 */
public class PutJobFailureResultRequestMarshaller
        implements
        Marshaller<Request<PutJobFailureResultRequest>, PutJobFailureResultRequest> {

    private final SdkJsonProtocolFactory protocolFactory;

    public PutJobFailureResultRequestMarshaller(
            SdkJsonProtocolFactory protocolFactory) {
        this.protocolFactory = protocolFactory;
    }

    public Request<PutJobFailureResultRequest> marshall(
            PutJobFailureResultRequest putJobFailureResultRequest) {

        if (putJobFailureResultRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<PutJobFailureResultRequest> request = new DefaultRequest<PutJobFailureResultRequest>(
                putJobFailureResultRequest, "AWSCodePipeline");
        request.addHeader("X-Amz-Target",
                "CodePipeline_20150709.PutJobFailureResult");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final StructuredJsonGenerator jsonGenerator = protocolFactory
                    .createGenerator();

            jsonGenerator.writeStartObject();

            if (putJobFailureResultRequest.getJobId() != null) {
                jsonGenerator.writeFieldName("jobId").writeValue(
                        putJobFailureResultRequest.getJobId());
            }
            if (putJobFailureResultRequest.getFailureDetails() != null) {
                jsonGenerator.writeFieldName("failureDetails");
                FailureDetailsJsonMarshaller.getInstance().marshall(
                        putJobFailureResultRequest.getFailureDetails(),
                        jsonGenerator);
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", jsonGenerator.getContentType());
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
<?php

class DBManager{

    private $BaseDatos;
	private $Servidor;
    private $Instancia;
	private $Usuario;
	private $Clave;
    private $Conexion;
    private $Gestor;

    public function __construct(){
        /*
            Gestor
            1 = SqlServer
            2 = MySql
        */
        /*
        $this->Servidor = ".";
        $this->Instancia = "";
		$this->Usuario = "";
		$this->Clave = "";
		$this->BaseDatos = "WFNPD";
        $this->Gestor = 1;
        */

        $this->Servidor = "localhost";
        //$this->Servidor = "capmysql.arhena.com.ec";
		$this->Usuario = "root";
		$this->Clave = "";
		$this->BaseDatos = "qualitycheck";
        $this->Gestor = 2;
        // Establecer la zona horaria
        date_default_timezone_set('America/Guayaquil');
	}

    public function DBParametros($servidor,$instancia,$db,$usuario,$clave) {
        $this->Servidor = $servidor;
        $this->Instancia = $instancia;
		$this->Usuario = $usuario;
		$this->Clave = $clave;
		$this->BaseDatos = $db;
	}

    public function BDGestor(){
        if($this->Gestor==1){
            return 'odbc_fetch_array';
        }else{
            return 'mysqli_fetch_array';
        }
    }

    public function BDFields(){
        if($this->Gestor==1){
            return array('odbc_num_fields','odbc_field_name');
        }else{
            return array('mysqli_num_fields','mysqli_fetch_field_direct');
        }
    }

    public function DBConectar(){
        if($this->Gestor==1){
            $conn = odbc_connect("Driver={SQL Server};Server=".$this->Servidor."\\".$this->Instancia.";Database=".$this->BaseDatos.";", $this->Usuario, $this->Clave);
            if(!($conn)){
                die("Problemas con la conexión");
                $this->Conexion = false;
                return false;
            }else{
                $this->Conexion = $conn;
                return true;
            }
        }else{
            $conn = mysqli_connect($this->Servidor,$this->Usuario,$this->Clave,$this->BaseDatos);
            if(!($conn)){
                die("Problemas con la conexión");
                $this->Conexion = false;
                return false;
            }else{
                $this->Conexion = $conn;
                return true;
            }
        }
	}

    public function DBConsulta($sql){
        if($this->Gestor==1){
            $resultado = odbc_exec($this->Conexion, utf8_decode($sql)) or die("<p>".odbc_errormsg());
            return $resultado;
        }else{
            mysqli_set_charset($this->Conexion,"utf8");
            $resultado = mysqli_query($this->Conexion,$sql) or die(mysqli_error($this->Conexion));
            return $resultado;
        }
	}

    public function __destruct(){
        if($this->Gestor==1){
            if($this->Conexion){
                odbc_close($this->Conexion);
            }
        }else{
            if($this->Conexion){
                mysqli_close($this->Conexion);
            }
        }
	}

}

?>


text:
cp -r ../../examples .
cp -r ../../tests .
cp ../../runtests.py .

docker build -t 'reflectrpc-test:python2.7' .

rm -rf examples
rm -rf tests
rm runtests.py


text:
Plugin collects network metrics from `/proc/net/netstat`, `/proc/net/snmp` and `/proc/net/snmp6` files

### Configuration

The plugin firstly tries to read file paths from config values
if it is empty, then it reads from env variables.
* `PROC_NET_NETSTAT`
* `PROC_NET_SNMP`
* `PROC_NET_SNMP6`

If these variables are also not set,
then it tries to read the proc root from env - `PROC_ROOT`,
and sets `/proc` as a root path if `PROC_ROOT` is also empty.

Then appends default file paths:
* `/net/netstat`
* `/net/snmp`
* `/net/snmp6`

So if nothing is given, no paths in config and in env vars, the plugin takes the default paths.
* `/proc/net/netstat`
* `/proc/net/snmp`
* `/proc/net/snmp6`

The sample config file
```toml
[[inputs.nstat]]
  ## file paths
  ## e.g: /proc/net/netstat, /proc/net/snmp, /proc/net/snmp6
  # proc_net_netstat    = 	""
  # proc_net_snmp 		= 	""
  # proc_net_snmp6 		= 	""
  ## dump metrics with 0 values too
  # dump_zeros			= 	true
```

In case that `proc_net_snmp6` path doesn't exist (e.g. IPv6 is not enabled) no error would be raised.

### Measurements & Fields

- nstat
    - Icmp6InCsumErrors
    - Icmp6InDestUnreachs
    - Icmp6InEchoReplies
    - Icmp6InEchos
    - Icmp6InErrors
    - Icmp6InGroupMembQueries
    - Icmp6InGroupMembReductions
    - Icmp6InGroupMembResponses
    - Icmp6InMLDv2Reports
    - Icmp6InMsgs
    - Icmp6InNeighborAdvertisements
    - Icmp6InNeighborSolicits
    - Icmp6InParmProblems
    - Icmp6InPktTooBigs
    - Icmp6InRedirects
    - Icmp6InRouterAdvertisements
    - Icmp6InRouterSolicits
    - Icmp6InTimeExcds
    - Icmp6OutDestUnreachs
    - Icmp6OutEchoReplies
    - Icmp6OutEchos
    - Icmp6OutErrors
    - Icmp6OutGroupMembQueries
    - Icmp6OutGroupMembReductions
    - Icmp6OutGroupMembResponses
    - Icmp6OutMLDv2Reports
    - Icmp6OutMsgs
    - Icmp6OutNeighborAdvertisements
    - Icmp6OutNeighborSolicits
    - Icmp6OutParmProblems
    - Icmp6OutPktTooBigs
    - Icmp6OutRedirects
    - Icmp6OutRouterAdvertisements
    - Icmp6OutRouterSolicits
    - Icmp6OutTimeExcds
    - Icmp6OutType133
    - Icmp6OutType135
    - Icmp6OutType143
    - IcmpInAddrMaskReps
    - IcmpInAddrMasks
    - IcmpInCsumErrors
    - IcmpInDestUnreachs
    - IcmpInEchoReps
    - IcmpInEchos
    - IcmpInErrors
    - IcmpInMsgs
    - IcmpInParmProbs
    - IcmpInRedirects
    - IcmpInSrcQuenchs
    - IcmpInTimeExcds
    - IcmpInTimestampReps
    - IcmpInTimestamps
    - IcmpMsgInType3
    - IcmpMsgOutType3
    - IcmpOutAddrMaskReps
    - IcmpOutAddrMasks
    - IcmpOutDestUnreachs
    - IcmpOutEchoReps
    - IcmpOutEchos
    - IcmpOutErrors
    - IcmpOutMsgs
    - IcmpOutParmProbs
    - IcmpOutRedirects
    - IcmpOutSrcQuenchs
    - IcmpOutTimeExcds
    - IcmpOutTimestampReps
    - IcmpOutTimestamps
    - Ip6FragCreates
    - Ip6FragFails
    - Ip6FragOKs
    - Ip6InAddrErrors
    - Ip6InBcastOctets
    - Ip6InCEPkts
    - Ip6InDelivers
    - Ip6InDiscards
    - Ip6InECT0Pkts
    - Ip6InECT1Pkts
    - Ip6InHdrErrors
    - Ip6InMcastOctets
    - Ip6InMcastPkts
    - Ip6InNoECTPkts
    - Ip6InNoRoutes
    - Ip6InOctets
    - Ip6InReceives
    - Ip6InTooBigErrors
    - Ip6InTruncatedPkts
    - Ip6InUnknownProtos
    - Ip6OutBcastOctets
    - Ip6OutDiscards
    - Ip6OutForwDatagrams
    - Ip6OutMcastOctets
    - Ip6OutMcastPkts
    - Ip6OutNoRoutes
    - Ip6OutOctets
    - Ip6OutRequests
    - Ip6ReasmFails
    - Ip6ReasmOKs
    - Ip6ReasmReqds
    - Ip6ReasmTimeout
    - IpDefaultTTL
    - IpExtInBcastOctets
    - IpExtInBcastPkts
    - IpExtInCEPkts
    - IpExtInCsumErrors
    - IpExtInECT0Pkts
    - IpExtInECT1Pkts
    - IpExtInMcastOctets
    - IpExtInMcastPkts
    - IpExtInNoECTPkts
    - IpExtInNoRoutes
    - IpExtInOctets
    - IpExtInTruncatedPkts
    - IpExtOutBcastOctets
    - IpExtOutBcastPkts
    - IpExtOutMcastOctets
    - IpExtOutMcastPkts
    - IpExtOutOctets
    - IpForwDatagrams
    - IpForwarding
    - IpFragCreates
    - IpFragFails
    - IpFragOKs
    - IpInAddrErrors
    - IpInDelivers
    - IpInDiscards
    - IpInHdrErrors
    - IpInReceives
    - IpInUnknownProtos
    - IpOutDiscards
    - IpOutNoRoutes
    - IpOutRequests
    - IpReasmFails
    - IpReasmOKs
    - IpReasmReqds
    - IpReasmTimeout
    - TcpActiveOpens
    - TcpAttemptFails
    - TcpCurrEstab
    - TcpEstabResets
    - TcpExtArpFilter
    - TcpExtBusyPollRxPackets
    - TcpExtDelayedACKLocked
    - TcpExtDelayedACKLost
    - TcpExtDelayedACKs
    - TcpExtEmbryonicRsts
    - TcpExtIPReversePathFilter
    - TcpExtListenDrops
    - TcpExtListenOverflows
    - TcpExtLockDroppedIcmps
    - TcpExtOfoPruned
    - TcpExtOutOfWindowIcmps
    - TcpExtPAWSActive
    - TcpExtPAWSEstab
    - TcpExtPAWSPassive
    - TcpExtPruneCalled
    - TcpExtRcvPruned
    - TcpExtSyncookiesFailed
    - TcpExtSyncookiesRecv
    - TcpExtSyncookiesSent
    - TcpExtTCPACKSkippedChallenge
    - TcpExtTCPACKSkippedFinWait2
    - TcpExtTCPACKSkippedPAWS
    - TcpExtTCPACKSkippedSeq
    - TcpExtTCPACKSkippedSynRecv
    - TcpExtTCPACKSkippedTimeWait
    - TcpExtTCPAbortFailed
    - TcpExtTCPAbortOnClose
    - TcpExtTCPAbortOnData
    - TcpExtTCPAbortOnLinger
    - TcpExtTCPAbortOnMemory
    - TcpExtTCPAbortOnTimeout
    - TcpExtTCPAutoCorking
    - TcpExtTCPBacklogDrop
    - TcpExtTCPChallengeACK
    - TcpExtTCPDSACKIgnoredNoUndo
    - TcpExtTCPDSACKIgnoredOld
    - TcpExtTCPDSACKOfoRecv
    - TcpExtTCPDSACKOfoSent
    - TcpExtTCPDSACKOldSent
    - TcpExtTCPDSACKRecv
    - TcpExtTCPDSACKUndo
    - TcpExtTCPDeferAcceptDrop
    - TcpExtTCPDirectCopyFromBacklog
    - TcpExtTCPDirectCopyFromPrequeue
    - TcpExtTCPFACKReorder
    - TcpExtTCPFastOpenActive
    - TcpExtTCPFastOpenActiveFail
    - TcpExtTCPFastOpenCookieReqd
    - TcpExtTCPFastOpenListenOverflow
    - TcpExtTCPFastOpenPassive
    - TcpExtTCPFastOpenPassiveFail
    - TcpExtTCPFastRetrans
    - TcpExtTCPForwardRetrans
    - TcpExtTCPFromZeroWindowAdv
    - TcpExtTCPFullUndo
    - TcpExtTCPHPAcks
    - TcpExtTCPHPHits
    - TcpExtTCPHPHitsToUser
    - TcpExtTCPHystartDelayCwnd
    - TcpExtTCPHystartDelayDetect
    - TcpExtTCPHystartTrainCwnd
    - TcpExtTCPHystartTrainDetect
    - TcpExtTCPKeepAlive
    - TcpExtTCPLossFailures
    - TcpExtTCPLossProbeRecovery
    - TcpExtTCPLossProbes
    - TcpExtTCPLossUndo
    - TcpExtTCPLostRetransmit
    - TcpExtTCPMD5NotFound
    - TcpExtTCPMD5Unexpected
    - TcpExtTCPMTUPFail
    - TcpExtTCPMTUPSuccess
    - TcpExtTCPMemoryPressures
    - TcpExtTCPMinTTLDrop
    - TcpExtTCPOFODrop
    - TcpExtTCPOFOMerge
    - TcpExtTCPOFOQueue
    - TcpExtTCPOrigDataSent
    - TcpExtTCPPartialUndo
    - TcpExtTCPPrequeueDropped
    - TcpExtTCPPrequeued
    - TcpExtTCPPureAcks
    - TcpExtTCPRcvCoalesce
    - TcpExtTCPRcvCollapsed
    - TcpExtTCPRenoFailures
    - TcpExtTCPRenoRecovery
    - TcpExtTCPRenoRecoveryFail
    - TcpExtTCPRenoReorder
    - TcpExtTCPReqQFullDoCookies
    - TcpExtTCPReqQFullDrop
    - TcpExtTCPRetransFail
    - TcpExtTCPSACKDiscard
    - TcpExtTCPSACKReneging
    - TcpExtTCPSACKReorder
    - TcpExtTCPSYNChallenge
    - TcpExtTCPSackFailures
    - TcpExtTCPSackMerged
    - TcpExtTCPSackRecovery
    - TcpExtTCPSackRecoveryFail
    - TcpExtTCPSackShiftFallback
    - TcpExtTCPSackShifted
    - TcpExtTCPSchedulerFailed
    - TcpExtTCPSlowStartRetrans
    - TcpExtTCPSpuriousRTOs
    - TcpExtTCPSpuriousRtxHostQueues
    - TcpExtTCPSynRetrans
    - TcpExtTCPTSReorder
    - TcpExtTCPTimeWaitOverflow
    - TcpExtTCPTimeouts
    - TcpExtTCPToZeroWindowAdv
    - TcpExtTCPWantZeroWindowAdv
    - TcpExtTCPWinProbe
    - TcpExtTW
    - TcpExtTWKilled
    - TcpExtTWRecycled
    - TcpInCsumErrors
    - TcpInErrs
    - TcpInSegs
    - TcpMaxConn
    - TcpOutRsts
    - TcpOutSegs
    - TcpPassiveOpens
    - TcpRetransSegs
    - TcpRtoAlgorithm
    - TcpRtoMax
    - TcpRtoMin
    - Udp6IgnoredMulti
    - Udp6InCsumErrors
    - Udp6InDatagrams
    - Udp6InErrors
    - Udp6NoPorts
    - Udp6OutDatagrams
    - Udp6RcvbufErrors
    - Udp6SndbufErrors
    - UdpIgnoredMulti
    - UdpInCsumErrors
    - UdpInDatagrams
    - UdpInErrors
    - UdpLite6InCsumErrors
    - UdpLite6InDatagrams
    - UdpLite6InErrors
    - UdpLite6NoPorts
    - UdpLite6OutDatagrams
    - UdpLite6RcvbufErrors
    - UdpLite6SndbufErrors
    - UdpLiteIgnoredMulti
    - UdpLiteInCsumErrors
    - UdpLiteInDatagrams
    - UdpLiteInErrors
    - UdpLiteNoPorts
    - UdpLiteOutDatagrams
    - UdpLiteRcvbufErrors
    - UdpLiteSndbufErrors
    - UdpNoPorts
    - UdpOutDatagrams
    - UdpRcvbufErrors
    - UdpSndbufErrors

### Tags
- All measurements have the following tags
    - host (host of the system)
    - name (the type of the metric: snmp, snmp6 or netstat)


text:
package views.changekeeper

import composition.TestHarness
import org.scalatest.selenium.WebBrowser.{currentUrl, go}
import pages.changekeeper.PrivacyPolicyPage
import uk.gov.dvla.vehicles.presentation.common.testhelpers.{UiSpec, UiTag}

final class PrivacyPolicyUiSpec extends UiSpec with TestHarness {

  "go to page" should {

    "display the page" taggedAs UiTag in new WebBrowserForSelenium {
      go to PrivacyPolicyPage

      currentUrl should equal(PrivacyPolicyPage.url)
    }
  }
}


text:
/*jshint bitwise: true, curly: true, eqeqeq: true, forin: true, immed: true, indent: 4, latedef: true, newcap: true, noarg: true, noempty: true, nonew: true, quotmark: double, undef: true, unused: vars, strict: true, trailing: true, maxdepth: 3, browser: true, devel: true, asi: true */
/*global _: true */

//
// ARRAY
//

// Contains
// Usage: array.contains(needle)

if (!Array.prototype.contains) {
    Array.prototype.contains = function (needle) {
        "use strict";
        return this.indexOf(needle) > -1
    }
}

// Flatten
// Usage: array.flatten()
if (!Array.prototype.flatten) {
    Array.prototype.flatten = function () {
        "use strict";
        return [].concat.apply([], this)
    }
}

// Unique
// Usage: array.unique()
if (!Array.prototype.unique) {
    Array.prototype.unique = function(a) {
        "use strict";
        return function () {
            return this.filter(a);
        }
    } (function (a,b,c) { return c.indexOf(a, b + 1) < 0; });
}

// Test Contains
// Usage: _.test();

if (window._ === undefined) {
    window._ = {}
}

_.test = function () {
    "use strict";

    var original = _.test

    return function() {
        var haystack1 = [4, 6, 51],
            haystack2 = ["4", "6", "51"]

        console.assert(haystack1.contains(4), "numeric array numeric contents")
        console.assert(!haystack1.contains("4"), "numeric array string contents")
        console.assert(!haystack1.contains(46), "numeric array bad combined numeric contents")
        console.assert(!haystack1.contains(1), "numeric array bad numeric contents")
        console.assert(!haystack1.contains("1"), "numeric array bad string contents")

        console.assert(haystack2.contains("4"), "string array string contents")
        console.assert(!haystack2.contains(46), "string array bad combined numeric contents")
        console.assert(!haystack2.contains("46"), "string array bad combined string contents")
        console.assert(!haystack2.contains(1), "string array bad numeric contents")
        console.assert(!haystack2.contains("1"), "string array bad string contents")

        return original()
    };
}


text:
package org.apache.nutch.searcher;

import java.io.IOException;

import java.util.HashMap;
import java.util.Iterator;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.*;
import org.apache.hadoop.fs.*;
import org.apache.nutch.protocol.*;
import org.apache.nutch.parse.*;
import org.apache.nutch.util.HadoopFSUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.*;
import org.apache.hadoop.mapred.lib.*;
import org.apache.nutch.crawl.*;

/** Implements {@link HitSummarizer} and {@link HitContent} for a set of
 * fetched segments. */
public class FetchedSegments implements HitSummarizer, HitContent {

  private static class Segment implements Closeable {

    private static final Partitioner PARTITIONER = new HashPartitioner();

    private FileSystem fs;
    private Path segmentDir;

    private MapFile.Reader[] content;
    private MapFile.Reader[] parseText;
    private MapFile.Reader[] parseData;
    private MapFile.Reader[] crawl;
    private Configuration conf;

    public Segment(FileSystem fs, Path segmentDir, Configuration conf) throws IOException {
      this.fs = fs;
      this.segmentDir = segmentDir;
      this.conf = conf;
    }

    public CrawlDatum getCrawlDatum(Text url) throws IOException {
      synchronized (this) {
        if (crawl == null)
          crawl = getReaders(CrawlDatum.FETCH_DIR_NAME);
      }
      return (CrawlDatum)getEntry(crawl, url, new CrawlDatum());
    }

    public byte[] getContent(Text url) throws IOException {
      synchronized (this) {
        if (content == null)
          content = getReaders(Content.DIR_NAME);
      }
      return ((Content)getEntry(content, url, new Content())).getContent();
    }

    public ParseData getParseData(Text url) throws IOException {
      synchronized (this) {
        if (parseData == null)
          parseData = getReaders(ParseData.DIR_NAME);
      }
      return (ParseData)getEntry(parseData, url, new ParseData());
    }

    public ParseText getParseText(Text url) throws IOException {
      synchronized (this) {
        if (parseText == null)
          parseText = getReaders(ParseText.DIR_NAME);
      }
      return (ParseText)getEntry(parseText, url, new ParseText());
    }

    private MapFile.Reader[] getReaders(String subDir) throws IOException {
      return MapFileOutputFormat.getReaders(fs, new Path(segmentDir, subDir), this.conf);
    }

    private Writable getEntry(MapFile.Reader[] readers, Text url,
                              Writable entry) throws IOException {
      return MapFileOutputFormat.getEntry(readers, PARTITIONER, url, entry);
    }

    public void close() throws IOException {
      if (content != null) { closeReaders(content); }
      if (parseText != null) { closeReaders(parseText); }
      if (parseData != null) { closeReaders(parseData); }
      if (crawl != null) { closeReaders(crawl); }
    }

    private void closeReaders(MapFile.Reader[] readers) throws IOException {
      for (int i = 0; i < readers.length; i++) {
        readers[i].close();
      }
    }

  }

  private HashMap segments = new HashMap();
  private Summarizer summarizer;

  /** Construct given a directory containing fetcher output. */
  public FetchedSegments(FileSystem fs, String segmentsDir, Configuration conf) throws IOException {
    FileStatus[] fstats = fs.listStatus(new Path(segmentsDir),
        HadoopFSUtil.getPassDirectoriesFilter(fs));
    Path[] segmentDirs = HadoopFSUtil.getPaths(fstats);
    this.summarizer = new SummarizerFactory(conf).getSummarizer();

    if (segmentDirs != null) {
        for (int i = 0; i < segmentDirs.length; i++) {
            Path segmentDir = segmentDirs[i];
//             Path indexdone = new Path(segmentDir, IndexSegment.DONE_NAME);
//             if (fs.exists(indexdone) && fs.isFile(indexdone)) {
//             	segments.put(segmentDir.getName(), new Segment(fs, segmentDir));
//             }
            segments.put(segmentDir.getName(), new Segment(fs, segmentDir, conf));

        }
    }
  }

  public String[] getSegmentNames() {
    return (String[])segments.keySet().toArray(new String[segments.size()]);
  }

  public byte[] getContent(HitDetails details) throws IOException {
    return getSegment(details).getContent(getUrl(details));
  }

  public ParseData getParseData(HitDetails details) throws IOException {
    return getSegment(details).getParseData(getUrl(details));
  }

  public long getFetchDate(HitDetails details) throws IOException {
    return getSegment(details).getCrawlDatum(getUrl(details))
      .getFetchTime();
  }

  public ParseText getParseText(HitDetails details) throws IOException {
    return getSegment(details).getParseText(getUrl(details));
  }

  public Summary getSummary(HitDetails details, Query query)
    throws IOException {

    if (this.summarizer == null) { return new Summary(); }

    Segment segment = getSegment(details);
    ParseText parseText = segment.getParseText(getUrl(details));
    String text = (parseText != null) ? parseText.getText() : "";

    return this.summarizer.getSummary(text, query);
  }

  private class SummaryThread extends Thread {
    private HitDetails details;
    private Query query;

    private Summary summary;
    private Throwable throwable;

    public SummaryThread(HitDetails details, Query query) {
      this.details = details;
      this.query = query;
    }

    public void run() {
      try {
        this.summary = getSummary(details, query);
      } catch (Throwable throwable) {
        this.throwable = throwable;
      }
    }

  }

  public Summary[] getSummary(HitDetails[] details, Query query)
    throws IOException {
    SummaryThread[] threads = new SummaryThread[details.length];
    for (int i = 0; i < threads.length; i++) {
      threads[i] = new SummaryThread(details[i], query);
      threads[i].start();
    }

    Summary[] results = new Summary[details.length];
    for (int i = 0; i < threads.length; i++) {
      try {
        threads[i].join();
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
      if (threads[i].throwable instanceof IOException) {
        throw (IOException)threads[i].throwable;
      } else if (threads[i].throwable != null) {
        throw new RuntimeException(threads[i].throwable);
      }
      results[i] = threads[i].summary;
    }
    return results;
  }

  private Segment getSegment(HitDetails details) {
    return (Segment)segments.get(details.getValue("segment"));
  }

  private Text getUrl(HitDetails details) {
    String url = details.getValue("orig");
    if (StringUtils.isBlank(url)) {
      url = details.getValue("url");
    }
    return new Text(url);
  }

  public void close() throws IOException {
    Iterator iterator = segments.values().iterator();
    while (iterator.hasNext()) {
      ((Segment) iterator.next()).close();
    }
  }

}


text:
package com.mindcognition.mindraider.ui.swing.concept.annotation.renderer;

import java.awt.Color;
import java.awt.event.FocusListener;

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

import com.emental.mindraider.core.rest.resource.ConceptResource;
import com.mindcognition.mindraider.MindRaiderException;
import com.mindcognition.mindraider.commons.MindRaiderConstants;
import com.mindcognition.mindraider.ui.swing.concept.annotation.listener.EditorAndViewerMouseListener;
import com.mindcognition.mindraider.ui.swing.concept.annotation.listener.EditorFocusListener;
import com.mindcognition.mindraider.ui.swing.concept.annotation.listener.EditorKeyListener;
import com.mindcognition.mindraider.ui.swing.concept.annotation.listener.ViewerKeyListener;
import com.mindcognition.mindraider.ui.swing.concept.annotation.toolbar.TextAnnotationToolbar;
import com.mindcognition.mindraider.ui.swing.concept.annotation.transformer.HtmlToHtmlTransformer;

public class HtmlAnnotationRenderer extends AbstractTextAnnotationRenderer {

    private static final Log logger = LogFactory.getLog(HtmlAnnotationRenderer.class); // {{debug}}

    /**
     * the label text constant.
     * TODO consider bundle
     */
    public static final String LABEL_TEXT = "HTML";

    public HtmlAnnotationRenderer() {
    }

    public void init() {
        EditorAndViewerMouseListener editorAndViewerMouseListener = new EditorAndViewerMouseListener(this);
        super.init(
                new HtmlToHtmlTransformer(),
                new EditorKeyListener(getConceptPanel(),this),
                new ViewerKeyListener(getConceptPanel(),this),
                new EditorFocusListener(getConceptPanel()),
                (FocusListener)null,
                editorAndViewerMouseListener,
                editorAndViewerMouseListener,
                new TextAnnotationToolbar(this));
    }

    public void openConceptAnnotation(ConceptResource conceptResource) {
        logger.debug("openConceptAnnotation() "+conceptResource.getAnnotationContentType() +" # "+getAnnotationTypeOwlClass());
        setConceptResource(conceptResource);

        // verify content type
        if(getAnnotationTypeOwlClass().equals(conceptResource.getAnnotationContentType())) {
            super.openConceptAnnotation(conceptResource);
        } else {
            throw new MindRaiderException("Invalid annotation content type - it's not: "+getAnnotationTypeOwlClass());
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see com.emental.mindraider.concept.annotation.ConceptAnnotation#getAnnotationContentTypeOwlClass()
     */
    public String getAnnotationTypeOwlClass() {
        return MindRaiderConstants.MR_OWL_CONTENT_TYPE_HTML;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.emental.mindraider.concept.annotation.ConceptAnnotation#getLabel()
     */
    public String getAnnotationTypeLabel() {
        // it must be possible to localize label
        return LABEL_TEXT;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.emental.mindraider.concept.annotation.ConceptAnnotationType#getForegroundColor()
     */
    public Color getForegroundColor() {
        return Color.WHITE;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.emental.mindraider.concept.annotation.ConceptAnnotationType#getBackgroundColor()
     */
    public Color getBackgroundColor() {
        return Color.BLACK;
    }

    private static final long serialVersionUID = -3175478167179198528L;
}


text:
package org.robolectric.testing;

import org.robolectric.annotation.internal.Instrument;

@Instrument
public class AnInstrumentedChild extends AnUninstrumentedParent {
  public final String childName;

  public AnInstrumentedChild(String name) {
    super(name.toUpperCase() + "'s child");
    this.childName = name;
  }
}


text:
import pandas as pd
import numpy as np
import json
import sys, os
from natsort import natsorted
import code
import SimpleITK as sitk
import os,sys
import glob
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from skimage import measure
import matplotlib.colors
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import DBSCAN
import math
import code

import matplotlib.pyplot as plt
import numpy as np

annotations = pd.read_csv("annotations_min4.csv") # its possible to use more precise nodule information from candidates_V2.csv

# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

# annotations.dropna()

def plot_histo(X, title):
    plt.hist(X, bins=4)
    plt.title(title)
    plt.xlabel("Priority")
    plt.xlim([1,4])
    plt.ylabel("Frequency")
    plt.show()

def get_stats(X, title):
    print title
    print "Mean: ", np.mean(X)
    print "Std: ", np.std(X)
    print "Total: ", len(X)
    print "Min: ", np.min(X)
    print "Max: ", np.max(X)

LUNA16_annos = pd.read_csv('./LUNA16_annotations.csv', sep = ',')
LUNA16_annos['patient'] = LUNA16_annos['seriesuid'].str.split('.').str[-1]

np.unique(annotations["nodule_priority"], return_counts=True)
# indices = []
# for i in xrange(annotations.shape[0]):
#     if math.isnan(annotations["nodule_priority"].ix[i]):
#         print annotations["seriesuid"].ix[i][34:]
#         print annotations.ix[i]
        # print LUNA16_annos.loc[LUNA16_annos['patient']==annotations["seriesuid"].ix[i][34:]]

#         # .split('.').str[-1]
#
# print indices
# get_stats(annotations["nodule_priority"].dropna(), "Nodule Priorities")
code.interact(local=dict(globals(), **locals()))
LUNA16_annos.loc[LUNA16_annos['patient']=="215640837032688688030770057224"]

# Failure at:
# [162, 166, 639, 863, 1441, 1827, 1829, 1830, 1863, 3164, 3286, 3499, 3762, 3834, 3836, 3860, 3868, 3874, 3983, 3989, 3998, 4000, 4001, 4269, 5177, 5610, 6048, 6055, 6063, 6075, 6205, 6218, 6418, 6844, 6920, 6926, 7470, 8272, 9413, 9894, 9902, 10156, 10197, 11531, 11532, 11533, 11534, 11535, 11540, 11827, 11830, 12077, 12078, 12079, 12110]

# plot_histo(annotations["nodule_priority"].dropna().astype(int), "Nodule Priority")


text:
import unittest
import numpy as np
from op_test import OpTest
import random

def np_partial_concat(inputs, start, length):
    assert len(inputs[0].shape) == 2
    size = inputs[0].shape[1]
    assert start >= -size and start < size

    if start < 0:
        start += size
    if length < 0:
        length = size - start
    assert size >= start + length

    elems = []
    for elem in inputs:
        assert elem.shape == inputs[0].shape
        elems.append(elem[:, start : start + length])
    res = np.concatenate(elems, axis=1)
    return np.concatenate(elems, axis=1)

class TestPartialConcatOp(OpTest):
    def setUp(self):
        self.op_type = "partial_concat"
        self.init_kernel_type()
        self.init_para()
        self.var_names = ['x' + str(num) for num in range(self.var_num)]
        self.vars = [
            np.random.random((self.batch_size, self.column)).astype(self.dtype)
            for num in range(self.var_num)
        ]
        self.inputs = {'X': list(zip(self.var_names, self.vars))}
        self.attrs = {'start_index': self.start_index, 'length': self.length}
        y = np_partial_concat(self.vars[:], self.start_index, self.length)
        self.outputs = {'Out': y}

    def init_kernel_type(self):
        self.dtype = np.float64

    def init_para(self):
        self.batch_size = random.randint(10, 20)
        self.column = random.randint(101, 200)
        self.start_index = random.randint(0, self.column - 1)
        self.length = -1
        self.var_num = random.randint(1, 3)

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        for var_name in self.var_names:
            self.check_grad([var_name], 'Out')

class TestPartialConcatOp2(TestPartialConcatOp):
    def init_para(self):
        self.batch_size = random.randint(1, 10)
        self.column = random.randint(101, 200)
        self.start_index = -5
        self.length = -1
        self.var_num = 3

class TestPartialConcatOp3(TestPartialConcatOp):
    def init_para(self):
        self.batch_size = random.randint(1, 10)
        self.column = random.randint(101, 200)
        self.start_index = 10
        self.length = 20
        self.var_num = 2

class TestPartialConcatOp4(TestPartialConcatOp):
    def init_para(self):
        self.batch_size = random.randint(1, 10)
        self.column = random.randint(101, 200)
        self.start_index = -1
        self.length = -1
        self.var_num = 1

if __name__ == '__main__':
    unittest.main()


text:
class PNMFileType;

////////////////////////////////////////////////////////////////////
//       Class : PNMFileTypeRegistry
// Description : This class maintains the set of all known
//               PNMFileTypes in the universe.
////////////////////////////////////////////////////////////////////
class EXPCL_PANDA_PNMIMAGE PNMFileTypeRegistry {
protected:
  PNMFileTypeRegistry();

public:
  ~PNMFileTypeRegistry();

  void register_type(PNMFileType *type);

PUBLISHED:
  int get_num_types() const;
  PNMFileType *get_type(int n) const;
  MAKE_SEQ(get_types, get_num_types, get_type);

  PNMFileType *get_type_from_extension(const string &filename) const;
  PNMFileType *get_type_from_magic_number(const string &magic_number) const;
  PNMFileType *get_type_by_handle(TypeHandle handle) const;

  void write(ostream &out, int indent_level = 0) const;

  static PNMFileTypeRegistry *get_global_ptr();

private:
  void sort_preferences();

  typedef pvector<PNMFileType *> Types;
  Types _types;

  typedef pmap<string, Types> Extensions;
  Extensions _extensions;

  typedef pmap<TypeHandle, PNMFileType *> Handles;
  Handles _handles;

  bool _requires_sort;

  static PNMFileTypeRegistry *_global_ptr;
};

#endif


text:
<?php

namespace Salma\SymCartBundle\Model;

use Salma\SymCartBundle\Model\Cart as Cart;

/**
 * ShoppingCart
 */
class ShoppingCart extends Cart {

    private $total = 0.00;

    /**
     * __construct() - Constructor. This assigns the name of the cart
     *                 to an instance variable and loads the cart from
     *                 session.
     *
     * @param string $name The name of the cart.
     * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
     */
    function __construct($name, $session) {

        $this->name = $name;
        $this->items = $session->get($this->name);
    }

    /**
     * Get subtotal
     *
     * @return float
     */
    public function getSubtotal($itemId) {

        $this->items[$itemId]['subtotal'] = $this->items[$itemId]['quantity'] *
                $this->items[$itemId]['unit_price'];

        return  $this->items[$itemId]['subtotal'];
    }

    /**
     * Get total
     *
     * @return double
     */
    public function getTotal() {

        if ($this->items) {
            foreach ($this->items as $key => $value) {
                $this->total += $value['quantity'] * $value['unit_price'];
            }
        } else {
            $this->total = 0.00;
        }
        return $this->total;
    }

    /**
     * changeItemQuantity() - change the quantity of specific item
     * @param $itemId
     * @param $quantity - the new quantity
     *
     */
    public function changeItemQuantity($itemId, $quantity) {

        $this->items[$itemId]['quantity'] = $quantity;
    }

}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/privacy/dlp/v2/dlp.proto

namespace Google\Cloud\Dlp\V2;

if (false) {
    /**
     * This class is deprecated. Use Google\Cloud\Dlp\V2\OutputStorageConfig\OutputSchema instead.
     * @deprecated
     */
    class OutputStorageConfig_OutputSchema {}
}
class_exists(OutputStorageConfig\OutputSchema::class);
@trigger_error('Google\Cloud\Dlp\V2\OutputStorageConfig_OutputSchema is deprecated and will be removed in the next major release. Use Google\Cloud\Dlp\V2\OutputStorageConfig\OutputSchema instead', E_USER_DEPRECATED);


text:
package ru.artyrian.statusmanager.web;

import org.apache.log4j.Logger;
import ru.artyrian.statusmanager.service.TaskExecutor;
import ru.artyrian.statusmanager.service.KeyValuesMap;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.ResourceBundle;

public class MyServletContextListener implements ServletContextListener {
    private final static Logger logger = Logger.getLogger(MyServletContextListener.class);

    private static final ResourceBundle props = ResourceBundle.getBundle(KeyValuesMap.AUTH_PROPS_NAME);
    private final TaskExecutor taskExecutor = TaskExecutor.getInstance();

    @Override
    public void contextInitialized(ServletContextEvent contextEvent) {
        /* Do Startup stuff. */
        logger.debug("startup stuff");
        taskExecutor.startTask(Integer.parseInt(props.getString(KeyValuesMap.SECONDS_PERIOD_UPDATE)));
    }

    @Override
    public void contextDestroyed(ServletContextEvent contextEvent) {
        /* Do Shutdown stuff. */
        logger.debug("shutdown stuff");
        taskExecutor.stopTask();
    }

}


text:
<?php

namespace Foundry;

/**
 * Parameter class.
 * Its value will never be quoted by the query builders.
 */
class Parameter implements ParameterInterface
{
    /**
     * @var string|null
     */
    protected $value = null;

    /**
     * @param string $value
     */
    public function __construct(string $value = '?')
    {
        $this->setValue($value);
    }

    /**
     * Set the parameter value.
     *
     * @param string $value
     * @return $this
     * @throws \UnexpectedValueException
     */
    protected function setValue(string $value)
    {
        if ($value === '') {
            throw new \UnexpectedValueException('The parameter value is required.');
        }

        if ($value !== '?' && strpos($value, ':') !== 0) {
            $value = ':' . $value;
        }

        $this->value = $value;

        return $this;
    }

    /**
     * Get the parameter value.
     *
     * @return string
     */
    public function toString()
    {
        return $this->value;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->toString();
    }
}


text:
import java.util.ArrayList;
import java.util.List;

class Sample {
  public static void main(List<String> testTags) {
    final List<String> resultJava7 = new ArrayList<>(testTags.size());
    for (final String tag : tes<caret>tTags) {
      if (!resultJava7.contains(tag.trim())) {
        resultJava7.add(tag.trim());
      }
    }

  }
}