text:
package v1alpha1

import (
	"context"
	"testing"

	"gotest.tools/v3/assert"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"knative.dev/pkg/apis"
)

func Test_ValidateTektonConfig_OnDelete(t *testing.T) {

	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "name",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{
			CommonSpec: CommonSpec{
				TargetNamespace: "namespace",
			},
			Profile: "all",
		},
	}

	err := tc.Validate(apis.WithinDelete(context.Background()))
	if err != nil {
		t.Errorf("ValidateTektonConfig.Validate() on Delete expected no error, but got one, ValidateTektonConfig: %v", err)
	}
}

func Test_ValidateTektonConfig_MissingTargetNamespace(t *testing.T) {

	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "config",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{},
	}

	err := tc.Validate(context.TODO())
	assert.Equal(t, "missing field(s): spec.targetNamespace", err.Error())
}

func Test_ValidateTektonConfig_InvalidProfile(t *testing.T) {

	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "config",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{
			CommonSpec: CommonSpec{
				TargetNamespace: "namespace",
			},
			Profile: "test",
		},
	}

	err := tc.Validate(context.TODO())
	assert.Equal(t, "invalid value: test: spec.profile", err.Error())
}

func Test_ValidateTektonConfig_InvalidPruningResource(t *testing.T) {

	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "config",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{
			CommonSpec: CommonSpec{
				TargetNamespace: "namespace",
			},
			Profile: "all",
			Pruner: Prune{
				Resources: []string{"task"},
				Schedule:  "",
			},
		},
	}

	err := tc.Validate(context.TODO())
	assert.Equal(t, "expected exactly one, got neither: spec.pruner.keep, spec.pruner.keep-since\ninvalid value: task: spec.pruner.resources[0]\nmissing field(s): spec.pruner.schedule", err.Error())
}

func Test_ValidateTektonConfig_MissingKeepKeepsinceSchedule(t *testing.T) {

	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "config",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{
			CommonSpec: CommonSpec{
				TargetNamespace: "namespace",
			},
			Profile: "all",
			Pruner: Prune{
				Resources: []string{"taskrun"},
			},
		},
	}

	err := tc.Validate(context.TODO())
	assert.Equal(t, "expected exactly one, got neither: spec.pruner.keep, spec.pruner.keep-since\nmissing field(s): spec.pruner.schedule", err.Error())
}

func Test_ValidateTektonConfig_MissingSchedule(t *testing.T) {
	keep := uint(2)
	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "config",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{
			CommonSpec: CommonSpec{
				TargetNamespace: "namespace",
			},
			Profile: "all",
			Pruner: Prune{
				Keep:      &keep,
				Resources: []string{"taskrun"},
			},
		},
	}

	err := tc.Validate(context.TODO())
	assert.Equal(t, "missing field(s): spec.pruner.schedule", err.Error())
}

func Test_ValidateTektonConfig_InvalidAddonParam(t *testing.T) {

	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "config",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{
			CommonSpec: CommonSpec{
				TargetNamespace: "namespace",
			},
			Profile: "all",
			Addon: Addon{
				Params: []Param{
					{
						Name:  "invalid-param",
						Value: "val",
					},
				},
			},
		},
	}

	err := tc.Validate(context.TODO())
	assert.Equal(t, "invalid key name \"invalid-param\": spec.addon.params", err.Error())
}

func Test_ValidateTektonConfig_InvalidAddonParamValue(t *testing.T) {

	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "config",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{
			CommonSpec: CommonSpec{
				TargetNamespace: "namespace",
			},
			Profile: "all",
			Addon: Addon{
				Params: []Param{
					{
						Name:  "clusterTasks",
						Value: "test",
					},
				},
			},
		},
	}

	err := tc.Validate(context.TODO())
	assert.Equal(t, "invalid value: test: spec.addon.params.clusterTasks[0]", err.Error())
}

func Test_ValidateTektonConfig_InvalidPipelineProperties(t *testing.T) {

	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "config",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{
			CommonSpec: CommonSpec{
				TargetNamespace: "namespace",
			},
			Profile: "all",
			Pipeline: Pipeline{
				PipelineProperties: PipelineProperties{
					EnableApiFields: "test",
				},
			},
		},
	}

	err := tc.Validate(context.TODO())
	assert.Equal(t, "invalid value: test: spec.pipeline.enable-api-fields", err.Error())
}

func Test_ValidateTektonConfig_InvalidTriggerProperties(t *testing.T) {

	tc := &TektonConfig{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "config",
			Namespace: "namespace",
		},
		Spec: TektonConfigSpec{
			CommonSpec: CommonSpec{
				TargetNamespace: "namespace",
			},
			Profile: "all",
			Trigger: Trigger{
				TriggersProperties: TriggersProperties{
					EnableApiFields: "test",
				},
			},
		},
	}

	err := tc.Validate(context.TODO())
	assert.Equal(t, "invalid value: test: spec.trigger.enable-api-fields", err.Error())
}


text:
package org.hillview.benchmarks;

import com.google.gson.*;
import org.hillview.dataStructures.*;
import org.hillview.dataset.LocalDataSet;
import org.hillview.dataset.api.Empty;
import org.hillview.dataset.api.IDataSet;
import org.hillview.dataset.api.IMap;
import org.hillview.dataset.api.TableSketch;
import org.hillview.sketches.Histogram2DSketch;
import org.hillview.sketches.results.*;
import org.hillview.targets.TableRpcTarget;
import org.hillview.main.Benchmarks;
import org.hillview.maps.FindFilesMap;
import org.hillview.maps.LoadFilesMap;
import org.hillview.security.SecureLaplace;
import org.hillview.security.TestKeyLoader;
import org.hillview.sketches.SummarySketch;
import org.hillview.storage.FileSetDescription;
import org.hillview.storage.IFileReference;
import org.hillview.table.ColumnDescription;
import org.hillview.table.PrivacySchema;
import org.hillview.table.Schema;
import org.hillview.table.api.ContentsKind;
import org.hillview.table.api.ITable;
import org.hillview.table.columns.ColumnQuantization;

import org.hillview.table.columns.DoubleColumnQuantization;

import org.hillview.table.columns.StringColumnQuantization;
import org.hillview.utils.*;
import org.junit.Assert;

import javax.annotation.Nullable;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;

public class DPAccuracyBenchmarks extends Benchmarks {
    private final static String ontime_directory = "../data/ontime_private/";
    private final static String privacy_metadata_name = "privacy_metadata.json";
    private static final String histogram_results_filename = "../results/ontime_private_histogram.json";
    private static final String heatmap_results_filename = "../results/ontime_private_heatmap.json";

    final String resultsFilename;

    private DPAccuracyBenchmarks(String resultsFilename) {
        this.resultsFilename = resultsFilename;
    }

    @Nullable
    IDataSet<ITable> loadData() {
        try {
            FileSetDescription fsd = new FileSetDescription();
            fsd.fileNamePattern = "../data/ontime_private/????_*.csv*";
            fsd.fileKind = "csv";
            fsd.schemaFile = "short.schema";

            Empty e = Empty.getInstance();
            LocalDataSet<Empty> local = new LocalDataSet<Empty>(e);
            IMap<Empty, List<IFileReference>> finder = new FindFilesMap<>(fsd);
            IDataSet<IFileReference> found = local.blockingFlatMap(finder);
            IMap<IFileReference, ITable> loader = new LoadFilesMap();
            return found.blockingMap(loader);
        }  catch (Exception ex) {
            // This can happen if the data files have not been generated
            return null;
        }
    }

    Schema loadSchema(IDataSet<ITable> data) {
        SummarySketch sk = new SummarySketch();
        TableSummary tableSummary = data.blockingSketch(sk);
        assert tableSummary != null;
        if (tableSummary.rowCount == 0)
            throw new RuntimeException("No file data loaded");
        return Converters.checkNull(tableSummary.schema);
    }

    /**
     * Compute the absolute and L2 error vs. ground truth for an instantiation of a private histogram
     * averaged over all possible range queries.
     *
     * @param ph The histogram whose accuracy we want to compute.
     * @param decomposition The leaf specification for the histogram.
     * @return The average per-query absolute error.
     */
    private double computeAccuracy(DPHistogram<IGroup<Count>> ph, IntervalDecomposition decomposition, SecureLaplace laplace) {
        double scale = PrivacyUtils.computeNoiseScale(ph.getEpsilon(), decomposition);
        double baseVariance = PrivacyUtils.laplaceVariance(scale);
        // Do all-intervals accuracy on leaves.
        int n = 0;
        double sqtot = 0.0;
        double abstot = 0.0;
        Noise noise = new Noise();
        int bucketCount = decomposition.getBucketCount();
        for (int left = 0; left < bucketCount; left++) {
            for (int right = left; right < bucketCount; right++) {
                ph.noiseForRange(left, right, scale, baseVariance, laplace, noise);
                sqtot += Math.pow(noise.getNoise(), 2);
                abstot += Math.abs(noise.getNoise());
                n++;
            }
        }

        System.out.println("Bucket count: " + bucketCount);
        System.out.println("Num intervals: " + n);
        System.out.println("Average absolute error: " + abstot / (double) n);
        System.out.println("Average L2 error: " + Math.sqrt(sqtot) / (double) n);

        return abstot / (double) n;
    }

    /**
     * Compute the absolute and L2 error vs. ground truth for an instantiation of a private heat map
     * averaged over all possible range queries (every rectangle).
     *
     * @param ph The heat map whose accuracy we want to compute.
     * @param xd The leaf specification for the x-axis.
     * @param yd The leaf specification for the y-axis.
     * @return The average per-query absolute error.
     */
    private Double computeAccuracy(DPHeatmapSketch<IGroup<Count>, IGroup<IGroup<Count>>> ph,
                                   IntervalDecomposition xd, IntervalDecomposition yd) {
        double scale = PrivacyUtils.computeNoiseScale(ph.getEpsilon(), xd, yd);
        double baseVariance = PrivacyUtils.laplaceVariance(scale);

        // Do all-intervals accuracy on leaves.
        int n = 0;
        double sqtot = 0.0;
        double abstot = 0.0;
        Noise noise = new Noise();
        int xBucketCount = xd.getBucketCount();
        int yBucketCount = yd.getBucketCount();
        for (int left = 0; left < xBucketCount; left++) {
            for (int right = left; right < xBucketCount; right++) {
                for (int top = 0; top < yBucketCount; top++) {
                    for (int bot = top; bot < yBucketCount; bot++) {
                        ph.noiseForRange(left, right, top, bot,
                                scale, baseVariance, noise);
                        sqtot += Math.pow(noise.getNoise(), 2);
                        abstot += Math.abs(noise.getNoise());
                        n++;
                    }
                }
            }
        }

        System.out.println("Bucket count: " + xBucketCount * yBucketCount);
        System.out.println("Num intervals: " + n);
        System.out.println("Average absolute error: " + abstot / (double) n);
        System.out.println("Average L2 error: " + Math.sqrt(sqtot) / (double) n);

        return abstot / (double) n;
    }

