text:
package com.example.administrator.aviation.ui.activity.domjcgrbb;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.example.administrator.aviation.R;
import com.example.administrator.aviation.http.HttpCommons;
import com.example.administrator.aviation.http.HttpRoot;
import com.example.administrator.aviation.tool.DateUtils;
import com.example.administrator.aviation.ui.base.NavBar;
import com.example.administrator.aviation.util.ChoseTimeMethod;

import org.ksoap2.serialization.SoapObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 国内出港日报表
 */

public class DomExportDayCarrierActivity extends Activity implements View.OnClickListener{
    @BindView(R.id.declare_info_begin_time_et)
    EditText declareInfoBeginTimeEt;
    @BindView(R.id.declare_info_begin_time_btn)
    ImageView declareInfoBeginTimeBtn;
    @BindView(R.id.declare_info_search_btn)
    Button declareInfoSearchBtn;
    @BindView(R.id.declare_info_pb)
    ProgressBar declareInfoPb;

    // 获取当前时间
    private String begainTime;
    private String endTime;
    private String currentTime;
    private String xml;

    ChoseTimeMethod choseTimeMethod = new ChoseTimeMethod();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appintexportdaycarrier);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        NavBar navBar = new NavBar(this);
        navBar.setTitle("国内出港日报表查询");
        navBar.hideRight();
        currentTime = DateUtils.getTodayDateTime();
        declareInfoBeginTimeEt.setText(currentTime);

        declareInfoBeginTimeBtn.setOnClickListener(this);

        declareInfoSearchBtn.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.declare_info_begin_time_btn:
                choseTimeMethod.getCurrentTime(DomExportDayCarrierActivity.this, declareInfoBeginTimeEt);
                break;

            case R.id.declare_info_search_btn:
                declareInfoPb.setVisibility(View.VISIBLE);
                getEditText();
                xml = getXml(begainTime);
                Map<String, String> params = new HashMap<>();
                params.put("awbXml", xml);
                params.put("ErrString", "");
                HttpRoot.getInstance().requstAync(DomExportDayCarrierActivity.this, HttpCommons.CGO_GET_DOM_EXPORT_DAY_REPORT_NAME,
                        HttpCommons.CGO_GET_DOM_EXPORT_DAY_REPORT_ACTION, params,
                        new HttpRoot.CallBack() {
                            @Override
                            public void onSucess(Object result) {
                                SoapObject object = (SoapObject) result;
                                String xmls = object.getProperty(0).toString();
//                                Toast.makeText(IntExportDayCarrierActivity.this, xml, Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(DomExportDayCarrierActivity.this, DomExportDayCarrierDetailActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putString("intexportdaydetailxml", xmls);
                                intent.putExtras(bundle);
                                intent.putExtra("xml", xml);
                                startActivity(intent);
                                declareInfoPb.setVisibility(View.GONE);
                            }

                            @Override
                            public void onFailed(String message) {
                                declareInfoPb.setVisibility(View.GONE);
                            }

                            @Override
                            public void onError() {
                                declareInfoPb.setVisibility(View.GONE);
                            }
                        });
                break;

            default:
                break;
        }
    }

    private void getEditText() {
        begainTime = declareInfoBeginTimeEt.getText().toString().trim();
    }

    private String getXml(String begainTime) {
        return "<GNCCarrierReport>"
                + "<StartDay>" + begainTime + "</StartDay>"
                + "</GNCCarrierReport>";
    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  @author GS <sgazeos@gmail.com>
//

#include <ops/declarable/helpers/legacy_helpers.h>
#include <NDArrayFactory.h>
#include <ops/ops.h>

namespace nd4j {
namespace ops {
namespace helpers {
    template <typename T>
    static void reluDerivative__(NDArray* theFirst, NDArray* theSecond) {
        auto functor = LAMBDA_TT(x, y){
            return x > (T) 0.f ? y : T(0.f);
        };

        theFirst->applyPairwiseLambda<T>(*theSecond, functor, *theFirst);
    }

    void reluDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), reluDerivative__, (theFirst, theSecond), FLOAT_TYPES);
    }

    template <typename T>
    static void reluDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {

        T zero = (T) 0.f;
        auto functor = LAMBDA_TT(x, y, zero){
            return x > zero ? y : zero;
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);

        /*
        auto x =  input->bufferAsT<T>();
        auto y =  epsilon->bufferAsT<T>();
        auto z =  output->bufferAsT<T>();

        int length = input->lengthOf();

        T zero = (T) 0.f;

        PRAGMA_OMP_PARALLEL_FOR
        for (int e = 0; e < length; e++) {
            z[e] = x[e] > zero ? y[e] : zero;
        }
        */
    }

    void reluDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), reluDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    template <typename T>
    static void relu6Derivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            return x > (T)0.f && x < (T)6.f? y : T(0.f);
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void relu6Derivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), relu6Derivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    template <typename T>
    static void leakyReluDerivative_(NDArray* input, NDArray* epsilon, NDArray* output, const float alpha) {

        const T alphaT = static_cast<T>(alpha);

        auto functor = LAMBDA_TT(x, y, alphaT) {
            return x < 0 ? alphaT * y : y;
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void leakyReluDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput, const float alpha) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), leakyReluDerivative_, (theFirst, theSecond, theOutput, alpha), FLOAT_TYPES);
    }

    template <typename T>
    static void eluDerivative_(NDArray* input, NDArray* epsilon, NDArray* output, const float alpha) {

        const T alphaT = static_cast<T>(alpha);

        auto functor = LAMBDA_TT(x, y, alphaT){
            return y * nd4j::math::nd4j_eluderivative<T,T>(x, alphaT);
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void eluDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput, const float alpha) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), eluDerivative_, (theFirst, theSecond, theOutput, alpha), FLOAT_TYPES);
    }

    template <typename T>
    static void seluDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            return y * simdOps::SELUDerivative<T>::op(x, nullptr);
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void seluDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), seluDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    template <typename T>
    static void cubeDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            return y * (3 * x * x);
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void cubeDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), cubeDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    //return (x >= X(0.f) ? y: -y);
    template <typename T>
    static void reduceNorm1_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            return x > T(0.f)? y : -y;
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void reduceNorm1(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), reduceNorm1_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    ////////////////////////////////////////////////////////////////////////
    template <typename T>
    static void sigmCrossEntropy_(NDArray* logits, NDArray* labels, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            return nd4j::math::nd4j_max<T>(x, (T)0.f) - x * y + nd4j::math::nd4j_log<T,T>((T)1.f + nd4j::math::nd4j_exp<T,T>(-nd4j::math::nd4j_abs(x)));
        };

        logits->applyPairwiseLambda<T>(*labels, functor, *output);
    }

    void sigmCrossEntropy(nd4j::LaunchContext * context, NDArray* logits, NDArray* labels, NDArray* output) {
        BUILD_SINGLE_SELECTOR(logits->dataType(), sigmCrossEntropy_, (logits, labels, output), FLOAT_TYPES);
    }

    ////////////////////////////////////////////////////////////////////////
    template <typename T>
    static void sigmCrossEntropyGrad_(NDArray* logits, NDArray* labels, NDArray* output) {
        // 1 - labels - 1 / (1 + exp(logits))
        auto functor = LAMBDA_TT(x, y) {
            if(x <= 0)
                return static_cast<T>(1.) - y - static_cast<T>(1.) / (static_cast<T>(1.) + nd4j::math::nd4j_exp<T,T>(x));
            auto e = nd4j::math::nd4j_exp<T,T>(-x);
            return static_cast<T>(1.) - y - e / (static_cast<T>(1.) + e);
        };

        logits->applyPairwiseLambda<T>(*labels, functor, *output);
    }

    void sigmCrossEntropyGrad(nd4j::LaunchContext * context, NDArray* logits, NDArray* labels, NDArray* output) {
        BUILD_SINGLE_SELECTOR(logits->dataType(), sigmCrossEntropyGrad_, (logits, labels, output), FLOAT_TYPES);
    }

    ////////////////////////////////////////////////////////////////////////
    template <typename T>
    static void tanhDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            T th = nd4j::math::nd4j_tanh<T,T>(x);
            return y * ((T)1.0f - (th * th));
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void tanhDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), tanhDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    // return static_cast<X>(d2) * simdOps::HardTanhDerivative<X>::op(d1, nullptr);
    template <typename T>
    static void hardTanhDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            T th = nd4j::math::nd4j_tanh<T,T>(x);
            return y * simdOps::HardTanhDerivative<T>::op(x, nullptr);
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void hardTanhDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), hardTanhDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    template <typename T>
    static void rationalTanhDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            return y * simdOps::RationalTanhDerivative<T>::op(x, nullptr);
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void rationalTanhDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), rationalTanhDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    template <typename T>
    static void rectifiedTanhDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            return x > (T) 0.0f ? y * (nd4j::math::nd4j_tanhderivative<T,T>(x)) : (T) 0.0f;
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void rectifiedTanhDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), rectifiedTanhDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    //            X f = (X) 1.0f + nd4j::math::nd4j_abs<X>(d1);
    //            return (X) d2 * ((X) 1.0f / (f * f));

    template <typename T>
    static void softSignDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            T ss = (T)1.f + nd4j::math::nd4j_abs<T>(x);
            return y * ((T) 1.0f  / (ss * ss));
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void softSignDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), softSignDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    template <typename T>
    static void softPlusDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            T p = nd4j::math::nd4j_pow<T, T, T>(static_cast<T>(M_E), x);
            return y * (p / (p + 1.));
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void softPlusDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), softPlusDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }
///
/// \param theFirst
/// \param theSecond
/// \param theOutput
    template <typename T>
    static void sigmoidDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            T s = nd4j::math::nd4j_sigmoid<T,T>(x);
            return y * (s * ((T) 1.0f - s));
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void sigmoidDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), sigmoidDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    template <typename T>
    static void hardSigmoidDerivative_(NDArray* input, NDArray* epsilon, NDArray* output) {
        auto functor = LAMBDA_TT(x, y){
            return y * simdOps::HardSigmoidDerivative<T>::op(x, nullptr);
        };

        input->applyPairwiseLambda<T>(*epsilon, functor, *output);
    }

    void hardSigmoidDerivative(nd4j::LaunchContext * context, NDArray* theFirst, NDArray* theSecond, NDArray* theOutput) {
        BUILD_SINGLE_SELECTOR(theFirst->dataType(), hardSigmoidDerivative_, (theFirst, theSecond, theOutput), FLOAT_TYPES);
    }

    template <typename T>
    static void logSumExp_(NDArray* input, NDArray* axis, NDArray* output) {
        // reduce along axis with
        NDArray tempInput = input->dup();
        input->applyTransform(transform::Exp, tempInput);
        std::vector<int> axisVector;
        if (axis != nullptr) {
            axisVector.resize(axis->lengthOf());
            for (size_t i = 0; i < axisVector.size(); ++i)
                axisVector[i] = axis->e<int>(i);
        }
        tempInput.reduceAlongDimension(reduce::Sum, *output, axisVector);
        output->applyTransform(transform::Log, *output);
    }

    template <typename T>
    static void logSumExp_(NDArray* input, NDArray* subtrah, NDArray* axis, NDArray* output) {
        // reduce along axis with
        NDArray tempInput = input->dup();
        input->applyPairwiseTransform(pairwise::Subtract, *subtrah, tempInput);
        tempInput.applyTransform(transform::Exp, tempInput);

        std::vector<int> axisVector;
        if (axis != nullptr) {
            axisVector.resize(axis->lengthOf());
            for (size_t i = 0; i < axisVector.size(); ++i)
                axisVector[i] = axis->e<int>(i);
        }
        tempInput.reduceAlongDimension(reduce::Sum, *output, axisVector);
        output->applyTransform(transform::Log, *output);
    }

    void logSumExp(nd4j::LaunchContext * context, NDArray* input, NDArray* axis, NDArray* output) {
        BUILD_SINGLE_SELECTOR(input->dataType(), logSumExp_, (input, axis, output), FLOAT_TYPES);
    }

    void logSumExp(nd4j::LaunchContext * context, NDArray* input, NDArray* subtrah, NDArray* axis, NDArray* output) {
        BUILD_SINGLE_SELECTOR(input->dataType(), logSumExp_, (input, subtrah, axis, output), FLOAT_TYPES);
    }