    private TableRpcTarget.HistogramRequestInfo
    createHistogramRequest(String col, ColumnQuantization cq) {
        // Construct a histogram corresponding to the leaves.
        // We will manually aggregate buckets as needed for the accuracy test.
        TableRpcTarget.HistogramInfo info;
        if (cq instanceof DoubleColumnQuantization) {
            DoubleColumnQuantization dq = (DoubleColumnQuantization)cq;
            info = new TableRpcTarget.HistogramInfo(
                    new ColumnDescription(col, ContentsKind.Double),
                    dq.globalMin, dq.globalMax, dq.getIntervalCount());
        } else {
            // StringColumnQuantization
            StringColumnQuantization sq = (StringColumnQuantization)cq;
            info = new TableRpcTarget.HistogramInfo(
                    new ColumnDescription(col, ContentsKind.String), sq.leftBoundaries, sq.globalMax);
        }

        TableRpcTarget.HistogramRequestInfo result = new TableRpcTarget.HistogramRequestInfo();
        result.histos = new TableRpcTarget.HistogramInfo[] { info };
        return result;
    }

    private Pair<Double, Double> computeSingleColumnAccuracy(
            String col, int colIndex,
            ColumnQuantization cq, double epsilon, IDataSet<ITable> table,
            int iterations) {
        // Construct a histogram corresponding to the leaves.
        // We will manually aggregate buckets as needed for the accuracy test.
        TableRpcTarget.HistogramRequestInfo info = createHistogramRequest(col, cq);
        TableSketch<Groups<Count>> sk = info.getSketch(0, cq);
        IntervalDecomposition dd = info.getDecomposition(0, cq);

        System.out.println("Epsilon: " + epsilon);
        Groups<Count> hist = table.blockingSketch(sk); // Leaf counts.
        Assert.assertNotNull(hist);

        TestKeyLoader tkl = new TestKeyLoader();
        ArrayList<Double> accuracies = new ArrayList<>();
        double totAccuracy = 0.0;
        for (int i = 0 ; i < iterations; i++) {
            tkl.setIndex(i);
            SecureLaplace laplace = new SecureLaplace(tkl);
            @SuppressWarnings("ConstantConditions")
            DPHistogram<IGroup<Count>> ph = new DPHistogram<>(null, colIndex, dd, epsilon, false, laplace);
            double acc = computeAccuracy(ph, dd, laplace);
            accuracies.add(acc);
            totAccuracy += acc;
        }
        return new Pair<Double, Double>(totAccuracy / iterations, Utilities.stdev(accuracies));
    }

    private Pair<Double, Double> computeHeatmapAccuracy(String col1, ColumnQuantization cq1,
                                                        String col2, ColumnQuantization cq2,
                                                        int columnsIndex,
                                                        double epsilon, IDataSet<ITable> table,
                                                        int iterations) {
        // Construct a histogram corresponding to the leaves.
        // We will manually aggregate buckets as needed for the accuracy test.
        TableRpcTarget.HistogramRequestInfo info0 = createHistogramRequest(col1, cq1);
        TableRpcTarget.HistogramRequestInfo info1 = createHistogramRequest(col2, cq2);

        Histogram2DSketch sk = new Histogram2DSketch(
                info0.getBuckets(0), info1.getBuckets(0));
        IntervalDecomposition d0 = info0.getDecomposition(0, cq1);
        IntervalDecomposition d1 = info1.getDecomposition(0, cq2);

        System.out.println("Epsilon: " + epsilon);
        Groups<Groups<Count>> heatmap = table.blockingSketch(sk); // Leaf counts.
        Assert.assertNotNull(heatmap);

        TestKeyLoader tkl = new TestKeyLoader();
        ArrayList<Double> accuracies = new ArrayList<>();
        double totAccuracy = 0.0;
        for (int i = 0 ; i < iterations; i++) {
            tkl.setIndex(i);
            SecureLaplace laplace = new SecureLaplace(tkl);
            @SuppressWarnings("ConstantConditions")
            DPHeatmapSketch<IGroup<Count>, IGroup<IGroup<Count>>> ph =
                    new DPHeatmapSketch<>(null, columnsIndex, d0, d1, epsilon, laplace);
            double acc = computeAccuracy(ph, d0, d1);
            accuracies.add(acc);
            totAccuracy += acc;
        }
        return new Pair<Double, Double>(totAccuracy / iterations, Utilities.stdev(accuracies));
    }

    public void benchmarkHistogramL2Accuracy() throws IOException {
        HillviewLogger.instance.setLogLevel(Level.OFF);
        @Nullable
        IDataSet<ITable> table = this.loadData();
        if (table == null) {
            System.out.println("Skipping test: no data");
            return;
        }

        Schema schema = this.loadSchema(table);
        List<String> cols = schema.getColumnNames();

        PrivacySchema mdSchema = PrivacySchema.loadFromFile(ontime_directory + privacy_metadata_name);
        Assert.assertNotNull(mdSchema);
        Assert.assertNotNull(mdSchema.quantization);

        HashMap<String, ArrayList<Double>> results = new HashMap<String, ArrayList<Double>>();
        int iterations = 5;
        for (String col : cols) {
            ColumnQuantization quantization = mdSchema.quantization.get(col);
            Assert.assertNotNull(quantization);

            double epsilon = mdSchema.epsilon(col);

            Pair<Double, Double> res = this.computeSingleColumnAccuracy(col, mdSchema.getColumnIndex(col), quantization, epsilon, table, iterations);
            System.out.println("Averaged absolute error over " + iterations + " iterations: " + res.first);

            // for JSON parsing convenience
            ArrayList<Double> resArr = new ArrayList<Double>();
            resArr.add(res.first); // noise
            resArr.add(res.second); // stdev

            results.put(col, resArr);
        }

        FileWriter writer = new FileWriter(histogram_results_filename);
        Gson resultsGson = new GsonBuilder().create();
        writer.write(resultsGson.toJson(results));
        writer.flush();
        writer.close();
    }

    public void benchmarkHeatmapL2Accuracy() throws IOException {
        HillviewLogger.instance.setLogLevel(Level.OFF);
        @Nullable
        IDataSet<ITable> table = this.loadData();
        if (table == null) {
            System.out.println("Skipping test: no data");
            return;
        }

        Schema schema = this.loadSchema(table);
        List<String> cols = schema.getColumnNames();

        PrivacySchema mdSchema = PrivacySchema.loadFromFile(ontime_directory + privacy_metadata_name);
        Assert.assertNotNull(mdSchema);
        Assert.assertNotNull(mdSchema.quantization);

        HashMap<String, ArrayList<Double>> results = new HashMap<String, ArrayList<Double>>();
        int iterations = 5;
        for (String col1 : cols) {
            for (String col2 : cols) {
                if (col1.equals(col2)) continue;

                ColumnQuantization q1 = mdSchema.quantization.get(col1);
                Assert.assertNotNull(q1);
                ColumnQuantization q2 = mdSchema.quantization.get(col2);
                Assert.assertNotNull(q2);

                String key = mdSchema.getKeyForColumns(col1, col2);
                double epsilon = mdSchema.epsilon(key);

                Pair<Double, Double> res = this.computeHeatmapAccuracy(col1, q1, col2, q2, mdSchema.getColumnIndex(col1, col2),
                        epsilon, table, iterations);
                System.out.println("Averaged absolute error over " + iterations + " iterations: " + res.first);

                // for JSON parsing convenience
                ArrayList<Double> resArr = new ArrayList<Double>();
                resArr.add(res.first); // noise
                resArr.add(res.second); // stdev

                System.out.println("Key: " + key + ", mean: " + res.first);
                results.put(key, resArr);
            }
        }

        FileWriter writer = new FileWriter(heatmap_results_filename);
        Gson resultsGson = new GsonBuilder().create();
        writer.write(resultsGson.toJson(results));
        writer.flush();
        writer.close();
    }

    public static void main(String[] args) throws IOException {
        if (args.length < 1) {
            return;
        }

        String resultsFilename = args[0];
        DPAccuracyBenchmarks bench = new DPAccuracyBenchmarks(resultsFilename);
        bench.benchmarkHeatmapL2Accuracy();
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Security.Cryptography;
using System.Text;

namespace ExactTarget.DataExtensions.Core
{
    public class ExternalKeyGenerator
    {
        public static string GenerateExternalKey(string value)
        {
            var md5 = MD5.Create();
            var bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(value));
            return new Guid(bytes).ToString();
        }
    }
}


text:
package org.apache.shardingsphere.transaction.spi;

import org.apache.shardingsphere.infra.config.schema.SchemaConfiguration;
import org.apache.shardingsphere.infra.instance.InstanceContext;
import org.apache.shardingsphere.spi.typed.TypedSPI;
import org.apache.shardingsphere.transaction.rule.TransactionRule;

import java.util.Properties;

/**
 * Transaction configuration file generator.
 */
public interface TransactionConfigurationFileGenerator extends TypedSPI {

    /**
     * Generate transaction configuration file.
     *
     * @param transactionRule transaction rule
     * @param instanceContext instance context
     */
    void generateFile(TransactionRule transactionRule, InstanceContext instanceContext);

    /**
     * Get transaction rule props.
     *
     * @param originTransactionProps origin transaction properties
     * @param schemaConfiguration schema configuration
     * @param modeType mode type
     * @return transaction rule props
     */
    Properties getTransactionProps(Properties originTransactionProps, SchemaConfiguration schemaConfiguration, String modeType);
}


text:
BaseRenderer::BaseRenderer(void)
{
	mContext = 0;
}

BaseRenderer::~BaseRenderer(void)
{
}


text:
var util = require('../util');
/*
    Digraph = require('graphlib').Digraph,
    topsort = require('graphlib').alg.topsort,
    nodesFromList = require('graphlib').filter.nodesFromList;
*/

module.exports = sortLayer;

/*
function sortLayer(g, cg, weights) {
  var result = sortLayerSubgraph(g, null, cg, weights);
  result.list.forEach(function(u, i) {
    g.node(u).order = i;
  });
  return result.constraintGraph;
}
*/

function sortLayer(g, cg, weights) {
  var ordering = [];
  var bs = {};
  g.eachNode(function(u, value) {
    ordering[value.order] = u;
    var ws = weights[u];
    if (ws.length) {
      bs[u] = util.sum(ws) / ws.length;
    }
  });

  var toSort = g.nodes().filter(function(u) { return bs[u] !== undefined; });
  toSort.sort(function(x, y) {
    return bs[x] - bs[y] || g.node(x).order - g.node(y).order;
  });

  for (var i = 0, j = 0, jl = toSort.length; j < jl; ++i) {
    if (bs[ordering[i]] !== undefined) {
      g.node(toSort[j++]).order = i;
    }
  }
}

// TOOD: re-enable constrained sorting once we have a strategy for handling
// undefined barycenters.
/*
function sortLayerSubgraph(g, sg, cg, weights) {
  cg = cg ? cg.filterNodes(nodesFromList(g.children(sg))) : new Digraph();

  var nodeData = {};
  g.children(sg).forEach(function(u) {
    if (g.children(u).length) {
      nodeData[u] = sortLayerSubgraph(g, u, cg, weights);
      nodeData[u].firstSG = u;
      nodeData[u].lastSG = u;
    } else {
      var ws = weights[u];
      nodeData[u] = {
        degree: ws.length,
        barycenter: ws.length > 0 ? util.sum(ws) / ws.length : 0,
        list: [u]
      };
    }
  });

  resolveViolatedConstraints(g, cg, nodeData);

  var keys = Object.keys(nodeData);
  keys.sort(function(x, y) {
    return nodeData[x].barycenter - nodeData[y].barycenter;
  });

  var result =  keys.map(function(u) { return nodeData[u]; })
                    .reduce(function(lhs, rhs) { return mergeNodeData(g, lhs, rhs); });
  return result;
}

/*
function mergeNodeData(g, lhs, rhs) {
  var cg = mergeDigraphs(lhs.constraintGraph, rhs.constraintGraph);

  if (lhs.lastSG !== undefined && rhs.firstSG !== undefined) {
    if (cg === undefined) {
      cg = new Digraph();
    }
    if (!cg.hasNode(lhs.lastSG)) { cg.addNode(lhs.lastSG); }
    cg.addNode(rhs.firstSG);
    cg.addEdge(null, lhs.lastSG, rhs.firstSG);
  }

  return {
    degree: lhs.degree + rhs.degree,
    barycenter: (lhs.barycenter * lhs.degree + rhs.barycenter * rhs.degree) /
                (lhs.degree + rhs.degree),
    list: lhs.list.concat(rhs.list),
    firstSG: lhs.firstSG !== undefined ? lhs.firstSG : rhs.firstSG,
    lastSG: rhs.lastSG !== undefined ? rhs.lastSG : lhs.lastSG,
    constraintGraph: cg
  };
}

function mergeDigraphs(lhs, rhs) {
  if (lhs === undefined) return rhs;
  if (rhs === undefined) return lhs;

  lhs = lhs.copy();
  rhs.nodes().forEach(function(u) { lhs.addNode(u); });
  rhs.edges().forEach(function(e, u, v) { lhs.addEdge(null, u, v); });
  return lhs;
}

function resolveViolatedConstraints(g, cg, nodeData) {
  // Removes nodes `u` and `v` from `cg` and makes any edges incident on them
  // incident on `w` instead.
  function collapseNodes(u, v, w) {
    // TODO original paper removes self loops, but it is not obvious when this would happen
    cg.inEdges(u).forEach(function(e) {
      cg.delEdge(e);
      cg.addEdge(null, cg.source(e), w);
    });

    cg.outEdges(v).forEach(function(e) {
      cg.delEdge(e);
      cg.addEdge(null, w, cg.target(e));
    });

    cg.delNode(u);
    cg.delNode(v);
  }

  var violated;
  while ((violated = findViolatedConstraint(cg, nodeData)) !== undefined) {
    var source = cg.source(violated),
        target = cg.target(violated);

    var v;
    while ((v = cg.addNode(null)) && g.hasNode(v)) {
      cg.delNode(v);
    }

    // Collapse barycenter and list
    nodeData[v] = mergeNodeData(g, nodeData[source], nodeData[target]);
    delete nodeData[source];
    delete nodeData[target];

    collapseNodes(source, target, v);
    if (cg.incidentEdges(v).length === 0) { cg.delNode(v); }
  }
}

function findViolatedConstraint(cg, nodeData) {
  var us = topsort(cg);
  for (var i = 0; i < us.length; ++i) {
    var u = us[i];
    var inEdges = cg.inEdges(u);
    for (var j = 0; j < inEdges.length; ++j) {
      var e = inEdges[j];
      if (nodeData[cg.source(e)].barycenter >= nodeData[u].barycenter) {
        return e;
      }
    }
  }
}
*/


text:
from __future__ import print_function, division, absolute_import

from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declared_attr

from app.libs.db import Base, db_session

class Model(Base):

    __abstract__ = True

    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    @declared_attr
    def id(cls):
        return Column('id', Integer(), primary_key=True, autoincrement=True)

    @classmethod
    def count(cls):
        return cls.query.count()

    @classmethod
    def get(cls, id_):
        return cls.query.filter(cls.id==id_).first()

    @classmethod
    def get_multi(cls, *ids):
        return [cls.get(id_) for id_ in ids]

    def delete(self):
        session = db_session.object_session(self)
        session.delete(self)
        session.commit()


text:
<!DOCTYPE html>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

{{obj.titulo}}

                            Campo
                            Valor

id	{{objEdit.id}}

                            curso

                                {{objEdit.obj_curso.titulo}}

descripcion	{{objEdit.descripcion}}

ponderacion	{{objEdit.ponderacion}}

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal" ng-click="remove('tipotarea', objEdit.id)">Delete</button>


text:
package org.hawkular.inventory.handlers;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.hawkular.inventory.Resources;
import org.hawkular.inventory.api.model.Inventory;
import org.hawkular.inventory.api.model.InventoryHealth;
import org.hawkular.inventory.api.model.Metric;
import org.hawkular.inventory.api.model.MetricUnit;
import org.hawkular.inventory.api.model.Operation;
import org.hawkular.inventory.api.model.RawResource;
import org.hawkular.inventory.api.model.ResourceType;
import org.hawkular.inventory.api.model.ResultSet;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.logging.Logger;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;

/**
 * @author Jay Shaughnessy
 * @author Lucas Ponce
 */
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(Performance.class)
public class InventoryPerfTest extends AbstractInventoryITest {
    private final Logger log = Logger.getLogger(InventoryPerfTest.class);

    public static Inventory createResourceTypes() {
        Map<String, Map<String, String>> reload;
        reload = new HashMap<>();
        reload.put("param1", new HashMap<>());
        reload.get("param1").put("type", "bool");
        reload.get("param1").put("description", "Description of param1 for Reload op");
        reload.put("param2", new HashMap<>());
        reload.get("param2").put("type", "bool");
        reload.get("param2").put("description", "Description of param2 for Reload op");

        Map<String, Map<String, String>> shutdown;
        shutdown = new HashMap<>();
        shutdown.put("param1", new HashMap<>());
        shutdown.get("param1").put("type", "bool");
        shutdown.get("param1").put("description", "Description of param1 for Shutdown op");
        shutdown.put("param2", new HashMap<>());
        shutdown.get("param2").put("type", "bool");
        shutdown.get("param2").put("description", "Description of param2 for Shutdown op");
        Collection<Operation> eapOps = Arrays.asList(
                new Operation("Reload", reload),
                new Operation("Shutdown", shutdown),
                new Operation("Start", Collections.emptyMap()));
        ResourceType eapType = new ResourceType("EAP", eapOps, new HashMap<>());

        Map<String, Map<String, String>> flush;
        flush = new HashMap<>();
        flush.put("param1", new HashMap<>());
        flush.get("param1").put("type", "bool");
        flush.get("param1").put("description", "Description of param1 for Flush op");
        flush.put("param2", new HashMap<>());
        flush.get("param2").put("type", "bool");
        flush.get("param2").put("description", "Description of param2 for Flush op");
        Collection<Operation> jdgOps = Arrays.asList(
                new Operation("Flush", flush),
                new Operation("Delete", Collections.emptyMap()));
        ResourceType jdgType = new ResourceType("JDG", jdgOps, new HashMap<>());

        List<ResourceType> resourceTypes = Arrays.asList(eapType, jdgType);

        return new Inventory(null, resourceTypes);
    }

    public static Inventory createLargeInventory(int from, int to, int children, int metrics) {
        List<RawResource> resources = new ArrayList<>();
        for (int i = from; i < to; i++) {
            String typeId = (i % 2 == 0) ? "EAP" : "JDG";
            String id = "Server-" + i;
            String name = "Server " + typeId + " with Id " + id;
            String feedX = "feedX";
            List<RawResource> childrenResource = new ArrayList<>();
            for (int j = 0; j < children; j++) {
                String childType = (j % 2 == 0) ? "FOO" : "BAR";
                String childIdX = id + "-child-" + j;
                String childNameX = "Child "+ j + " from " + id;
                RawResource childX = new RawResource(childIdX, childNameX, feedX, childType, id,
                        new ArrayList<>(), new HashMap<>(), new HashMap<>());

                childrenResource.add(childX);
            }

            List<Metric> metricsResource = new ArrayList<>();
            for (int k = 0; k < metrics; k++) {
                Metric metricX = new Metric("Metric " + k, "metric-" + k, MetricUnit.BYTES, null, new HashMap<>(),
                        new HashMap<>());
                metricsResource.add(metricX);
            }

            Map<String, String> propsX = new HashMap<>();
            propsX.put("description", "This is a description for " + id);
            RawResource serverX = new RawResource(id,
                    name,
                    feedX,
                    typeId,
                    null,
                    metricsResource,
                    propsX,
                    new HashMap<>());

            resources.add(serverX);
            resources.addAll(childrenResource);
        }

        return new Inventory(resources, null);
    }

    @Test
    @RunAsClient
    public void test000_statusIsUp() {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(baseUrl.toString()).path("status");
        Response response = target
                .request(MediaType.APPLICATION_JSON_TYPE)
                .get();
        assertEquals(200, response.getStatus());
    }