//////////////////////////////////////////////////////////////////////////
template <typename T>
static void weightedCrossEntropyWithLogitsFunctor_(NDArray const* targets, NDArray const* input, NDArray const* weights, NDArray* output) {

    T posWeight = weights->e<T>(0);

    auto mainRoutineT1 = LAMBDA_TT(_x, _z, posWeight) {
        T targetWeight = (1. + (posWeight - (T)1.f) * _z);
        return (1. - _z) * _x +
               targetWeight * (nd4j::math::nd4j_log<T,T>((T)1.f + nd4j::math::nd4j_exp<T,T>(-nd4j::math::nd4j_abs(_x))) +
                               nd4j::math::nd4j_max(-_x, T(0.f))
               );
    };

    auto mainRoutineT2 = LAMBDA_TTT(_x, _z, _w) {
        return (((T)1.0 - _z) * _x) +
               _w * (nd4j::math::nd4j_log<T,T>(T(1.) + nd4j::math::nd4j_exp<T,T>(-nd4j::math::nd4j_abs(_x))) +
                     nd4j::math::nd4j_max(-_x, T(0.f)));
    };

    if (weights->isScalar()) {
        const_cast<NDArray*>(input)->applyPairwiseLambda<T>(const_cast<NDArray&>(*targets), mainRoutineT1, *output);
    }
    else
    {
        std::unique_ptr<NDArray> targetVector(new NDArray(*weights));
        targetVector->applyScalar(scalar::Add, -1.f, *targetVector);

        std::unique_ptr<NDArray> targetTensor(new NDArray(*targets));
        *targetTensor = (*targetVector * *targetTensor) + T(1.f);
        const_cast<NDArray*>(input)->applyTriplewiseLambda<T>(const_cast<NDArray&>(*targets), *targetTensor.get(), mainRoutineT2, *output);
    }
}