    @Test
    @RunAsClient
    public void test0001_clean() {
        WebTarget target = ClientBuilder.newClient().target(baseUrl.toString()).path("resources");
        Response response = target
                .request(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .delete();
        assertEquals(200, response.getStatus());

        target = ClientBuilder.newClient().target(baseUrl.toString()).path("types");
        response = target
                .request(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .delete();
        assertEquals(200, response.getStatus());
    }

    @Test
    @RunAsClient
    public void test001_importResources() {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(baseUrl.toString()).path("import");
        Response response = target
                .request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(Resources.INVENTORY, MediaType.APPLICATION_JSON_TYPE));
        assertEquals(200, response.getStatus());
    }

    @Test
    @RunAsClient
    public void test002_largeImportWithStats() {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(baseUrl.toString()).path("import");
        Response response = target
                .request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(createResourceTypes(), MediaType.APPLICATION_JSON_TYPE));
        assertEquals(200, response.getStatus());

        int maxIterations = 50;
        int maxServersPerIteration = 100;
        int childrenPerServer = 100;
        int metricsPerServer = 20;

        for (int i = 0; i < maxIterations; i++) {
            int from = i * maxServersPerIteration;
            int to = ((i + 1) * maxServersPerIteration) - 1;
            client = ClientBuilder.newClient();
            target = client.target(baseUrl.toString()).path("import");
            response = target
                    .request(MediaType.APPLICATION_JSON_TYPE)
                    .post(Entity.entity(createLargeInventory(from, to, childrenPerServer, metricsPerServer), MediaType.APPLICATION_JSON_TYPE));
            assertEquals(200, response.getStatus());
            int mod = maxIterations > 500 ? 100 : 10;
            if ( i % mod == 0) {
                log.infof("Creating [%s] Servers", (i * maxServersPerIteration));
            }
        }
        log.infof("Final - Created [%s] Servers", (maxIterations * maxServersPerIteration));

        log.infof("Fetch top resources");
        for (int i = 0; i < maxIterations; i++) {
            client = ClientBuilder.newClient();
            target = client.target(baseUrl.toString())
                    .path("resources")
                    .queryParam("root", true)
                    .queryParam("maxResults", maxServersPerIteration)
                    .queryParam("startOffset", i * maxServersPerIteration);
            response = target
                    .request(MediaType.APPLICATION_JSON_TYPE)
                    .accept(MediaType.APPLICATION_JSON_TYPE)
                    .get();
            assertEquals(200, response.getStatus());
            int mod = maxIterations > 500 ? 100 : 10;
            if ( i % mod == 0) {
                log.infof("Querying [%s] Servers", (i * maxServersPerIteration));
            }
        }

        log.info("Querying all types");
        client = ClientBuilder.newClient();
        target = client.target(baseUrl.toString()).path("types");
        response = target
                .request(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .get();
        assertEquals(200, response.getStatus());
        assertThat((List<ResourceType>) response.readEntity(ResultSet.class).getResults())
                .extracting(ResourceType::getId)
                .containsOnly("EAP", "FOO", "BAR", "JDG");

        client = ClientBuilder.newClient();
        target = client.target(baseUrl.toString()).path("health");
        response = target
                .request(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .get();
        InventoryHealth health = (InventoryHealth) response.readEntity(InventoryHealth.class);
        assertThat(health.getInventoryStats()).isNotNull();
        assertThat(health.getInventoryStats().getNumberOfResources() > 10000);
        assertThat(health.getInventoryStats().getNumberOfResourcesInMemory() ==  5000);
        assertThat(health.getDiskStats().getInventoryTotalSpace() > 4000000L);
    }

    @Test
    @RunAsClient
    public void test003_shouldGetResourceTypesAndNotImpactFromResources() {
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(baseUrl.toString()).path("types");
        Response response = target
                .request(MediaType.APPLICATION_JSON_TYPE)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .get();
        assertEquals(200, response.getStatus());
        assertThat((List<ResourceType>) response.readEntity(ResultSet.class).getResults())
                .extracting(ResourceType::getId)
                .containsOnly("EAP", "FOO", "BAR", "JDG");
    }
}


text:
package com.navercorp.pinpoint.web.mapper.stat.sampling.sampler;

import com.navercorp.pinpoint.common.server.bo.stat.ResponseTimeBo;
import com.navercorp.pinpoint.web.vo.chart.Point;
import com.navercorp.pinpoint.web.vo.chart.UncollectedPoint;
import com.navercorp.pinpoint.web.vo.stat.SampledResponseTime;
import com.navercorp.pinpoint.web.vo.stat.chart.DownSampler;
import com.navercorp.pinpoint.web.vo.stat.chart.DownSamplers;
import org.springframework.stereotype.Component;

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

/**
 * @author Taejin Koo
 */
@Component
public class ResponseTimeSampler implements AgentStatSampler<ResponseTimeBo, SampledResponseTime> {

    public static final DownSampler<Long> LONG_DOWN_SAMPLER = DownSamplers.getLongDownSampler(ResponseTimeBo.UNCOLLECTED_VALUE);

    @Override
    public SampledResponseTime sampleDataPoints(int timeWindowIndex, long timestamp, List<ResponseTimeBo> dataPoints, ResponseTimeBo previousDataPoint) {
        List<Long> avgs = new ArrayList<>(dataPoints.size());
        for (ResponseTimeBo responseTimeBo : dataPoints) {
            avgs.add(responseTimeBo.getAvg());
        }

        SampledResponseTime sampledResponseTime = new SampledResponseTime();
        sampledResponseTime.setAvg(createPoint(timestamp, avgs));
        return sampledResponseTime;
    }

    private Point<Long, Long> createPoint(long timestamp, List<Long> values) {
        if (values.isEmpty()) {
            return new UncollectedPoint<>(timestamp, ResponseTimeBo.UNCOLLECTED_VALUE);
        } else {
            return new Point<>(
                    timestamp,
                    LONG_DOWN_SAMPLER.sampleMin(values),
                    LONG_DOWN_SAMPLER.sampleMax(values),
                    LONG_DOWN_SAMPLER.sampleAvg(values),
                    LONG_DOWN_SAMPLER.sampleSum(values));
        }
    }

}


text:
/*
Problem 6. Calculate N! / K!

Write a program that calculates n! / k! for given n and k (1 < k < n < 100).
Use only one loop.
*/

using System;

class FactDivFact
{
    static void Main()
    {
        Console.Write("Enter n: ");
        int n = int.Parse(Console.ReadLine());
        Console.Write("Enter k: ");
        int k = int.Parse(Console.ReadLine());

        decimal result = 1;

        for (int i = k + 1; i <= n; i++)
        {
            result *= i;
        }
        Console.WriteLine(result);
    }
}


text:
package com.fishercoder;

import com.fishercoder.solutions._933;
import org.junit.BeforeClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class _933Test {
    private static _933.Solution1.RecentCounter solution1;

    @BeforeClass
    public static void setup() {
        solution1 = new _933.Solution1.RecentCounter();
    }

    @Test
    public void test1() {
        assertEquals(1, solution1.ping(1));
    }

}


text:
package com.jaamsim.StringProviders;

public class StringProvConstant implements StringProvider {

	private final String val;

	public StringProvConstant(String str) {
		val = str;
	}

	@Override
	public String getNextString(double simTime) {
		return val;
	}

	@Override
	public String getNextString(double simTime, double siFactor) {
		return val;
	}

	@Override
	public String getNextString(double simTime, double siFactor, boolean integerValue) {
		return val;
	}

	@Override
	public String getNextString(double simTime, String fmt, double siFactor) {
		return String.format(fmt, val);
	}

	@Override
	public double getNextValue(double simTime) {
		return Double.NaN;
	}

	@Override
	public String toString() {
		return val;
	}

}


text:
from abc import ABCMeta, abstractmethod

class Source:
    """
    Abstract class of any sources
    """
    __metaclass__ = ABCMeta

    @abstractmethod
    def __init__(self, config):
        """
        Initialized with config dictionary
        """

    @abstractmethod
    def get(self, date):
        """
        Get data source of sepecified date
        """

    @staticmethod
    def get(source_name, config):
        """
        Get instance of data source implementation
        """

        import util;
        return util.get_class(__name__, source_name, Source)(config)

class WebSource(Source):
    """
    Source by web scraping
    """

    def __init__(self, config):
        """
        Initialized with config dictionary

        config['url']: soruce URL

        config['verify']: verify SSL certs

        config['auth']: authentication
            auth['type']: authentication type (now, to be 'basic')
            auth['username']: username
            auth['password']: password
        """

        self.url = config.get('url')

        self.verify = config.get('verify', True)

        auth = config.get('auth')
        if auth:
            self.auth = {
                    'type': auth.get('type', 'basic'),
                    'username': auth.get('username'),
                    'password': auth.get('password'),
                    }
        else:
            self.auth = False

    def get_url(self, date):
        """
        Format URL with date
        """

        return date.strftime(self.url)

    def get(self, date):
        """
        Get data
        """
        from lxml import html
        from urllib2 import HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm, build_opener, urlopen

        if not self.verify:
            import ssl
            ssl._create_default_https_context = ssl._create_unverified_context

        url = self.get_url(date)
        if self.auth:
            password_mgr = HTTPPasswordMgrWithDefaultRealm()
            password_mgr.add_password(None, url, self.auth['username'], self.auth['password'])

            handler = HTTPBasicAuthHandler(password_mgr)
            opener = build_opener(handler)

            src = opener.open(url).read()
        else:
            src = urlopen(url).read()

        return html.fromstring(src)


text:
package org.decomisims.vistas;

import java.awt.Color;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.decomisims.app.Aplicacion;
import org.decomisims.modelo.Salarios;
import org.decomisims.util.Format;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author José Bernardo Gómez-Andrade
 */
public class ValorExentoOneroso extends javax.swing.JPanel {

    private static final long serialVersionUID = 1123581321L;
    private static final Logger log = LoggerFactory.getLogger(ValorExentoOneroso.class);
    private Salarios salarios;

    public ValorExentoOneroso() {
        initComponents();

        DocumentListener dl = new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                eval();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                eval();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                eval();
            }

            private void eval() {
                if (jtfValor.getText().isEmpty()) {
                    jtfValor.setBackground(Aplicacion.DEFAULT_COLOR);
                    jtfCobro.setText(null);
                    lblEstatus.setText(null);
                } else {
                    String str = jtfValor.getText();
                    try {
                        Double val = Double.parseDouble(str);
                        jtfValor.setBackground(Color.white);
                    } catch (NumberFormatException nfex) {
                        jtfValor.setBackground(Aplicacion.ERROR_COLOR);
                    }
                }
            }
        };
        jtfValor.getDocument().addDocumentListener(dl);

        DocumentListener dl2 = new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                eval();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                eval();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                eval();
            }

            private void eval() {
                String tmp = jtfCobro.getText();
                if (!tmp.isEmpty()) {
                    try {
                        Double val = Double.parseDouble(tmp);
                        if (val >= (0.20 * salarios.getSalarioDF())) {
                            lblEstatus.setText("Exento");
                        } else {
                            lblEstatus.setText("Integrado");
                        }
                        if (val > getValor()) {
                            jtfCobro.setBackground(Aplicacion.ERROR_COLOR);
                        } else {
                            jtfCobro.setBackground(Aplicacion.DEFAULT_COLOR);
                        }
                    } catch (NumberFormatException nfex) {
                        jtfCobro.setBackground(Aplicacion.ERROR_COLOR);
                    }
                } else {
                    lblEstatus.setText("Integrado");
                }
            }
        };
        jtfCobro.getDocument().addDocumentListener(dl2);

    }

    public void setSalarios(Salarios salarios) {
        this.salarios = salarios;
    }

    public Double getValor() {
       return Format.DECIMAL.parse(jtfValor.getText(), 0d);
    }

    public Double getCobroOneroso() {
        return Format.DECIMAL.parse(jtfCobro.getText(), 0d);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jtfValor = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jtfCobro = new javax.swing.JTextField();
        lblEstatus = new javax.swing.JLabel();

        jtfValor.setPreferredSize(new java.awt.Dimension(120, 26));

        jLabel1.setText("Cobro oneroso");
        jLabel1.setPreferredSize(new java.awt.Dimension(120, 26));

        jtfCobro.setPreferredSize(new java.awt.Dimension(120, 26));

        lblEstatus.setToolTipText("La alimentación y la habitación cuando se entreguen en forma onerosa a los trabajadores; se entiende que son onerosas estas prestaciones cuando el trabajador pague por cada una de ellas, como mínimo, el veinte por ciento del salario mínimo general diario que rija en el Distrito Federal");
        lblEstatus.setPreferredSize(new java.awt.Dimension(120, 26));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jtfValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfCobro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblEstatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jtfValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jtfCobro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(lblEstatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jtfCobro;
    private javax.swing.JTextField jtfValor;
    private javax.swing.JLabel lblEstatus;
    // End of variables declaration//GEN-END:variables
}


text:
'use strict';

const DigsValidator = require('./validator');
const define = require('../define');
const validator = require('../validator');

const DigsInitValidator = define({
  'static': {
    validateInitArgs(schema) {
      return DigsValidator.init(function init(context) {
        this.doValidate(this.initValidationArgs, context.args);
      })
        .compose(this)
        .refs({
          initValidationArgs: schema
        });
    },
    validateInitInstance(schema) {
      return DigsValidator.init(function init() {
        this.doValidate(this.initValidationInstance, this);
      })
        .compose(this)
        .refs({
          initValidationInstance: schema
        });
    },
    validator: validator
  }
});

module.exports = DigsInitValidator;


text:
namespace DAVA
{
namespace ValueSliderDetail
{
const QString editorQss =
"border: 1px solid black;\n"
"background: transparent;"
"padding: 0px;"
"margin: 0px;";
}

ValueSlider::ValueSlider(QWidget* parent)
    : QWidget(parent)
    , minVal(0)
    , maxVal(1)
    , val(0)
    , digitsAfterDot(6)
    , mouse(new MouseHelper(this))
    , clickVal(0)
{
    connect(mouse, SIGNAL(mousePress(const QPoint&)), SLOT(OnMousePress(const QPoint&)));
    connect(mouse, SIGNAL(mouseMove(const QPoint&)), SLOT(OnMouseMove(const QPoint&)));
    connect(mouse, SIGNAL(mouseRelease(const QPoint&)), SLOT(OnMouseRelease(const QPoint&)));
    connect(mouse, SIGNAL(clicked()), SLOT(OnMouseClick()));
}

void ValueSlider::SetDigitsAfterDot(int c)
{
    digitsAfterDot = c;
}

void ValueSlider::SetRange(double min, double max)
{
    minVal = qMin(min, max);
    maxVal = qMax(min, max);
    SetValue(val); // Validation
}

void ValueSlider::SetValue(double _val)
{
    val = _val;
    normalize();
    update();
}

double ValueSlider::GetValue() const
{
    return val;
}

double ValueSlider::GetMaxValue() const
{
    return maxVal;
}

void ValueSlider::DrawBackground(QPainter* p) const
{
    const QRect rc = PosArea().adjusted(0, 0, -1, -1);

    p->fillRect(rc, Qt::darkGray);
    p->setPen(QPen(Qt::black, 1));
    p->drawRect(rc);
}

void ValueSlider::DrawForeground(QPainter* p) const
{
    const double relVal = (val - minVal) / (maxVal - minVal);
    const int w = int((PosArea().width() - 2) * relVal);
    const QRect rc(1, 1, w, PosArea().height() - 2);
    const QRect clip = PosArea().adjusted(1, 1, -2, -1);

    const QColor c1(135, 135, 135);
    const QColor c2(50, 50, 50);
    const QColor c3(135, 135, 135);

    QLinearGradient gradient(1, 1, 1, rc.height());
    gradient.setColorAt(0.0, c1);
    gradient.setColorAt(0.8, c2);
    gradient.setColorAt(1.0, c3);

    p->setClipRect(clip);
    p->fillRect(rc, gradient);

    if (!IsEditorMode())
    {
        QStyleOptionFrameV2 panel;
        panel.initFrom(this);
        style()->drawItemText(p, clip.adjusted(3, 1, 0, 0), (Qt::AlignLeft | Qt::AlignVCenter), palette(), true, QString::number(val, 'f', digitsAfterDot), QPalette::WindowText);

        if (arrows.isNull())
        {
            const int div = 3;
            const QSize arrowSize(clip.height() / div + 1, clip.height() / div + 1);
            const QImage& left = PaintingHelper::DrawArrowIcon(arrowSize, RIGHT_EDGE);
            const QImage& right = PaintingHelper::DrawArrowIcon(arrowSize, LEFT_EDGE);

            arrows = QPixmap(arrowSize.width() * 2, arrowSize.height());
            arrows.fill(Qt::transparent);
            QPainter pa(&arrows);
            pa.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing, false);
            pa.drawImage(0, 0, left);
            pa.drawImage(arrowSize.width(), 0, right);
        }

        p->drawPixmap(clip.width() - arrows.width(), (clip.height() - arrows.height()) / 2, arrows);
    }
}

QRect ValueSlider::PosArea() const
{
    return QRect(0, 0, width(), height());
}

void ValueSlider::paintEvent(QPaintEvent* e)
{
    Q_UNUSED(e);

    QPainter p(this);

    p.save();
    DrawBackground(&p);
    p.restore();
    p.save();
    DrawForeground(&p);
    p.restore();
}

void ValueSlider::resizeEvent(QResizeEvent* e)
{
    Q_UNUSED(e);
}

bool ValueSlider::eventFilter(QObject* obj, QEvent* e)
{
    if (obj == editor)
    {
        switch (e->type())
        {
        case QEvent::KeyPress:
        {
            QKeyEvent* ke = static_cast<QKeyEvent*>(e);
            switch (ke->key())
            {
            case Qt::Key_Enter:
            case Qt::Key_Return:
            case Qt::Key_Escape:
            case Qt::Key_Tab:
                acceptEditing();
                ke->accept();
                return true;

            default:
                break;
            }
        }
        break;

        case QEvent::FocusOut:
            acceptEditing();
            break;

        default:
            break;
        }
    }

    return QWidget::eventFilter(obj, e);
}

bool ValueSlider::IsEditorMode() const
{
    return !editor.isNull();
}

void ValueSlider::OnMousePress(const QPoint& pos)
{
    clickPos = pos;
    clickVal = val;

    QApplication::setOverrideCursor(Qt::BlankCursor);
    emit started(GetValue());
}

void ValueSlider::OnMouseMove(const QPoint& pos)
{
    if (mouse->IsPressed())
    {
        const int dist = pos.x() - clickPos.x();
        const int w = width();
        const double dd = double(dist) / double(w);
        const double dw = (maxVal - minVal);
        const double ofs = dd * dw;

        val = clickVal + ofs;
        normalize();
        emit changing(GetValue());

        repaint();
    }
}

void ValueSlider::OnMouseRelease(const QPoint& pos)
{
    QCursor::setPos(mapToGlobal(clickPos));
    QApplication::restoreOverrideCursor();

    if (clickVal != val)
    {
        emit changed(GetValue());
    }
    else
    {
        emit canceled();
    }
}

void ValueSlider::OnMouseClick()
{
    if (editor)
        delete editor;

    QRegExpValidator* validator = new QRegExpValidator(QRegExp("\\s*-?\\d*[,\\.]?\\d*\\s*"));

    editor = new QLineEdit(this);
    editor->installEventFilter(this);
    editor->setValidator(validator);
    editor->setStyleSheet(ValueSliderDetail::editorQss);
    editor->move(0, 0);
    editor->resize(width(), height());

    editor->setText(QString::number(val, 'f', digitsAfterDot));

    editor->show();
    editor->setFocus();
    update();
}

void ValueSlider::normalize()
{
    if (val < minVal)
    {
        val = minVal;
        update();
    }
    if (val > maxVal)
    {
        val = maxVal;
        update();
    }
}

void ValueSlider::undoEditing()
{
    if (editor)
    {
        editor->deleteLater();
    }
}

void ValueSlider::acceptEditing()
{
    if (editor)
    {
        const QString text = editor->text();

        bool ok = true;
        const double newVal = text.isEmpty() ? 0.0 : text.toDouble(&ok);
        if (ok)
        {
            val = newVal;
            normalize();
            emit changed(val);
        }

        editor->deleteLater();
        update();
    }
}
}


text:
using namespace gxy;

using testing::_;
using testing::DoAll;
using testing::InvokeArgument;
using testing::IsNull;
using testing::NiceMock;
using testing::NotNull;
using testing::Return;

struct Fixture : public testing::Test
{
  NiceMock<gl::mockglxw> mockglxw{};
  NiceMock<gl::mockglfw> mockglfw{};

  Fixture()
  {
#if BOOST_OS_MACOS
    EXPECT_CALL(mockglxw, Init())
      .Times(0);
#endif

    ON_CALL(mockglfw, Init())
      .WillByDefault(Return(GL_TRUE));
  }
};

TEST_F(Fixture, CreateEnvironment_CallsInit)
{
  EXPECT_CALL(mockglfw, Init())
    .Times(1);

  gl::environment env;
}

TEST_F(Fixture, InitReturnsFalse_Throw)
{
  EXPECT_CALL(mockglfw, Init())
    .WillOnce(Return(GL_FALSE));

  ASSERT_THROW(gl::environment(), std::runtime_error);
}

TEST_F(Fixture, SetErrorCallbackCalled)
{
  EXPECT_CALL(mockglfw, SetErrorCallback(NotNull()))
    .Times(1);

  gl::environment env;

  EXPECT_CALL(mockglfw, SetErrorCallback(IsNull()))
    .Times(1);
}

TEST_F(Fixture, SetErrorCallback_InvokeThrows)
{
  auto callback([](int, const char *) {});

  EXPECT_CALL(mockglfw, SetErrorCallback(_))
    .WillOnce(DoAll(InvokeArgument<0>(0, "badger"), Return(callback)));

  ASSERT_THROW(gl::environment(), gl::glfw_error);
}

TEST_F(Fixture, SetErroCallback_InvokeThrowsParametersPropagated)
{
  auto callback([](int, const char *) {});

  EXPECT_CALL(mockglfw, SetErrorCallback(_))
    .WillOnce(DoAll(InvokeArgument<0>(GLFW_INVALID_ENUM, "badger"), Return(callback)));

  try {
    gl::environment env;
  } catch(const std::exception &e) {
    ASSERT_STREQ("invalid_enum: badger", e.what());
  }
}

TEST_F(Fixture, TerminateCalledOnDestruction)
{
  gl::environment env;

  EXPECT_CALL(mockglfw, Terminate())
    .Times(1);
}