void weightedCrossEntropyWithLogitsFunctor(nd4j::LaunchContext * context, NDArray const* targets, NDArray const* input, NDArray const* weights, NDArray* output) {
    BUILD_SINGLE_SELECTOR(targets->dataType(), weightedCrossEntropyWithLogitsFunctor_, (targets, input, weights, output), FLOAT_TYPES);
}

}
}
}


text:
<?php

class Twitter extends Service {

    private $url;
    private $count = 0;

    function __construct($url, $config) {
	parent::__construct($config);
	$this->url = $url;
    }

    public function getName() {
	return "twitter";
    }

    public function fetchCount() {
	$serviceCall = 'https://cdn.api.twitter.com/1/urls/count.json?url=' . urlencode($this->url);
	$result = $this->getContent($serviceCall);
	$json = json_decode($result, true);

	$this->log($json);

	$this->count = $json['count'];
    }

    public function getCount() {
	return $this->count;
    }

}


text:
group_id ? "sub-component" : "component" }}">
    @if($component->link)
    link }}" target="_blank" class="links">{{ $component->name }}
    @else
    {{ $component->name }}
    @endif

    @if($component->description)
    description }}">
    @endif

        status }} {{ $component->status_color }}">{{ $component->humanStatus }}


text:
package bucket

import (
	"errors"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestSplit(t *testing.T) {
	for _, test := range []struct {
		in         string
		wantBucket string
		wantPath   string
	}{
		{in: "", wantBucket: "", wantPath: ""},
		{in: "bucket", wantBucket: "bucket", wantPath: ""},
		{in: "bucket/path", wantBucket: "bucket", wantPath: "path"},
		{in: "bucket/path/subdir", wantBucket: "bucket", wantPath: "path/subdir"},
	} {
		gotBucket, gotPath := Split(test.in)
		assert.Equal(t, test.wantBucket, gotBucket, test.in)
		assert.Equal(t, test.wantPath, gotPath, test.in)
	}
}

func TestCache(t *testing.T) {
	c := NewCache()
	errBoom := errors.New("boom")

	assert.Equal(t, 0, len(c.status))

	// IsDeleted before creation
	assert.False(t, c.IsDeleted("bucket"))

	// MarkOK

	c.MarkOK("")
	assert.Equal(t, 0, len(c.status))

	// MarkOK again

	c.MarkOK("bucket")
	assert.Equal(t, map[string]bool{"bucket": true}, c.status)

	// MarkDeleted

	c.MarkDeleted("bucket")
	assert.Equal(t, map[string]bool{"bucket": false}, c.status)

	// MarkOK again

	c.MarkOK("bucket")
	assert.Equal(t, map[string]bool{"bucket": true}, c.status)

	// IsDeleted after creation
	assert.False(t, c.IsDeleted("bucket"))

	// Create from root

	err := c.Create("", nil, nil)
	assert.NoError(t, err)
	assert.Equal(t, map[string]bool{"bucket": true}, c.status)

	// Create bucket that is already OK

	err = c.Create("bucket", nil, nil)
	assert.NoError(t, err)
	assert.Equal(t, map[string]bool{"bucket": true}, c.status)

	// Create new bucket

	err = c.Create("bucket2", func() error {
		return nil
	}, func() (bool, error) {
		return true, nil
	})
	assert.NoError(t, err)
	assert.Equal(t, map[string]bool{"bucket": true, "bucket2": true}, c.status)

	// Create bucket that has been deleted with error

	c.status["bucket2"] = false // mark bucket deleted
	err = c.Create("bucket2", nil, func() (bool, error) {
		return false, errBoom
	})
	assert.Equal(t, errBoom, err)
	assert.Equal(t, map[string]bool{"bucket": true, "bucket2": false}, c.status)

	// Create bucket that has been deleted with no error

	err = c.Create("bucket2", nil, func() (bool, error) {
		return true, nil
	})
	assert.NoError(t, err)
	assert.Equal(t, map[string]bool{"bucket": true, "bucket2": true}, c.status)

	// Create a new bucket with no exists function

	err = c.Create("bucket3", func() error {
		return nil
	}, nil)
	assert.NoError(t, err)
	assert.Equal(t, map[string]bool{"bucket": true, "bucket2": true, "bucket3": true}, c.status)

	// Create a new bucket with no exists function with an error

	err = c.Create("bucket4", func() error {
		return errBoom
	}, nil)
	assert.Equal(t, errBoom, err)
	assert.Equal(t, map[string]bool{"bucket": true, "bucket2": true, "bucket3": true}, c.status)

	// Remove root

	err = c.Remove("", func() error {
		return nil
	})
	assert.NoError(t, err)
	assert.Equal(t, map[string]bool{"bucket": true, "bucket2": true, "bucket3": true}, c.status)

	// Remove existing bucket

	err = c.Remove("bucket3", func() error {
		return nil
	})
	assert.NoError(t, err)
	assert.Equal(t, map[string]bool{"bucket": true, "bucket2": true, "bucket3": false}, c.status)

	// IsDeleted after removal
	assert.True(t, c.IsDeleted("bucket3"))

	// Remove it again

	err = c.Remove("bucket3", func() error {
		return errBoom
	})
	assert.Equal(t, ErrAlreadyDeleted, err)
	assert.Equal(t, map[string]bool{"bucket": true, "bucket2": true, "bucket3": false}, c.status)

	// Remove bucket with error

	err = c.Remove("bucket2", func() error {
		return errBoom
	})
	assert.Equal(t, errBoom, err)
	assert.Equal(t, map[string]bool{"bucket": true, "bucket2": true, "bucket3": false}, c.status)
}


text:
package org.isisaddons.wicket.wizard.fixture.scripts;

import org.isisaddons.wicket.wizard.fixture.scripts.todo.ToDoItemsRecreateAndCompleteSeveral;
import org.apache.isis.applib.fixturescripts.FixtureScript;

public class WizardWicketAppSetUpFixture extends FixtureScript {

    public WizardWicketAppSetUpFixture() {
        withDiscoverability(Discoverability.DISCOVERABLE);
    }

    @Override
    protected void execute(ExecutionContext executionContext) {
        execute(new ToDoItemsRecreateAndCompleteSeveral(null), executionContext);
    }

}


text:
"""View classes."""

from __future__ import unicode_literals

import abc

try:
  import win32console
except ImportError:
  win32console = None

class BaseTableView(object):
  """Table view interface."""

  def __init__(self, column_names=None, title=None):
    """Initializes a table view.

    Args:
      column_names (Optional[list[str]]): column names.
      title (Optional[str]): title.
    """
    super(BaseTableView, self).__init__()
    self._columns = column_names or []
    self._number_of_columns = len(self._columns)
    self._rows = []
    self._title = title

  def AddRow(self, values):
    """Adds a row of values.

    Args:
      values (list[object]): values.

    Raises:
      ValueError: if the number of values is out of bounds.
    """
    if self._number_of_columns and len(values) != self._number_of_columns:
      raise ValueError('Number of values is out of bounds.')

    self._rows.append(values)

    if not self._number_of_columns:
      self._number_of_columns = len(values)

  @abc.abstractmethod
  def Write(self, output_writer):
    """Writes the table to the output writer.

    Args:
      output_writer (OutputWriter): output writer.
    """

class CLITableView(BaseTableView):
  """Command line table view.

  Note that currently this table view does not support more than 2 columns.
  """

  # The maximum width of the table in number of characters.
  # The standard width of Windows cmd.exe is 80 characters.
  _MAXIMUM_WIDTH = 80

  _HEADER_FORMAT_STRING = '{{0:*^{0:d}}}\n'.format(_MAXIMUM_WIDTH)

  def __init__(self, column_names=None, title=None):
    """Initializes a command line table view.

    Args:
      column_names (Optional[list[str]]): column names.
      title (Optional[str]): title.
    """
    super(CLITableView, self).__init__(column_names=column_names, title=title)
    if self._columns:
      self._column_width = len(self._columns[0])
    else:
      self._column_width = 0

  def _WriteHeader(self, output_writer):
    """Writes a header.

    Args:
      output_writer (OutputWriter): output writer.
    """
    header_string = ''
    if self._title:
      header_string = ' {0:s} '.format(self._title)

    header_string = self._HEADER_FORMAT_STRING.format(header_string)
    output_writer.Write(header_string)

  def _WriteRow(self, output_writer, values):
    """Writes a row of values aligned to the column width.

    Args:
      output_writer (OutputWriter): output writer.
      values (list[object]): values.
    """
    maximum_row_width = self._MAXIMUM_WIDTH - self._column_width - 3

    # The format string of the first line of the column value.
    primary_format_string = '{{0:>{0:d}s}} : {{1:s}}\n'.format(
        self._column_width)

    # The format string of successive lines of the column value.
    secondary_format_string = '{{0:<{0:d}s}}{{1:s}}\n'.format(
        self._column_width + 3)

    if isinstance(values[1], str):
      value_string = values[1]
    else:
      value_string = '{0!s}'.format(values[1])

    if len(value_string) < maximum_row_width:
      output_writer.Write(primary_format_string.format(
          values[0], value_string))
      return

    # Split the column value in words.
    words = value_string.split()

    current = 0

    lines = []
    word_buffer = []
    for word in words:
      current += len(word) + 1
      if current >= maximum_row_width:
        current = len(word)
        lines.append(' '.join(word_buffer))
        word_buffer = [word]
      else:
        word_buffer.append(word)
    lines.append(' '.join(word_buffer))

    # Split the column value across multiple lines.
    output_writer.Write(
        primary_format_string.format(values[0], lines[0]))
    for line in lines[1:]:
      output_writer.Write(secondary_format_string.format('', line))

  def _WriteSeparatorLine(self, output_writer):
    """Writes a separator line.

    Args:
      output_writer (OutputWriter): output writer.
    """
    output_writer.Write('-' * self._MAXIMUM_WIDTH)
    output_writer.Write('\n')

  def AddRow(self, values):
    """Adds a row of values.

    Args:
      values (list[object]): values.

    Raises:
      ValueError: if the number of values is out of bounds.
    """
    super(CLITableView, self).AddRow(values)

    value_length = len(values[0])
    if value_length > self._column_width:
      self._column_width = value_length

  def Write(self, output_writer):
    """Writes the table to the output writer.

    Args:
      output_writer (OutputWriter): output writer.

    Raises:
      RuntimeError: if the title exceeds the maximum width or
          if the table has more than 2 columns or
          if the column width is out of bounds.
    """
    if self._title and len(self._title) > self._MAXIMUM_WIDTH:
      raise RuntimeError('Title length out of bounds.')

    if self._number_of_columns not in (0, 2):
      raise RuntimeError('Unsupported number of columns: {0:d}.'.format(
          self._number_of_columns))

    if self._column_width < 0 or self._column_width >= self._MAXIMUM_WIDTH:
      raise RuntimeError('Column width out of bounds.')

    output_writer.Write('\n')

    self._WriteHeader(output_writer)

    if self._columns:
      self._WriteRow(output_writer, self._columns)
      self._WriteSeparatorLine(output_writer)

    for values in self._rows:
      self._WriteRow(output_writer, values)

    self._WriteSeparatorLine(output_writer)

class CLITabularTableView(BaseTableView):
  """Command line tabular table view interface."""

  _NUMBER_OF_SPACES_IN_TAB = 8

  def __init__(self, column_names=None, column_sizes=None, title=None):
    """Initializes a command line table view.

    Args:
      column_names (Optional[list[str]]): column names.
      column_sizes (Optional[list[int]]): minimum column sizes, in number of
          characters. If a column name or row value is larger than the
          minimum column size the column will be enlarged. Note that the
          minimum columns size will be rounded up to the number of spaces
          of the next tab.
      title (Optional[str]): title.
    """
    super(CLITabularTableView, self).__init__(
        column_names=column_names, title=title)
    self._column_sizes = column_sizes or []

  def _WriteRow(self, output_writer, values, in_bold=False):
    """Writes a row of values aligned to the column width.

    Args:
      output_writer (OutputWriter): output writer.
      values (list[object]): values.
      in_bold (Optional[bool]): True if the row should be written in bold.
    """
    row_strings = []
    if self._column_sizes:
      for value_index, value_string in enumerate(values):
        padding_size = self._column_sizes[value_index] - len(value_string)
        padding_string = ' ' * padding_size

        row_strings.extend([value_string, padding_string])

      row_strings.pop()

    row_strings = ''.join(row_strings)

    if in_bold and not win32console:
      # TODO: for win32console get current color and set intensity,
      # write the header separately then reset intensity.
      row_strings = '\x1b[1m{0:s}\x1b[0m'.format(row_strings)

    row_strings = '{0:s}\n'.format(row_strings)
    output_writer.Write(row_strings)

  def AddRow(self, values):
    """Adds a row of values.

    Args:
      values (list[object]): values.

    Raises:
      ValueError: if the number of values is out of bounds.
    """
    if self._number_of_columns and len(values) != self._number_of_columns:
      raise ValueError('Number of values is out of bounds.')

    if not self._column_sizes and self._columns:
      self._column_sizes = [len(column) for column in self._columns]

    value_strings = []
    for value_index, value_string in enumerate(values):
      if not isinstance(value_string, str):
        value_string = '{0!s}'.format(value_string)
      value_strings.append(value_string)

      self._column_sizes[value_index] = max(
          self._column_sizes[value_index], len(value_string))

    self._rows.append(value_strings)

    if not self._number_of_columns:
      self._number_of_columns = len(value_strings)

  def Write(self, output_writer):
    """Writes the table to the output writer.

    Args:
      output_writer (OutputWriter): output writer.
    """
    # Round up the column sizes to the nearest tab.
    for column_index, column_size in enumerate(self._column_sizes):
      column_size, _ = divmod(column_size, self._NUMBER_OF_SPACES_IN_TAB)
      column_size = (column_size + 1) * self._NUMBER_OF_SPACES_IN_TAB
      self._column_sizes[column_index] = column_size

    # TODO: write title.

    if self._columns:
      self._WriteRow(output_writer, self._columns, in_bold=True)

    for values in self._rows:
      self._WriteRow(output_writer, values)

class MarkdownTableView(BaseTableView):
  """Markdown table view."""

  def Write(self, output_writer):
    """Writes the table to the output writer.

    Args:
      output_writer (OutputWriter): output writer.
    """
    if self._title:
      output_writer.Write('### {0:s}\n\n'.format(self._title))

    if not self._columns:
      self._columns = ['' for _ in range(0, self._number_of_columns)]

    output_writer.Write(' | '.join(self._columns))
    output_writer.Write('\n')

    output_writer.Write(' | '.join(['---' for _ in self._columns]))
    output_writer.Write('\n')

    for values in self._rows:
      values = ['{0!s}'.format(value) for value in values]
      output_writer.Write(' | '.join(values))
      output_writer.Write('\n')

    output_writer.Write('\n')

class ViewsFactory(object):
  """Views factory."""

  FORMAT_TYPE_CLI = 'cli'
  FORMAT_TYPE_MARKDOWN = 'markdown'

  _TABLE_VIEW_FORMAT_CLASSES = {
      FORMAT_TYPE_CLI: CLITableView,
      FORMAT_TYPE_MARKDOWN: MarkdownTableView
  }

  @classmethod
  def GetTableView(cls, format_type, column_names=None, title=None):
    """Retrieves a table view.

    Args:
      format_type (str): table view format type.
      column_names (Optional[list[str]]): column names.
      title (Optional[str]): title.

    Returns:
      BaseTableView: table view.

    Raises:
      ValueError: if the format type is not supported.
    """
    view_class = cls._TABLE_VIEW_FORMAT_CLASSES.get(format_type, None)
    if not view_class:
      raise ValueError('Unsupported format type: {0:s}'.format(format_type))

    return view_class(column_names=column_names, title=title)


text:
package com.azavea.keras.config

object ProcessConf {
  case class Options(
    layerName: String = "keras-raw",
    catalogPath: String = "keras-ingest",
    discriminator: String = "entire",
    zoom: Int = 0,
    tiffSize: Int = 256,
    amount: Int = 5000,
    randomization: Boolean = true,
    zscore: Boolean = true,
    path: String = "/tmp",
    bands: Option[String] = None,
    withS3upload: Boolean = false,
    backend: String = "hadoop",
    withGzip: Boolean = false
  ) {
    def isHadoop = backend == "hadoop"
    def isS3 = backend == "s3"
    def isFile = backend == "file"
  }

  val help = """
               |geotrellis-keras-generators
               |
               |Usage: geotrellis-keras-generators [options]
               |
               |  --layerName <value>
               |        layerName is a non-empty String option [default: keras-raw]
               |  --catalogPath <value>
               |        catalogPath is a non-empty String option [default: /data/keras-ingest]
               |  --discriminator <value>
               |        discriminator is a non-empty String option [default: entire] [options: training, validation, test, entire]
               |  --zoom <value>
               |        zoom is a non-empty Int option [default: 0]
               |  --tiffSize <value>
               |        tiffSize is a non-empty Int option [default: 256]
               |  --amount <value>
               |        amount is a non-empty Int option [default: 5000]
               |  --randomization <value>
               |        randomization is a non-empty Boolean option [default: true]
               |  --zscore <value>
               |        zscore is a non-empty Boolean option [default: true]
               |  --path <value>
               |        path is a a String option [default: /tmp]
               |  --bands <value>
               |        bands is a String option
               |  --withS3upload <value>
               |        withS3upload is a non-empty Boolean option [default: false]
               |  --withGzip <value>
               |        withGzip is a non-empty Boolean option [default: false]
               |  --backend <value>
               |        backend is a non-empty String option [default: hadoop] [options: file, hadoop, s3]
               |  --help
               |        prints this usage text
             """.stripMargin

  def nextOption(opts: Options, list: Seq[String]): Options = {
    list.toList match {
      case Nil => opts
      case "--layerName" :: value :: tail =>
        nextOption(opts.copy(layerName = value), tail)
      case "--catalogPath" :: value :: tail =>
        nextOption(opts.copy(catalogPath = value), tail)
      case "--discriminator" :: value :: tail => value match {
        case "training" | "validation" | "test" | "entire" => nextOption (opts.copy (discriminator = value), tail)
        case _ => {
          println(s"Unknown value ${value} for option discriminator")
          println(help)
          sys.exit(1)
        }
      }
      case "--zoom" :: value :: tail =>
        nextOption(opts.copy(zoom = value.toInt), tail)
      case "--tiffSize" :: value :: tail =>
        nextOption(opts.copy(tiffSize = value.toInt), tail)
      case "--amount" :: value :: tail =>
        nextOption(opts.copy(amount = value.toInt), tail)
      case "--randomization" :: value :: tail =>
        nextOption(opts.copy(randomization = value.toBoolean), tail)
      case "--zscore" :: value :: tail =>
        nextOption(opts.copy(zscore = value.toBoolean), tail)
      case "--path" :: value :: tail =>
        nextOption(opts.copy(path = value), tail)
      case "--bands" :: value :: tail =>
        nextOption(opts.copy(bands = Some(value)), tail)
      case "--withS3upload" :: value :: tail =>
        nextOption(opts.copy(withS3upload = value.toBoolean), tail)
      case "--withGzip" :: value :: tail =>
        nextOption(opts.copy(withGzip = value.toBoolean), tail)
      case "--backend" :: value :: tail => value match {
        case "file" | "hadoop" | "s3" => nextOption (opts.copy (backend = value), tail)
        case _ => {
          println(s"Unknown value ${value} for option discriminator")
          println(help)
          sys.exit(1)
        }
      }
      case "--help" :: tail => {
        println(help)
        sys.exit(1)
      }
      case option :: tail => {
        println(s"Unknown option ${option}")
        println(help)
        sys.exit(1)
      }
    }
  }

  def parse(args: Seq[String]) = nextOption(Options(), args)

  def apply(args: Seq[String]): Options = parse(args)
}


text:
'use strict';

import Boom from 'boom';
import Joi from 'joi';
import Converter from '../converters/xml';
import _ from 'lodash';

export default {
  path: '/v1/convert/xml',
  method: 'POST',
  config: {
    description: 'Convert XML to JSON',
    tags: ['api', 'v1'],

    payload: {
      parse: false,
      allow: ['application/xml', 'text/xml'],
      defaultContentType: 'application/xml'
    }
  },
  handler: {
    async: async (request, reply) => {
      try {
        const xml = request.payload.toString();
        const result = Converter.convert(xml);
        return reply(result);
      } catch (e) {
        return reply(e);
      }
    }
  }
}


text:
package org.epnoi.learner.terms;

import java.util.HashMap;
import java.util.Map;

public class ResourceMetadata implements Comparable<ResourceMetadata> {

	private Map<String, Long> termsOcurrences;
	private long numberOfTerms;

	// ---------------------------------------------------------------------------------------------------------

	public ResourceMetadata() {
		this.numberOfTerms = 0;
		this.termsOcurrences = new HashMap<String, Long>();

	}

	// ---------------------------------------------------------------------------------------------------------

	@Override
	public int compareTo(ResourceMetadata o) {
		// TODO Auto-generated method stub
		return 0;
	}

	// ---------------------------------------------------------------------------------------------------------

	public Map<String, Long> getTermsOcurrences() {
		return termsOcurrences;
	}

	// ---------------------------------------------------------------------------------------------------------

	public void setTermsOcurrences(Map<String, Long> termsOcurrences) {
		this.termsOcurrences = termsOcurrences;
	}

	// ---------------------------------------------------------------------------------------------------------

	public long getNumberOfTerms() {
		return numberOfTerms;
	}

	// ---------------------------------------------------------------------------------------------------------

	public void setNumberOfTerms(long numberOfTerms) {
		this.numberOfTerms = numberOfTerms;
	}

	// ---------------------------------------------------------------------------------------------------------

	@Override
	public String toString() {
		return "ResourceMetadata [termsOcurrences=" + termsOcurrences
				+ ", numberOfTerms=" + numberOfTerms + "]";
	}

}


text:
/*
 * 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 org.apache.tez.dag.app.launcher;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.tez.common.TezUtils;
import org.apache.tez.dag.api.NamedEntityDescriptor;
import org.apache.tez.dag.api.TezConstants;
import org.apache.tez.dag.api.TezException;
import org.apache.tez.dag.api.TezReflectionException;
import org.apache.tez.dag.api.UserPayload;
import org.apache.tez.dag.app.AppContext;
import org.apache.tez.dag.app.TaskCommunicatorManagerInterface;
import org.apache.tez.dag.app.rm.ContainerLauncherLaunchRequestEvent;
import org.apache.tez.serviceplugins.api.ContainerLaunchRequest;
import org.apache.tez.serviceplugins.api.ContainerLauncher;
import org.apache.tez.serviceplugins.api.ContainerLauncherContext;
import org.apache.tez.serviceplugins.api.ContainerStopRequest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

public class TestContainerLauncherManager {

  @Before
  @After
  public void reset() {
    ContainerLaucherRouterForMultipleLauncherTest.reset();
  }

  @Test(timeout = 5000)
  public void testNoLaunchersSpecified() throws IOException, TezException {

    AppContext appContext = mock(AppContext.class);
    TaskCommunicatorManagerInterface tal = mock(TaskCommunicatorManagerInterface.class);

    try {

      new ContainerLaucherRouterForMultipleLauncherTest(appContext, tal, null, null,
          false);
      fail("Expecting a failure without any launchers being specified");
    } catch (IllegalArgumentException e) {

    }
  }

  @Test(timeout = 5000)
  public void testCustomLauncherSpecified() throws IOException, TezException {
    Configuration conf = new Configuration(false);

    AppContext appContext = mock(AppContext.class);
    TaskCommunicatorManagerInterface tal = mock(TaskCommunicatorManagerInterface.class);

    String customLauncherName = "customLauncher";
    List<NamedEntityDescriptor> launcherDescriptors = new LinkedList<>();
    ByteBuffer bb = ByteBuffer.allocate(4);
    bb.putInt(0, 3);
    UserPayload customPayload = UserPayload.create(bb);
    launcherDescriptors.add(
        new NamedEntityDescriptor(customLauncherName, FakeContainerLauncher.class.getName())
            .setUserPayload(customPayload));

    ContainerLaucherRouterForMultipleLauncherTest clr =
        new ContainerLaucherRouterForMultipleLauncherTest(appContext, tal, null,
            launcherDescriptors,
            true);
    try {
      clr.init(conf);
      clr.start();

      assertEquals(1, clr.getNumContainerLaunchers());
      assertFalse(clr.getYarnContainerLauncherCreated());
      assertFalse(clr.getUberContainerLauncherCreated());
      assertEquals(customLauncherName, clr.getContainerLauncherName(0));
      assertEquals(bb, clr.getContainerLauncherContext(0).getInitialUserPayload().getPayload());
    } finally {
      clr.stop();
    }
  }

  @Test(timeout = 5000)
  public void testMultipleContainerLaunchers() throws IOException, TezException {
    Configuration conf = new Configuration(false);
    conf.set("testkey", "testvalue");
    UserPayload userPayload = TezUtils.createUserPayloadFromConf(conf);

    AppContext appContext = mock(AppContext.class);
    TaskCommunicatorManagerInterface tal = mock(TaskCommunicatorManagerInterface.class);

    String customLauncherName = "customLauncher";
    List<NamedEntityDescriptor> launcherDescriptors = new LinkedList<>();
    ByteBuffer bb = ByteBuffer.allocate(4);
    bb.putInt(0, 3);
    UserPayload customPayload = UserPayload.create(bb);
    launcherDescriptors.add(
        new NamedEntityDescriptor(customLauncherName, FakeContainerLauncher.class.getName())
            .setUserPayload(customPayload));
    launcherDescriptors
        .add(new NamedEntityDescriptor(TezConstants.getTezYarnServicePluginName(), null)
            .setUserPayload(userPayload));

    ContainerLaucherRouterForMultipleLauncherTest clr =
        new ContainerLaucherRouterForMultipleLauncherTest(appContext, tal, null,
            launcherDescriptors,
            true);
    try {
      clr.init(conf);
      clr.start();

      assertEquals(2, clr.getNumContainerLaunchers());
      assertTrue(clr.getYarnContainerLauncherCreated());
      assertFalse(clr.getUberContainerLauncherCreated());
      assertEquals(customLauncherName, clr.getContainerLauncherName(0));
      assertEquals(bb, clr.getContainerLauncherContext(0).getInitialUserPayload().getPayload());

      assertEquals(TezConstants.getTezYarnServicePluginName(), clr.getContainerLauncherName(1));
      Configuration confParsed = TezUtils
          .createConfFromUserPayload(clr.getContainerLauncherContext(1).getInitialUserPayload());
      assertEquals("testvalue", confParsed.get("testkey"));
    } finally {
      clr.stop();
    }
  }

  @Test(timeout = 5000)
  public void testEventRouting() throws Exception {
    Configuration conf = new Configuration(false);
    UserPayload userPayload = TezUtils.createUserPayloadFromConf(conf);

    AppContext appContext = mock(AppContext.class);
    TaskCommunicatorManagerInterface tal = mock(TaskCommunicatorManagerInterface.class);

    String customLauncherName = "customLauncher";
    List<NamedEntityDescriptor> launcherDescriptors = new LinkedList<>();
    ByteBuffer bb = ByteBuffer.allocate(4);
    bb.putInt(0, 3);
    UserPayload customPayload = UserPayload.create(bb);
    launcherDescriptors.add(
        new NamedEntityDescriptor(customLauncherName, FakeContainerLauncher.class.getName())
            .setUserPayload(customPayload));
    launcherDescriptors
        .add(new NamedEntityDescriptor(TezConstants.getTezYarnServicePluginName(), null)
            .setUserPayload(userPayload));

    ContainerLaucherRouterForMultipleLauncherTest clr =
        new ContainerLaucherRouterForMultipleLauncherTest(appContext, tal, null,
            launcherDescriptors,
            true);
    try {
      clr.init(conf);
      clr.start();

      assertEquals(2, clr.getNumContainerLaunchers());
      assertTrue(clr.getYarnContainerLauncherCreated());
      assertFalse(clr.getUberContainerLauncherCreated());
      assertEquals(customLauncherName, clr.getContainerLauncherName(0));
      assertEquals(TezConstants.getTezYarnServicePluginName(), clr.getContainerLauncherName(1));

      verify(clr.getTestContainerLauncher(0)).initialize();
      verify(clr.getTestContainerLauncher(0)).start();
      verify(clr.getTestContainerLauncher(1)).initialize();
      verify(clr.getTestContainerLauncher(1)).start();

      ContainerLaunchContext clc1 = mock(ContainerLaunchContext.class);
      Container container1 = mock(Container.class);

      ContainerLaunchContext clc2 = mock(ContainerLaunchContext.class);
      Container container2 = mock(Container.class);

      ContainerLauncherLaunchRequestEvent launchRequestEvent1 =
          new ContainerLauncherLaunchRequestEvent(clc1, container1, 0, 0, 0);
      ContainerLauncherLaunchRequestEvent launchRequestEvent2 =
          new ContainerLauncherLaunchRequestEvent(clc2, container2, 1, 0, 0);

      clr.handle(launchRequestEvent1);

      ArgumentCaptor<ContainerLaunchRequest> captor =
          ArgumentCaptor.forClass(ContainerLaunchRequest.class);
      verify(clr.getTestContainerLauncher(0)).launchContainer(captor.capture());
      assertEquals(1, captor.getAllValues().size());
      ContainerLaunchRequest launchRequest1 = captor.getValue();
      assertEquals(clc1, launchRequest1.getContainerLaunchContext());

      clr.handle(launchRequestEvent2);
      captor = ArgumentCaptor.forClass(ContainerLaunchRequest.class);
      verify(clr.getTestContainerLauncher(1)).launchContainer(captor.capture());
      assertEquals(1, captor.getAllValues().size());
      ContainerLaunchRequest launchRequest2 = captor.getValue();
      assertEquals(clc2, launchRequest2.getContainerLaunchContext());

    } finally {
      clr.stop();
      verify(clr.getTestContainerLauncher(0)).shutdown();
      verify(clr.getTestContainerLauncher(1)).shutdown();
    }
  }

  private static class ContainerLaucherRouterForMultipleLauncherTest
      extends ContainerLauncherManager {

    // All variables setup as static since methods being overridden are invoked by the ContainerLauncherRouter ctor,
    // and regular variables will not be initialized at this point.
    private static final AtomicInteger numContainerLaunchers = new AtomicInteger(0);
    private static final Set<Integer> containerLauncherIndices = new HashSet<>();
    private static final ContainerLauncher yarnContainerLauncher = mock(ContainerLauncher.class);
    private static final ContainerLauncher uberContainerlauncher = mock(ContainerLauncher.class);
    private static final AtomicBoolean yarnContainerLauncherCreated = new AtomicBoolean(false);
    private static final AtomicBoolean uberContainerLauncherCreated = new AtomicBoolean(false);

    private static final List<ContainerLauncherContext> containerLauncherContexts =
        new LinkedList<>();
    private static final List<String> containerLauncherNames = new LinkedList<>();
    private static final List<ContainerLauncher> testContainerLaunchers = new LinkedList<>();

    public static void reset() {
      numContainerLaunchers.set(0);
      containerLauncherIndices.clear();
      yarnContainerLauncherCreated.set(false);
      uberContainerLauncherCreated.set(false);
      containerLauncherContexts.clear();
      containerLauncherNames.clear();
      testContainerLaunchers.clear();
    }

    public ContainerLaucherRouterForMultipleLauncherTest(AppContext context,
                                                         TaskCommunicatorManagerInterface taskCommunicatorManagerInterface,
                                                         String workingDirectory,
                                                         List<NamedEntityDescriptor> containerLauncherDescriptors,
                                                         boolean isPureLocalMode) throws
        UnknownHostException, TezException {
      super(context, taskCommunicatorManagerInterface, workingDirectory,
          containerLauncherDescriptors, isPureLocalMode);
    }

    @Override
    ContainerLauncher createContainerLauncher(NamedEntityDescriptor containerLauncherDescriptor,
                                              AppContext context,
                                              ContainerLauncherContext containerLauncherContext,
                                              TaskCommunicatorManagerInterface taskCommunicatorManagerInterface,
                                              String workingDirectory,
                                              int containerLauncherIndex,
                                              boolean isPureLocalMode) throws TezException {
      numContainerLaunchers.incrementAndGet();
      boolean added = containerLauncherIndices.add(containerLauncherIndex);
      assertTrue("Cannot add multiple launchers with the same index", added);
      containerLauncherNames.add(containerLauncherDescriptor.getEntityName());
      containerLauncherContexts.add(containerLauncherContext);
      return super
          .createContainerLauncher(containerLauncherDescriptor, context, containerLauncherContext,
              taskCommunicatorManagerInterface, workingDirectory, containerLauncherIndex, isPureLocalMode);
    }

    @Override
    ContainerLauncher createYarnContainerLauncher(
        ContainerLauncherContext containerLauncherContext) {
      yarnContainerLauncherCreated.set(true);
      testContainerLaunchers.add(yarnContainerLauncher);
      return yarnContainerLauncher;
    }

    @Override
    ContainerLauncher createUberContainerLauncher(ContainerLauncherContext containerLauncherContext,
                                                  AppContext context,
                                                  TaskCommunicatorManagerInterface taskCommunicatorManagerInterface,
                                                  String workingDirectory,
                                                  boolean isPureLocalMode) {
      uberContainerLauncherCreated.set(true);
      testContainerLaunchers.add(uberContainerlauncher);
      return uberContainerlauncher;
    }

    @Override
    ContainerLauncher createCustomContainerLauncher(
        ContainerLauncherContext containerLauncherContext,
        NamedEntityDescriptor containerLauncherDescriptor) throws TezException {
      ContainerLauncher spyLauncher = spy(super.createCustomContainerLauncher(
          containerLauncherContext, containerLauncherDescriptor));
      testContainerLaunchers.add(spyLauncher);
      return spyLauncher;
    }

    public int getNumContainerLaunchers() {
      return numContainerLaunchers.get();
    }

    public boolean getYarnContainerLauncherCreated() {
      return yarnContainerLauncherCreated.get();
    }

    public boolean getUberContainerLauncherCreated() {
      return uberContainerLauncherCreated.get();
    }

    public String getContainerLauncherName(int containerLauncherIndex) {
      return containerLauncherNames.get(containerLauncherIndex);
    }

    public ContainerLauncher getTestContainerLauncher(int containerLauncherIndex) {
      return testContainerLaunchers.get(containerLauncherIndex);
    }

    public ContainerLauncherContext getContainerLauncherContext(int containerLauncherIndex) {
      return containerLauncherContexts.get(containerLauncherIndex);
    }
  }

  public static class FakeContainerLauncher extends ContainerLauncher {

    public FakeContainerLauncher(
        ContainerLauncherContext containerLauncherContext) {
      super(containerLauncherContext);
    }

    @Override
    public void launchContainer(ContainerLaunchRequest launchRequest) {

    }

    @Override
    public void stopContainer(ContainerStopRequest stopRequest) {

    }
  }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.garygregory.jcommander.converters.sql (jcommander-addons 1.0.0-SNAPSHOT Test API)</title>
<meta name="date" content="2016-11-10">
<meta name="keywords" content="com.garygregory.jcommander.converters.sql package">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

com.garygregory.jcommander.converters.sql

Classes

AllTypesConverterTest

ConnectionConverterTest

DateConverterTest

DriverConverterTest

TimeConverterTest

TimestampConverterTest

TypesConverterTest