using FixtureDeathTest = Fixture;

TEST_F(FixtureDeathTest, SetErrorCallbackReturnsNull)
{
  ASSERT_DEATH({
    auto callback([](int, const char *) {});
    EXPECT_CALL(mockglfw, SetErrorCallback(_))
      .WillOnce(Return(callback));

    gl::environment env;
  }, "");
}


text:
package org.infinispan.reconfigurableprotocol;

import org.infinispan.CacheException;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.remote.ReconfigurableProtocolCommand;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.interceptors.DeadlockDetectingInterceptor;
import org.infinispan.interceptors.EntryWrappingInterceptor;
import org.infinispan.interceptors.InterceptorChain;
import org.infinispan.interceptors.InvalidationInterceptor;
import org.infinispan.interceptors.ReplicationInterceptor;
import org.infinispan.interceptors.VersionedEntryWrappingInterceptor;
import org.infinispan.interceptors.VersionedReplicationInterceptor;
import org.infinispan.interceptors.base.CommandInterceptor;
import org.infinispan.interceptors.distribution.NonTxConcurrentDistributionInterceptor;
import org.infinispan.interceptors.distribution.NonTxDistributionInterceptor;
import org.infinispan.interceptors.distribution.TxDistributionInterceptor;
import org.infinispan.interceptors.distribution.VersionedDistributionInterceptor;
import org.infinispan.interceptors.gmu.GMUDistributionInterceptor;
import org.infinispan.interceptors.gmu.GMUEntryWrappingInterceptor;
import org.infinispan.interceptors.gmu.GMUReplicationInterceptor;
import org.infinispan.interceptors.locking.NonTransactionalLockingInterceptor;
import org.infinispan.interceptors.locking.OptimisticLockingInterceptor;
import org.infinispan.interceptors.locking.OptimisticReadWriteLockingInterceptor;
import org.infinispan.interceptors.locking.PessimisticLockingInterceptor;
import org.infinispan.reconfigurableprotocol.manager.ReconfigurableReplicationManager;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.statetransfer.StateTransferInterceptor;
import org.infinispan.transaction.LocalTransaction;
import org.infinispan.transaction.LockingMode;
import org.infinispan.transaction.TransactionMode;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.util.InfinispanCollections;
import org.infinispan.util.concurrent.IsolationLevel;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;

import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static org.infinispan.commands.remote.ReconfigurableProtocolCommand.Type;
import static org.infinispan.interceptors.InterceptorChain.InterceptorType;

/**
 * represents an instance of a replication protocol
 *
 * @author Pedro Ruivo
 * @since 5.2
 */
public abstract class ReconfigurableProtocol {

   private static final String LOCAL_STOP_ACK = "_LOCAL_ACK_";
   protected final Log log = LogFactory.getLog(getClass());
   protected final Map<GlobalTransaction, Set<Object>> localTransactions;
   protected final Map<GlobalTransaction, Set<Object>> remoteTransactions;
   protected final Set<Transaction> localExecutionTransactions;
   private final AckCollector ackCollector;
   protected Configuration configuration;
   protected ReconfigurableReplicationManager manager;
   private ComponentRegistry componentRegistry;
   private RpcManager rpcManager;
   private CommandsFactory commandsFactory;

   public ReconfigurableProtocol() {
      localTransactions = new HashMap<GlobalTransaction, Set<Object>>();
      remoteTransactions = new HashMap<GlobalTransaction, Set<Object>>();
      localExecutionTransactions = new HashSet<Transaction>();
      ackCollector = new AckCollector();
   }

   //sets the dependencies
   public final void initialize(Configuration configuration, ComponentRegistry componentRegistry,
                                ReconfigurableReplicationManager manager) {
      this.configuration = configuration;
      this.componentRegistry = componentRegistry;
      this.manager = manager;
      this.rpcManager = getComponent(RpcManager.class);
      this.commandsFactory = getComponent(CommandsFactory.class);
   }

   public final void startTransaction(Transaction transaction) {
      synchronized (localExecutionTransactions) {
         localExecutionTransactions.add(transaction);
      }
   }

   public final boolean commitTransaction(GlobalTransaction globalTransaction, Object[] affectedKeys,
                                       Transaction transaction) {
      synchronized (localExecutionTransactions) {
         synchronized (localTransactions) {
            boolean removed = transaction != null && localExecutionTransactions.remove(transaction);
            localExecutionTransactions.notifyAll();
            try {
               if (transaction != null && transaction.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
                  throw new CacheException("Transaction " + globalTransaction.globalId() + " is marked for rollback.");
               }
            } catch (SystemException e) {
               throw new CacheException(e);
            }
            localTransactions.put(globalTransaction, affectedKeys == null ? InfinispanCollections.emptySet() : new HashSet<Object>(Arrays.asList(affectedKeys)));
            return removed;
         }
      }
   }

   public final boolean commitTransaction(Transaction transaction) {
      synchronized (localExecutionTransactions) {
         boolean removed = transaction != null && localExecutionTransactions.remove(transaction);
         localExecutionTransactions.notifyAll();
         try {
            if (transaction != null && transaction.getStatus() == Status.STATUS_MARKED_ROLLBACK) {
               throw new CacheException("Transaction " + transaction + " is marked for rollback.");
            }
         } catch (SystemException e) {
            throw new CacheException(e);
         }
         return removed;
      }
   }

   /**
    * Adds the global transaction to the list of local transactions finished by this protocol
    *
    * @param globalTransaction the global transaction
    * @param affectedKeys      the modifications array
    */
   public final void addLocalTransaction(GlobalTransaction globalTransaction, Object[] affectedKeys) {
      synchronized (localTransactions) {
         localTransactions.put(globalTransaction, affectedKeys == null ? InfinispanCollections.emptySet() : new HashSet<Object>(Arrays.asList(affectedKeys)));
      }
   }

   /**
    * Removes the global transaction to the list of local transactions finished by this protocol
    *
    * @param globalTransaction the global transaction
    */
   public final void removeLocalTransaction(GlobalTransaction globalTransaction) {
      synchronized (localTransactions) {
         localTransactions.remove(globalTransaction);
         localTransactions.notifyAll();
      }
   }

   /**
    * Adds the global transaction to the list of remote transactions finished by this protocol
    *
    * @param globalTransaction the global transaction
    * @param affectedKeys      the modifications array
    */
   public final void addRemoteTransaction(GlobalTransaction globalTransaction, Object[] affectedKeys) {
      synchronized (remoteTransactions) {
         if (remoteTransactions.get(globalTransaction) != null) {
            //no-op
         } else if (affectedKeys == null) {
            remoteTransactions.put(globalTransaction, null);
         } else {
            remoteTransactions.put(globalTransaction, new HashSet<Object>(Arrays.asList(affectedKeys)));
         }
      }
   }

   /**
    * Removes the global transaction to the list of remote transactions finished by this protocol
    *
    * @param globalTransaction the global transaction
    */
   public final void removeRemoteTransaction(GlobalTransaction globalTransaction) {
      synchronized (remoteTransactions) {
         remoteTransactions.remove(globalTransaction);
         remoteTransactions.notifyAll();
      }
   }

   /**
    * method invoked when a message is received for this protocol
    *
    * @param data the data in the message
    * @param from the sender
    */
   public final void handleData(Object data, Address from) {
      if (LOCAL_STOP_ACK.equals(data)) {
         if (log.isTraceEnabled()) {
            log.tracef("Data message from %s received and it is a stop ack", from);
         }
         ackCollector.ack(from);
      } else {
         if (log.isTraceEnabled()) {
            log.tracef("Data message from %s received. Data is %s", from, data);
         }
         internalHandleData(data, from);
      }
   }

   @Override
   public final String toString() {
      return "ReconfigurableProtocol{protocolName=" + getUniqueProtocolName() + "}";
   }

   /**
    * it ensures that the write set in parameters does not conflict with transactions that are committing with this
    * protocol. This method can block waiting for transactions to finish
    *
    * @param affectedKeys the modifications array
    * @throws InterruptedException if it is interrupted while waiting
    */
   public final void ensureNoConflict(Object[] affectedKeys) throws InterruptedException {
      synchronized (localTransactions) {
         boolean conflict = true;
         while (conflict) {
            conflict = false;
            for (Set<Object> localWriteSet : localTransactions.values()) {
               if (localWriteSet == null || affectedKeys == null) {
                  conflict = true;
                  localTransactions.wait();
                  break;
               }
            }
         }
      }

      synchronized (remoteTransactions) {
         boolean conflict = true;
         while (conflict) {
            conflict = false;
            for (Set<Object> localWriteSet : remoteTransactions.values()) {
               if (localWriteSet == null || affectedKeys == null) {
                  conflict = true;
                  remoteTransactions.wait();
                  break;
               }
            }
         }
      }
   }

   /**
    * returns all the pending local transactions and their write set
    *
    * @return all the pending local transactions and their write set
    */
   public final String printLocalTransactions() {
      StringBuilder sb = new StringBuilder("Local committing transactions are:\n");
      synchronized (localTransactions) {
         for (Map.Entry<GlobalTransaction, Set<Object>> entry : localTransactions.entrySet()) {
            sb.append(entry.getKey().globalId()).append("=>").append(entry.getValue()).append("\n");
         }
      }

      sb.append("\nLocal executing transactions are:\n");
      synchronized (localExecutionTransactions) {
         for (Transaction transaction : localExecutionTransactions) {
            sb.append(transaction).append("\n");
         }
      }

      return sb.toString();
   }

   /**
    * returns all the pending remote transactions and their write set
    *
    * @return all the pending remote transactions and their write set
    */
   public final String printRemoteTransactions() {
      StringBuilder sb = new StringBuilder("Remote transactions are:\n");
      synchronized (remoteTransactions) {
         for (Map.Entry<GlobalTransaction, Set<Object>> entry : remoteTransactions.entrySet()) {
            sb.append(entry.getKey().globalId()).append("=>").append(entry.getValue()).append("\n");
         }
      }
      return sb.toString();
   }

   /**
    * the global unique protocol name
    *
    * @return the global unique protocol name
    */
   public abstract String getUniqueProtocolName();

   /**
    * returns true if the {@link #switchTo(ReconfigurableProtocol)} can be perform with the new protocol
    *
    * @param protocol the new protocol
    * @return true if this protocol can switch directly to the new protocol, false otherwise
    */
   public abstract boolean canSwitchTo(ReconfigurableProtocol protocol);

   /**
    * this method switches between te current protocol to the new protocol without ensure this strong condition: -- no
    * transaction in the current protocol are running in all the system see {@link #stopProtocol(boolean)}
    *
    * @param protocol the new protocol
    */
   public abstract void switchTo(ReconfigurableProtocol protocol);

   /**
    * it ensures that no transactions in the current protocol are running in the system (strong condition). this is
    * necessary to switch to any protocol In other words, it means that all transactions active with that protocol in
    * the cluster need to be ended
    *
    * @param abortOnStop abort local executing transaction (that did not request the commit) otherwise it waits for that
    *                    transactions to finish
    */
   public abstract void stopProtocol(boolean abortOnStop) throws InterruptedException;

   /**
    * it starts this new protocol
    */
   public abstract void bootProtocol();

   /**
    * method invoked before a normal remote transaction will be processed in a safe state
    *
    * @param globalTransaction the global transaction
    * @param affectedKKeys     the modifications array
    */
   public abstract void processTransaction(GlobalTransaction globalTransaction, Object[] affectedKKeys);

   /**
    * method invoked before an old remote transaction will be processed
    *
    * @param globalTransaction the global transaction
    * @param affectedKeys      the modifications array
    * @param currentProtocol   the current replication protocol
    */
   public abstract void processOldTransaction(GlobalTransaction globalTransaction, Object[] affectedKeys, ReconfigurableProtocol currentProtocol);

   /**
    * method invoked before a correct epoch transaction will be processed in an unsafe state
    *
    * @param globalTransaction the global transaction
    * @param affectedKeys      the affected keys, null if it has clear command
    * @param oldProtocol       the old replication protocol
    */
   public abstract void processSpeculativeTransaction(GlobalTransaction globalTransaction, Object[] affectedKeys,
                                                      ReconfigurableProtocol oldProtocol);

   /**
    * one of the first methods to be invoked when this protocol is register. It must register all the components added
    * and possible dependencies
    */
   public abstract void bootstrapProtocol();

   /**
    * creates the interceptor chain for this protocol. if some position in the map is null, the interceptor in that
    * position is bypassed. It is possible to add two custom interceptors: one before Tx Interceptor and another after.
    * <p/>
    * Note: the interceptor instances should be instances returned by {@link #createInterceptor(org.infinispan.interceptors.base.CommandInterceptor,
    * Class)}
    *
    * @return the map with the new interceptors
    */
   public abstract EnumMap<InterceptorType, CommandInterceptor> buildInterceptorChain();

   /**
    * check is this local transaction can be committed via 1 phase, instead of 2 phases. In 1 phase, only the prepare
    * message is created
    *
    * @param localTransaction the local transaction that wants finish
    * @return true if it can be committed in 1 phase, false otherwise
    */
   public abstract boolean use1PC(LocalTransaction localTransaction);

   /**
    * returns true is the replication protocol uses Total Order properties
    *
    * @return true is the replication protocol uses Total Order properties
    */
   public abstract boolean useTotalOrder();

   /**
    * blocks until the local transaction set is empty, i.e., no more local transactions are committing
    *
    * @throws InterruptedException if interrupted
    */
   protected final void awaitUntilLocalCommittingTransactionsFinished() throws InterruptedException {
      if (log.isTraceEnabled()) {
         log.tracef("[%s] thread will wait until all local transaction are finished", Thread.currentThread().getName());
      }
      synchronized (localTransactions) {
         while (!localTransactions.isEmpty()) {
            localTransactions.wait();
         }
      }
      if (log.isTraceEnabled()) {
         log.tracef("[%s] all local transaction are finished. Moving on...", Thread.currentThread().getName());
      }
   }

   protected final void awaitUntilLocalExecutingTransactionsFinished(boolean abort) throws InterruptedException {
      if (log.isTraceEnabled()) {
         log.tracef("[%s] thread will wait until all executing local transaction are finished", Thread.currentThread().getName());
      }
      synchronized (localExecutionTransactions) {
         if (abort) {
            for (Transaction transaction : localExecutionTransactions) {
               try {
                  transaction.setRollbackOnly();
               } catch (SystemException e) {
                  if (log.isDebugEnabled()) {
                     log.warnf(e, "Error marking transaction %s to rollback only.", transaction);
                  } else {
                     log.warnf("Error marking transaction %s to rollback only. %s", transaction, e.getMessage());
                  }
               }
            }
            manager.addNumberOfAbortedTransactionDueToSwitch(localExecutionTransactions.size());
         } else {
            while (!localExecutionTransactions.isEmpty()) {
               localExecutionTransactions.wait();
            }
         }
      }
      if (log.isTraceEnabled()) {
         log.tracef("[%s] all local transaction are finished. Moving on...", Thread.currentThread().getName());
      }
   }

   /**
    * blocks until the remote transaction set is empty, i.e., no more remote transactions are committing
    *
    * @throws InterruptedException if interrupted
    */
   protected final void awaitUntilRemoteTransactionsFinished() throws InterruptedException {
      if (log.isTraceEnabled()) {
         log.tracef("[%s] thread will wait until all remote transaction are finished", Thread.currentThread().getName());
      }
      synchronized (remoteTransactions) {
         while (!remoteTransactions.isEmpty()) {
            remoteTransactions.wait();
         }
      }
      if (log.isTraceEnabled()) {
         log.tracef("[%s] all remote transaction are finished. Moving on...", Thread.currentThread().getName());
      }
   }

   /**
    * Registers a component in the registry under the given type, and injects any dependencies needed.  If a component
    * of this type already exists, it is overwritten.
    *
    * @param component component to register
    * @param clazz     type of component
    */
   protected final void registerComponent(Object component, Class<?> clazz) {
      if (log.isTraceEnabled()) {
         log.tracef("Register a new component. Object is %s, and class is %s", component, clazz);
      }
      componentRegistry.registerComponent(component, clazz);
   }

   /**
    * it tries to create and register the interceptor. if it exists, it returns the old instance if it does not exits,
    * it register the interceptor in {@param interceptor}
    *
    * @param interceptor     the interceptor to register if it does not exits
    * @param interceptorType the interceptor type
    * @return the instance of the interceptor type
    */
   protected final CommandInterceptor createInterceptor(CommandInterceptor interceptor, Class<? extends CommandInterceptor> interceptorType) {
      if (log.isTraceEnabled()) {
         log.tracef("Create a new interceptor. Class is %s", interceptorType);
      }
      CommandInterceptor chainedInterceptor = getComponent(interceptorType);
      if (chainedInterceptor == null) {
         chainedInterceptor = interceptor;
         registerComponent(interceptor, interceptorType);
      }
      return chainedInterceptor;
   }

   /**
    * Retrieves a component of a specified type from the registry, or null if it cannot be found.
    *
    * @param clazz type to find
    * @return component, or null
    */
   protected final <T> T getComponent(Class<? extends T> clazz) {
      return componentRegistry.getComponent(clazz);
   }

   /**
    * broadcast the data for all members in the cluster
    *
    * @param data       the data
    * @param totalOrder if the data should be sent in total order
    */
   protected final void broadcastData(Object data, boolean totalOrder) {
      if (LOCAL_STOP_ACK.equals(data)) {
         throw new IllegalStateException("Cannot broadcast data for protocol " + getUniqueProtocolName() + ". It" +
                                               " is equals to the private data");
      }
      internalBroadcastData(data, totalOrder);
   }

   protected final boolean needsVersionAwareComponents() {
      return configuration.transaction().transactionMode() == TransactionMode.TRANSACTIONAL &&
            configuration.locking().writeSkewCheck() &&
            configuration.transaction().lockingMode() == LockingMode.OPTIMISTIC &&
            configuration.versioning().enabled();
   }

   /**
    * builds the default 2PC interceptor chain based on the configuration
    *
    * @return the default 2PC interceptor chain
    */
   protected final EnumMap<InterceptorType, CommandInterceptor> buildDefaultInterceptorChain() {
      EnumMap<InterceptorType, CommandInterceptor> defaultIC = new EnumMap<InterceptorType, CommandInterceptor>(InterceptorType.class);
      boolean serializability = configuration.locking().isolationLevel() == IsolationLevel.SERIALIZABLE;

      //State transfer
      // load the state transfer lock interceptor
      // the state transfer lock ensures that the cache member list is up-to-date
      // so it's necessary even if state transfer is disabled
      if (configuration.clustering().cacheMode().isDistributed() || configuration.clustering().cacheMode().isReplicated()) {
         defaultIC.put(InterceptorChain.InterceptorType.STATE_TRANSFER,
                       createInterceptor(new StateTransferInterceptor(), StateTransferInterceptor.class));
      }

      //Locking
      if (configuration.transaction().transactionMode() == TransactionMode.TRANSACTIONAL) {
         if (serializability) {
            defaultIC.put(InterceptorType.LOCKING,
                          createInterceptor(new OptimisticReadWriteLockingInterceptor(),
                                            OptimisticReadWriteLockingInterceptor.class));
         } else if (configuration.transaction().lockingMode() == LockingMode.PESSIMISTIC) {
            defaultIC.put(InterceptorType.LOCKING,
                          createInterceptor(new PessimisticLockingInterceptor(), PessimisticLockingInterceptor.class));
         } else {
            defaultIC.put(InterceptorType.LOCKING,
                          createInterceptor(new OptimisticLockingInterceptor(), OptimisticLockingInterceptor.class));
         }
      } else {
         if (configuration.locking().supportsConcurrentUpdates())
            defaultIC.put(InterceptorType.LOCKING,
                          createInterceptor(new NonTransactionalLockingInterceptor(), NonTransactionalLockingInterceptor.class));
      }

      //Wrapper
      if (serializability) {
         defaultIC.put(InterceptorType.WRAPPER,
                       createInterceptor(new GMUEntryWrappingInterceptor(), GMUEntryWrappingInterceptor.class));
      } else if (needsVersionAwareComponents() && configuration.clustering().cacheMode().isClustered()) {
         defaultIC.put(InterceptorType.WRAPPER,
                       createInterceptor(new VersionedEntryWrappingInterceptor(), VersionedEntryWrappingInterceptor.class));

      } else {
         defaultIC.put(InterceptorType.WRAPPER,
                       createInterceptor(new EntryWrappingInterceptor(), EntryWrappingInterceptor.class));
      }

      //Deadlock
      if (configuration.deadlockDetection().enabled()) {
         defaultIC.put(InterceptorType.DEADLOCK,
                       createInterceptor(new DeadlockDetectingInterceptor(), DeadlockDetectingInterceptor.class));
      }

      //Clustering interceptor
      switch (configuration.clustering().cacheMode()) {
         case REPL_SYNC:
            if (serializability) {
               defaultIC.put(InterceptorType.CLUSTER,
                             createInterceptor(new GMUReplicationInterceptor(), GMUReplicationInterceptor.class));
               break;
            } else if (needsVersionAwareComponents()) {
               defaultIC.put(InterceptorType.CLUSTER,
                             createInterceptor(new VersionedReplicationInterceptor(), VersionedReplicationInterceptor.class));
               break;
            }
         case REPL_ASYNC:
            defaultIC.put(InterceptorType.CLUSTER,
                          createInterceptor(new ReplicationInterceptor(), ReplicationInterceptor.class));
            break;
         case INVALIDATION_SYNC:
         case INVALIDATION_ASYNC:
            defaultIC.put(InterceptorType.CLUSTER,
                          createInterceptor(new InvalidationInterceptor(), InvalidationInterceptor.class));
            break;
         case DIST_SYNC:
            if (serializability) {
               defaultIC.put(InterceptorType.CLUSTER,
                             createInterceptor(new GMUDistributionInterceptor(), GMUDistributionInterceptor.class));
               break;
            } else if (needsVersionAwareComponents()) {
               defaultIC.put(InterceptorType.CLUSTER,
                             createInterceptor(new VersionedDistributionInterceptor(), VersionedDistributionInterceptor.class));
               break;
            }
         case DIST_ASYNC:
            if (configuration.transaction().transactionMode().isTransactional()) {
               defaultIC.put(InterceptorType.CLUSTER,
                             createInterceptor(new TxDistributionInterceptor(), TxDistributionInterceptor.class));
            } else {
               if (configuration.locking().supportsConcurrentUpdates()) {
                  defaultIC.put(InterceptorType.CLUSTER,
                                createInterceptor(new NonTxConcurrentDistributionInterceptor(), NonTxConcurrentDistributionInterceptor.class));
               } else {
                  defaultIC.put(InterceptorType.CLUSTER,
                                createInterceptor(new NonTxDistributionInterceptor(), NonTxDistributionInterceptor.class));
               }
            }
            break;
         case LOCAL:
            //Nothing...
      }

      if (log.isTraceEnabled()) {
         log.tracef("Building default Interceptor Chain: %s", defaultIC);
      }

      return defaultIC;
   }

   /**
    * performs a global stop the world model, ensuring no local neither remote transaction are committing
    *
    * @param totalOrder if it uses total order
    * @throws InterruptedException if interrupted
    */
   protected final void globalStopProtocol(boolean totalOrder, boolean abortOnStop) throws InterruptedException {
      /*
      1) block local transactions (already done by Manager)
      2) wait until all local transactions has finished
      3) send message signal the end of transactions
      4) wait for others members messages
      5) wait until all remote transactions has finished
      */
      if (log.isDebugEnabled()) {
         log.debugf("[%s] Performing the global stop protocol. Using total order? %s", Thread.currentThread().getName(),
                    totalOrder);
      }
      awaitUntilLocalExecutingTransactionsFinished(abortOnStop);
      awaitUntilLocalCommittingTransactionsFinished();
      internalBroadcastData(LOCAL_STOP_ACK, totalOrder);
      ackCollector.awaitAllAck();
      awaitUntilRemoteTransactionsFinished();
      if (log.isDebugEnabled()) {
         log.debugf("[%s] Global stop protocol completed. No transaction are committing now",
                    Thread.currentThread().getName());
      }
   }

   /**
    * returns the actual cache members
    *
    * @return the actual cache members
    */
   protected final Collection<Address> getCacheMembers() {
      return rpcManager.getTransport().getMembers();
   }

   /**
    * returns true it this node is the coordinator, false otherwise
    *
    * @return true it this node is the coordinator, false otherwise
    */
   protected final boolean isCoordinator() {
      return rpcManager.getTransport().isCoordinator();
   }

   /**
    * throw an exception when this protocol cannot process an old transaction
    */
   protected final void throwOldTxException(GlobalTransaction globalTransaction) {
      manager.addNumberOfAbortedTransactionDueToSwitch(1);
      throw new CacheException("Old transaction '" + globalTransaction.globalId() + "' from " +
                                     getUniqueProtocolName() + " not allowed in current epoch");
   }

   /**
    * throw an exception when this protocol cannot process a speculative transaction
    */
   protected final void throwSpeculativeTxException(GlobalTransaction globalTransaction) {
      manager.addNumberOfAbortedTransactionDueToSwitch(1);
      throw new CacheException("Speculative transaction '" + globalTransaction.globalId() + "' from " +
                                     getUniqueProtocolName() + " not allowed");
   }

   /**
    * logs the normal transaction process
    *
    * @param globalTransaction the global transaction
    */
   protected final void logProcessTransaction(GlobalTransaction globalTransaction) {
      if (log.isTraceEnabled()) {
         log.tracef("Process transaction '%s'", globalTransaction.globalId());
      }
   }

   /**
    * logs the old transaction process
    *
    * @param globalTransaction the global transaction
    * @param current           the current protocol
    */
   protected final void logProcessOldTransaction(GlobalTransaction globalTransaction, ReconfigurableProtocol current) {
      if (log.isTraceEnabled()) {
         log.tracef("Process old transaction '%s' and the current protocol is %s",
                    globalTransaction.globalId(), current.getUniqueProtocolName());
      }
   }

   /**
    * logs the speculative transaction process
    *
    * @param globalTransaction the global transaction
    * @param old               the old protocol
    */
   protected final void logProcessSpeculativeTransaction(GlobalTransaction globalTransaction, ReconfigurableProtocol old) {
      if (log.isTraceEnabled()) {
         log.tracef("Process speculative transaction '%s' and the old protocol is %s",
                    globalTransaction.globalId(), old.getUniqueProtocolName());
      }
   }

   /**
    * method invoked when a message is received for this protocol
    *
    * @param data the data in the message
    * @param from the sender
    */
   protected abstract void internalHandleData(Object data, Address from);

   /**
    * broadcast the data for all members in the cluster
    *
    * @param data       the data
    * @param totalOrder if the data should be sent in total order
    */
   private void internalBroadcastData(Object data, boolean totalOrder) {
      if (log.isTraceEnabled()) {
         log.tracef("Broadcast data. Data is %s, Using total order? %s", data, totalOrder);
      }

      ReconfigurableProtocolCommand command = commandsFactory.buildReconfigurableProtocolCommand(Type.DATA, getUniqueProtocolName());
      command.setData(data);
      rpcManager.broadcastRpcCommand(command, false, totalOrder);
   }

   /**
    * class the collects all the ack from all member, unblocking waiting threads in the end
    */
   protected class AckCollector {
      //NOTE: it is assuming that nodes will no leave neither join the cache during the switch
      private final Set<Address> members;
      private boolean notReady;

      public AckCollector() {
         members = new HashSet<Address>();
         notReady = true;
      }

      public synchronized final void ack(Address from) {
         resetIfNeeded();

         if (log.isDebugEnabled()) {
            log.debugf("Received stop ack from %s", from);
         }
         members.remove(from);
         if (members.isEmpty()) {
            this.notifyAll();
         }
      }

      public synchronized final void awaitAllAck() throws InterruptedException {
         resetIfNeeded();

         if (log.isDebugEnabled()) {
            log.debugf("[%s] thread will wait for all acks...", Thread.currentThread().getName());
         }
         while (!members.isEmpty()) {
            this.wait();
         }
         if (log.isDebugEnabled()) {
            log.debugf("[%s] all acks received. Moving on...", Thread.currentThread().getName());
         }
         notReady = true;
      }

      private void resetIfNeeded() {
         if (notReady) {
            members.clear();
            members.addAll(getCacheMembers());
            members.remove(rpcManager.getAddress());
            notReady = false;
         }
      }
   }
}


text:
using SqlServerDataAdapter.Infrastruction;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlServerDataAdapter
{
    public class Insert<T>
    {
        private string _tableName;
        private IDictionary<string, object> _values;
        private IList<ExcludeField> _excludeField; //不需要添加的字段

        public Insert(string tableName, T values, IList<ExcludeField> excludeField)
        {
            _tableName = tableName;
            _values = ConvertToDictionary.ConvertTo<T>(values);
            _excludeField = excludeField;
        }

        public Insert(string tableName, T values)
        {
            _tableName = tableName;
            _values = ConvertToDictionary.ConvertTo<T>(values);
            _excludeField = new List<ExcludeField>();
        }

        public Insert(string tableName)
        {
            _tableName = tableName;
            _values = new Dictionary<string, object>();
            _excludeField = new List<ExcludeField>();
        }

        private Insert()
        { }

        public string TableName
        {
            get { return _tableName; }
        }
        public IDictionary<string, object> Values
        {
            get { return _values; }
            //set { _values = value; }
        }
        public IList<ExcludeField> ExcludeField
        {
            get { return _excludeField; }
            set { _excludeField = value; }
        }

        public void AddValues(T values)
        {
            _values = ConvertToDictionary.ConvertTo<T>(values);
        }

        public void AddExcludeField(ExcludeField excludeField)
        {
            _excludeField.Add(excludeField);
        }
        public void AddExcludeField(string fieldName)
        {
            _excludeField.Add(new ExcludeField
            {
                Name = fieldName
            });
        }
    }
}


text:
package org.mapfish.print;

import java.nio.charset.Charset;

/**
 * Strings used in configurations etc...
 * User: jeichar
 * Date: Sep 30, 2010
 * Time: 4:27:46 PM
 *

 * CSOFF:MagicNumber
 * CSOFF:RequireThis
 */
public interface Constants {
    /**
     * The layout tag in the json spec file.
     */
    String JSON_LAYOUT_KEY = "layout";

    /**
     * The output filename in the json spec file.
     */
    String OUTPUT_FILENAME_KEY = "outputFilename";

    /**
     * The default encoding to use throughout the system.  This can be set by setting the system property:
     *

     * mapfish.file.encoding
     *

     * before starting the JVM.
     */
    String DEFAULT_ENCODING = System.getProperty("mapfish.file.encoding", "UTF-8");

    /**
     * The default charset.  Depends on {@link #DEFAULT_ENCODING}.
     */
    Charset DEFAULT_CHARSET = Charset.forName(DEFAULT_ENCODING);

    /**
     * The DPI of a PDF according to the spec.  Also the DPI used by old Openlayers versions (2.0 and earlier).
     */
    double PDF_DPI = 72.0;

    /**
     * The OGC standard dpi. (About 90 dpi)
     */
    double OGC_DPI = 25.4 / 0.28;
    /**
     * The amount of precision to use when comparing opacity levels.  For example 0.0009 is considered the same as 0.0 for opacity
     */
    double OPACITY_PRECISION = 0.001;

    /**
     * Style related constants.
     */
    interface Style {
        double POINT_SIZE = 10.0;

        /**
         * Grid style constants.
         */
        interface Grid {

            /**
             * The name of the grid feature type name.
             */
            String NAME_LINES = "grid";
            /**
             * The geometry attribute name.
             */
            String ATT_GEOM = "geom";
        }

        /**
         * Raster style constants.
         */
        interface Raster {

            /**
             * The default style name for raster layers.
             */
            String NAME = "raster";
        }

        /**
         * Default Style for the Overview Map and Area of interest.
         */
        interface OverviewMap {

            /**
             * The default style name for the bbox rectangle in the overview map.
             */
            String NAME = "overview-map";
        }
    }
}