text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>HebBinyan</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

HebBinyan: binyan (verb form in Hebrew)

Binyan (plural binyanim; "building, structure") is a traditional part of verbal morphology in Hebrew
(see, e.g., page 1347 of books.google.com
or http://tzion.org/devarim/The%20Seven%20Binyanim.pdf).
It mostly corresponds to Voice, but also Mood in other languages.

The individual binyan categories reflect the root-vowel templates for the given forms.
For example, template CaCaC means that the three consonants of the root of the verb
are interspersed with two vowels a.

PAAL: basic/simple form

Template CaCaC. The basic form corresponds to the active voice.

Examples

katav "wrote"

NIFAL: basic/simple-passive form

Template niCCaC. This form corresponds to the passive voice.

Examples

niktav "was written"

PIEL: intensive form

Template CiCeC. Active voice, but the action is done intensively.

Examples

kitev "inscribed, engraved"

PUAL: intensive-passive form

Template CuCaC. Passive voice, but the action is done intensively.

Examples

kutav "was inscribed/engraved" (theoretical, to illustrate the binyanim; not used with this root)

HIFIL: causative form

Template hiCCiC. Causative voice.

Examples

hiktiv "dictated"

HUFAL: causative-passive form

Template huCCaC. Causative-passive voice.

Examples

huktav "was dictated"

HITPAEL: reflexive-cooperative form

Template hitCaCeC. Reflexive, reciprocal or middle voice.

Examples

hitkatev "corresponded"

HebBinyan in other languages:

[hbo]

[he]

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
@class NSMutableArray, NSString;

@interface GiftCenter : WXPBGeneratedMessage
{
}

+ (void)initialize;

// Remaining properties
@property(retain, nonatomic) NSString *desc; // @dynamic desc;
@property(retain, nonatomic) NSString *externInfo; // @dynamic externInfo;
@property(retain, nonatomic) NSString *imgUrl; // @dynamic imgUrl;
@property(retain, nonatomic) NSString *jumpUrl; // @dynamic jumpUrl;
@property(nonatomic) unsigned int positionId; // @dynamic positionId;
@property(retain, nonatomic) NSMutableArray *signGiftList; // @dynamic signGiftList;
@property(retain, nonatomic) NSString *title; // @dynamic title;
@property(nonatomic) unsigned int type; // @dynamic type;

@end

redpajama_set_name: RedPajamaGithub


text:
package org.drip.spline.stretch;

/*
 * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 */

/*!
 * Copyright (C) 2017 Lakshmi Krishnamurthy
 * Copyright (C) 2016 Lakshmi Krishnamurthy
 * Copyright (C) 2015 Lakshmi Krishnamurthy
 * Copyright (C) 2014 Lakshmi Krishnamurthy
 * Copyright (C) 2013 Lakshmi Krishnamurthy
 *
 *  This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
 *  	libraries targeting analysts and developers
 *  	https://lakshmidrip.github.io/DRIP/
 *
 *  DRIP is composed of four main libraries:
 *
 *  - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
 *  - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
 *  - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
 *  - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
 *
 *  - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
 *  	Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
 *  	Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
 *  	Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
 *  	Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
 *
 *  - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
 *  	Incorporator, Holdings Constraint, and Transaction Costs.
 *
 *  - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
 *
 *  - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *   	you may not use this file except in compliance with the License.
 *
 *  You may obtain a copy of the License at
 *  	http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  	distributed under the License is distributed on an "AS IS" BASIS,
 *  	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 *  See the License for the specific language governing permissions and
 *  	limitations under the License.
 */

/**
 * SingleSegmentLagrangePolynomial implements the SingleSegmentSequence Stretch interface using the Lagrange
 *  Polynomial Estimator. As such it provides a perfect fit that travels through all the predictor/response
 *  pairs causing Runge's instability.
 *
 * @author Lakshmi Krishnamurthy
 */

public class SingleSegmentLagrangePolynomial implements org.drip.spline.stretch.SingleSegmentSequence {
	private static final double DIFF_SCALE = 1.0e-06;
	private static final int MAXIMA_PREDICTOR_ORDINATE_NODE = 1;
	private static final int MINIMA_PREDICTOR_ORDINATE_NODE = 2;
	private static final int MONOTONE_PREDICTOR_ORDINATE_NODE = 4;

	private double[] _adblResponseValue = null;
	private double[] _adblPredictorOrdinate = null;

	private static final double CalcAbsoluteMin (
		final double[] adblY)
		throws java.lang.Exception
	{
		if (null == adblY)
			throw new java.lang.Exception
				("SingleSegmentLagrangePolynomial::CalcAbsoluteMin => Invalid Inputs");

		int iNumPoints = adblY.length;

		if (1 >= iNumPoints)
			throw new java.lang.Exception
				("SingleSegmentLagrangePolynomial::CalcAbsoluteMin => Invalid Inputs");

		double dblMin = java.lang.Math.abs (adblY[0]);

		for (int i = 0; i < iNumPoints; ++i) {
			double dblValue = java.lang.Math.abs (adblY[i]);

			dblMin = dblMin > dblValue ? dblValue : dblMin;
		}

		return dblMin;
	}

	private static final double CalcMinDifference (
		final double[] adblY)
		throws java.lang.Exception
	{
		if (null == adblY)
			throw new java.lang.Exception
				("SingleSegmentLagrangePolynomial::CalcMinDifference => Invalid Inputs");

		int iNumPoints = adblY.length;

		if (1 >= iNumPoints)
			throw new java.lang.Exception
				("SingleSegmentLagrangePolynomial::CalcMinDifference => Invalid Inputs");

		double dblMinDiff = java.lang.Math.abs (adblY[0] - adblY[1]);

		for (int i = 0; i < iNumPoints; ++i) {
			for (int j = i + 1; j < iNumPoints; ++j) {
				double dblDiff = java.lang.Math.abs (adblY[i] - adblY[j]);

				dblMinDiff = dblMinDiff > dblDiff ? dblDiff : dblMinDiff;
			}
		}

		return dblMinDiff;
	}

	private static final double EstimateBumpDelta (
		final double[] adblY)
		throws java.lang.Exception
	{
		double dblBumpDelta = CalcMinDifference (adblY);

		if (!org.drip.quant.common.NumberUtil.IsValid (dblBumpDelta) || 0. == dblBumpDelta)
			dblBumpDelta = CalcAbsoluteMin (adblY);

		return 0. == dblBumpDelta ? DIFF_SCALE : dblBumpDelta * DIFF_SCALE;
	}

	/**
	 * SingleSegmentLagrangePolynomial constructor
	 *
	 * @param adblPredictorOrdinate Array of Predictor Ordinates
	 *
	 * @throws java.lang.Exception Thrown if inputs are invalid
	 */

	public SingleSegmentLagrangePolynomial (
		final double[] adblPredictorOrdinate)
		throws java.lang.Exception
	{
		if (null == (_adblPredictorOrdinate = adblPredictorOrdinate))
			throw new java.lang.Exception ("SingleSegmentLagrangePolynomial ctr: Invalid Inputs");

		int iNumPredictorOrdinate = _adblPredictorOrdinate.length;

		if (1 >= iNumPredictorOrdinate)
			throw new java.lang.Exception ("SingleSegmentLagrangePolynomial ctr: Invalid Inputs");

		for (int i = 0; i < iNumPredictorOrdinate; ++i) {
			for (int j = i + 1; j < iNumPredictorOrdinate; ++j) {
				if (_adblPredictorOrdinate[i] == _adblPredictorOrdinate[j])
					throw new java.lang.Exception ("SingleSegmentLagrangePolynomial ctr: Invalid Inputs");
			}
		}
	}

	@Override public boolean setup (
		final double dblYLeading,
		final double[] adblResponseValue,
		final org.drip.spline.params.StretchBestFitResponse rbfr,
		final org.drip.spline.stretch.BoundarySettings bs,
		final int iCalibrationDetail)
	{
		return null != (_adblResponseValue = adblResponseValue) && _adblResponseValue.length ==
			_adblPredictorOrdinate.length;
	}

	@Override public double responseValue (
		final double dblPredictorOrdinate)
		throws java.lang.Exception
	{
		if (!org.drip.quant.common.NumberUtil.IsValid (dblPredictorOrdinate))
			throw new java.lang.Exception
				("SingleSegmentLagrangePolynomial::responseValue => Invalid inputs!");

		int iNumPredictorOrdinate = _adblPredictorOrdinate.length;

		if (_adblPredictorOrdinate[0] > dblPredictorOrdinate ||
			_adblPredictorOrdinate[iNumPredictorOrdinate - 1] < dblPredictorOrdinate)
			throw new java.lang.Exception
				("SingleSegmentLagrangePolynomial::responseValue => Input out of range!");

		double dblResponse = 0;

		for (int i = 0; i < iNumPredictorOrdinate; ++i) {
			double dblResponsePredictorOrdinateContribution = _adblResponseValue[i];

			for (int j = 0; j < iNumPredictorOrdinate; ++j) {
				if (i != j)
					dblResponsePredictorOrdinateContribution = dblResponsePredictorOrdinateContribution *
						(dblPredictorOrdinate - _adblPredictorOrdinate[j]) / (_adblPredictorOrdinate[i] -
							_adblPredictorOrdinate[j]);
			}

			dblResponse += dblResponsePredictorOrdinateContribution;
		}

		return dblResponse;
	}

	@Override public double responseValueDerivative (
		final double dblPredictorOrdinate,
		final int iOrder)
		throws java.lang.Exception
	{
		if (!org.drip.quant.common.NumberUtil.IsValid (dblPredictorOrdinate) || 0 >= iOrder)
			throw new java.lang.Exception
				("SingleSegmentLagrangePolynomial::responseValueDerivative => Invalid inputs!");

		org.drip.function.definition.R1ToR1 au = new org.drip.function.definition.R1ToR1
			(null) {
			@Override public double evaluate (
				double dblX)
				throws java.lang.Exception
			{
				return responseValue (dblX);
			}
		};

		return au.derivative (dblPredictorOrdinate, iOrder);
	}

	@Override public org.drip.quant.calculus.WengertJacobian jackDResponseDCalibrationInput (
		final double dblPredictorOrdinate,
		final int iOrder)
	{
		if (!org.drip.quant.common.NumberUtil.IsValid (dblPredictorOrdinate)) return null;

		int iNumPredictorOrdinate = _adblPredictorOrdinate.length;
		double dblInputResponseSensitivityShift = java.lang.Double.NaN;
		double dblResponseWithUnadjustedResponseInput = java.lang.Double.NaN;
		org.drip.quant.calculus.WengertJacobian wjDResponseDResponseInput = null;

		if (_adblPredictorOrdinate[0] > dblPredictorOrdinate ||
			_adblPredictorOrdinate[iNumPredictorOrdinate - 1] < dblPredictorOrdinate)
			return null;

		try {
			if (!org.drip.quant.common.NumberUtil.IsValid (dblInputResponseSensitivityShift =
				EstimateBumpDelta (_adblResponseValue)) || !org.drip.quant.common.NumberUtil.IsValid
					(dblResponseWithUnadjustedResponseInput = responseValue (dblPredictorOrdinate)))
				return null;

			wjDResponseDResponseInput = new org.drip.quant.calculus.WengertJacobian (1,
				iNumPredictorOrdinate);
		} catch (java.lang.Exception e) {
			e.printStackTrace();

			return null;
		}

		for (int i = 0; i < iNumPredictorOrdinate; ++i) {
			double[] adblSensitivityShiftedInputResponse = new double[iNumPredictorOrdinate];

			for (int j = 0; j < iNumPredictorOrdinate; ++j)
				adblSensitivityShiftedInputResponse[j] = i == j ? _adblResponseValue[j] +
					dblInputResponseSensitivityShift : _adblResponseValue[j];

			try {
				SingleSegmentLagrangePolynomial lps = new SingleSegmentLagrangePolynomial
					(_adblPredictorOrdinate);

				if (!lps.setup (adblSensitivityShiftedInputResponse[0], adblSensitivityShiftedInputResponse,
					null, org.drip.spline.stretch.BoundarySettings.FloatingStandard(),
						org.drip.spline.stretch.MultiSegmentSequence.CALIBRATE) ||
							!wjDResponseDResponseInput.accumulatePartialFirstDerivative (0, i,
								(lps.responseValue (dblPredictorOrdinate) -
									dblResponseWithUnadjustedResponseInput) /
										dblInputResponseSensitivityShift))
					return null;
			} catch (java.lang.Exception e) {
				e.printStackTrace();

				return null;
			}
		}

		return wjDResponseDResponseInput;
	}

	@Override public org.drip.quant.calculus.WengertJacobian jackDResponseDManifestMeasure (
		final java.lang.String strManifestMeasure,
		final double dblPredictorOrdinate,
		final int iOrder)
	{
		return null;
	}

	@Override public org.drip.spline.segment.Monotonocity monotoneType (
		final double dblPredictorOrdinate)
	{
		if (!org.drip.quant.common.NumberUtil.IsValid (dblPredictorOrdinate)) return null;

		int iNumPredictorOrdinate = _adblPredictorOrdinate.length;

		if (_adblPredictorOrdinate[0] > dblPredictorOrdinate ||
			_adblPredictorOrdinate[iNumPredictorOrdinate - 1] < dblPredictorOrdinate)
			return null;

		if (2 == iNumPredictorOrdinate) {
			try {
				return new org.drip.spline.segment.Monotonocity
					(org.drip.spline.segment.Monotonocity.MONOTONIC);
			} catch (java.lang.Exception e) {
				e.printStackTrace();

				return null;
			}
		}

		org.drip.function.definition.R1ToR1 auDeriv = new
			org.drip.function.definition.R1ToR1 (null) {
			@Override public double evaluate (
				final double dblX)
				throws java.lang.Exception
			{
				double dblDeltaX = CalcMinDifference (_adblPredictorOrdinate) * DIFF_SCALE;

				return (responseValue (dblX + dblDeltaX) - responseValue (dblX)) / dblDeltaX;
			}

			@Override public double integrate (
				final double dblBegin,
				final double dblEnd)
				throws java.lang.Exception
			{
				return org.drip.quant.calculus.R1ToR1Integrator.Boole (this, dblBegin, dblEnd);
			}
		};

		try {
			org.drip.function.r1tor1solver.FixedPointFinderOutput fpop = new
				org.drip.function.r1tor1solver.FixedPointFinderBrent (0., auDeriv, true).findRoot
					(org.drip.function.r1tor1solver.InitializationHeuristics.FromHardSearchEdges (0., 1.));

			if (null == fpop || !fpop.containsRoot())
				return new org.drip.spline.segment.Monotonocity
					(org.drip.spline.segment.Monotonocity.MONOTONIC);

			double dblExtremum = fpop.getRoot();

			if (!org.drip.quant.common.NumberUtil.IsValid (dblExtremum) || dblExtremum <= 0. || dblExtremum
				>= 1.)
				return new org.drip.spline.segment.Monotonocity
					(org.drip.spline.segment.Monotonocity.MONOTONIC);

			double dblDeltaX = CalcMinDifference (_adblPredictorOrdinate) * DIFF_SCALE;

			double dbl2ndDeriv = responseValue (dblExtremum + dblDeltaX) + responseValue (dblExtremum -
				dblDeltaX) - 2. * responseValue (dblPredictorOrdinate);

			if (0. > dbl2ndDeriv)
				return new org.drip.spline.segment.Monotonocity
					(org.drip.spline.segment.Monotonocity.MAXIMA);

			if (0. < dbl2ndDeriv)
				return new org.drip.spline.segment.Monotonocity
					(org.drip.spline.segment.Monotonocity.MINIMA);

			if (0. == dbl2ndDeriv)
				return new org.drip.spline.segment.Monotonocity
					(org.drip.spline.segment.Monotonocity.INFLECTION);

			return new org.drip.spline.segment.Monotonocity
				(org.drip.spline.segment.Monotonocity.NON_MONOTONIC);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		try {
			return new org.drip.spline.segment.Monotonocity
				(org.drip.spline.segment.Monotonocity.MONOTONIC);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@Override public boolean isLocallyMonotone()
		throws java.lang.Exception
	{
		org.drip.spline.segment.Monotonocity sm = monotoneType (0.5 * (_adblPredictorOrdinate[0] +
			_adblPredictorOrdinate[_adblPredictorOrdinate.length - 1]));

		return null != sm && org.drip.spline.segment.Monotonocity.MONOTONIC == sm.type();
	}

	@Override public boolean isCoMonotone (
		final double[] adblMeasuredResponse)
		throws java.lang.Exception
	{
		if (null == adblMeasuredResponse) return false;

		int iNumMeasuredResponse = adblMeasuredResponse.length;

		if (2 >= iNumMeasuredResponse) return false;

		int[] aiNodeMiniMax = new int[iNumMeasuredResponse];
		int[] aiMonotoneType = new int[iNumMeasuredResponse];

		for (int i = 0; i < iNumMeasuredResponse; ++i) {
			if (0 == i || iNumMeasuredResponse - 1 == i)
				aiNodeMiniMax[i] = 0;
			else {
				if (adblMeasuredResponse[i - 1] < adblMeasuredResponse[i] && adblMeasuredResponse[i + 1] <
					adblMeasuredResponse[i])
					aiNodeMiniMax[i] = MAXIMA_PREDICTOR_ORDINATE_NODE;
				else if (adblMeasuredResponse[i - 1] > adblMeasuredResponse[i] && adblMeasuredResponse[i + 1]
					> adblMeasuredResponse[i])
					aiNodeMiniMax[i] = MINIMA_PREDICTOR_ORDINATE_NODE;
				else
					aiNodeMiniMax[i] = MONOTONE_PREDICTOR_ORDINATE_NODE;
			}

			org.drip.spline.segment.Monotonocity sm = monotoneType (adblMeasuredResponse[i]);

			aiMonotoneType[i] = null != sm ? sm.type() :
				org.drip.spline.segment.Monotonocity.NON_MONOTONIC;
		}

		for (int i = 1; i < iNumMeasuredResponse - 1; ++i) {
			if (MAXIMA_PREDICTOR_ORDINATE_NODE == aiNodeMiniMax[i]) {
				if (org.drip.spline.segment.Monotonocity.MAXIMA != aiMonotoneType[i] &&
					org.drip.spline.segment.Monotonocity.MAXIMA != aiMonotoneType[i - 1])
					return false;
			} else if (MINIMA_PREDICTOR_ORDINATE_NODE == aiNodeMiniMax[i]) {
				if (org.drip.spline.segment.Monotonocity.MINIMA != aiMonotoneType[i] &&
					org.drip.spline.segment.Monotonocity.MINIMA != aiMonotoneType[i - 1])
					return false;
			}
		}

		return true;
	}

	@Override public boolean isKnot (
		final double dblPredictorOrdinate)
	{
		if (!org.drip.quant.common.NumberUtil.IsValid (dblPredictorOrdinate)) return false;

		int iNumPredictorOrdinate = _adblPredictorOrdinate.length;

		if (_adblPredictorOrdinate[0] > dblPredictorOrdinate ||
			_adblPredictorOrdinate[iNumPredictorOrdinate - 1] < dblPredictorOrdinate)
			return false;

		for (int i = 0; i < iNumPredictorOrdinate; ++i) {
			if (dblPredictorOrdinate == _adblPredictorOrdinate[i]) return true;
		}

		return false;
	}

	@Override public boolean resetNode (
		final int iPredictorOrdinateNodeIndex,
		final double dblResetResponse)
	{
		if (!org.drip.quant.common.NumberUtil.IsValid (dblResetResponse)) return false;

		if (iPredictorOrdinateNodeIndex > _adblPredictorOrdinate.length) return false;

		_adblResponseValue[iPredictorOrdinateNodeIndex] = dblResetResponse;
		return true;
	}

	@Override public boolean resetNode (
		final int iPredictorOrdinateNodeIndex,
		final org.drip.spline.params.SegmentResponseValueConstraint sprcReset)
	{
		return false;
	}

	@Override public org.drip.function.definition.R1ToR1 toAU()
	{
		org.drip.function.definition.R1ToR1 au = new
			org.drip.function.definition.R1ToR1 (null)
		{
			@Override public double evaluate (
				final double dblVariate)
				throws java.lang.Exception
			{
				return responseValue (dblVariate);
			}

			@Override public double derivative (
				final double dblVariate,
				final int iOrder)
				throws java.lang.Exception
			{
				return responseValueDerivative (dblVariate, iOrder);
			}
		};

		return au;
	}

	@Override public double getLeftPredictorOrdinateEdge()
	{
		return _adblPredictorOrdinate[0];
	}

	@Override public double getRightPredictorOrdinateEdge()
	{
		return _adblPredictorOrdinate[_adblPredictorOrdinate.length - 1];
	}
}


text:
package cmd

import (
	"testing"

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

// TestFmtUnit describes the behavior of fmtUnit.
func TestFmtUnit(t *testing.T) {
	assert.Equal(t, "25 °C", fmtUnit(func() string { return "25" }, "°C"))
	assert.Equal(t, "UNKNOWN", fmtUnit(func() string { return "UNKNOWN" }, "mVA"))
	assert.Equal(t, "", fmtUnit(func() string { return "" }, "MeV"))
}


text:
package org.nutz.trans;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import javax.sql.DataSource;

import org.nutz.lang.ComboException;

public class NutTransaction extends Transaction {

    private static AtomicLong TransIdMaker = new AtomicLong();

    private List<ConnInfo> list;

    private long id;

    private static class ConnInfo {
        ConnInfo(DataSource ds, Connection conn, int level) throws SQLException {
            this.ds = ds;
            this.conn = conn;
            this.oldLevel = conn.getTransactionIsolation();
            if (this.oldLevel != level)
                conn.setTransactionIsolation(level);
        }

        DataSource ds;
        Connection conn;
        int oldLevel;
    }

    public NutTransaction() {
        list = new ArrayList<ConnInfo>();
        id = TransIdMaker.getAndIncrement();
    }

    protected void commit() {
        ComboException ce = new ComboException();
        for (ConnInfo cInfo : list) {
            try {
                // 提交事务
                cInfo.conn.commit();
                // 恢复旧的事务级别
                if (cInfo.conn.getTransactionIsolation() != cInfo.oldLevel)
                    cInfo.conn.setTransactionIsolation(cInfo.oldLevel);
            }
            catch (SQLException e) {
                ce.add(e);
            }
        }
        // 如果有一个数据源提交时发生异常,抛出
        if (null != ce.getCause()) {
            throw ce;
        }
    }

    @Override
    public Connection getConnection(DataSource dataSource) throws SQLException {
        for (ConnInfo p : list)
            if (p.ds == dataSource)
                return p.conn;
        Connection conn = dataSource.getConnection();
        // System.out.printf("=> %s\n", conn.toString());
        if (conn.getAutoCommit())
            conn.setAutoCommit(false);
        // Store conn, it will set the trans level
        list.add(new ConnInfo(dataSource, conn, getLevel()));
        return conn;
    }

    public long getId() {
        return id;
    }

    @Override
    public void close() {
        ComboException ce = new ComboException();
        for (ConnInfo cInfo : list) {
            try {
                // 试图恢复旧的事务级别
                if (!cInfo.conn.isClosed()) {
                    if (cInfo.conn.getTransactionIsolation() != cInfo.oldLevel)
                        cInfo.conn.setTransactionIsolation(cInfo.oldLevel);
                }
            }
            catch (Throwable e) {}
            finally {
                try {
                    cInfo.conn.close();
                }
                catch (Exception e) {
                    ce.add(e);
                }
            }
        }
        // 清除数据源记录
        list.clear();
    }

    @Override
    protected void rollback() {
        for (ConnInfo cInfo : list) {
            try {
                cInfo.conn.rollback();
            }
            catch (Throwable e) {}
        }
    }

}


text:
#ifndef _DEBUG_H_
#define _DEBUG_H_
void putc(char ch);
void printhex(int data);
void printf(char *fmt, ...);
#endif


text:
var fs = require('fs');

// Blogger API back-end helper
var BloggerPostComment = require('../lib/blogger/post_comment.js');

// Load optional shell environment config
var config = require('dotenv');
config._getKeysAndValuesFromEnvFilePath( './.env.curl' );
config.load();

// HTTP request
var req = {};

// Additional cURL options
var options = {};

// options.verbose = false;

// FIXME:
options.pretend = process.env.DRY_RUN;

// Required
req.blog_id = process.env.BLOG_ID || '';

// Required
req.post_id = process.env.POST_ID || '';

// Required
req.token = process.env.TOKEN || '';

options.encoding = 'utf8';

if( process.env.CURL_FILE ) {
  req.body = fs.readFileSync( process.env.CURL_FILE, options.encoding );
}
else {
  req.body = fs.readFileSync( './post_comment.atom', options.encoding );
}

var post = new BloggerPostComment( req, options );
// console.log(post.options);

// ...off you go, HTTP POST request!
post.send( post.options, function on_response( err, data ) {
  if( err ) {
    console.error("app-blogger [ERROR]: ", err );
  }
  else {
    console.log( data );
  }
});


text:
package nz.co.doltech.databind.core.gwt;

import nz.co.doltech.databind.core.properties.Properties;

public class DTO {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        Properties.notify(this, "name");
    }
}


text:
package ru.aserdyuchenko.testTask;

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

/**
 * Created by anton on 05.05.17.
 */
public class Bank {
    /**
     * @param collection - коллекция всех пользователей и их счетов.
     */
    private Map<User, List<Account>> collection = new HashMap<>();

    /**
     * Добавление нового пользователя.
     * @param user - новый пользователь.
     */
    public void addUser(User user) {
        List<Account> accounts = new ArrayList<>();
        collection.put(user, accounts);
    }

    /**
     * Удаление пользователя.
     * @param user - пользователь, с которым будет расторгнут договор.
     */
    public void deleteUser(User user) {
        collection.remove(user);
    }

    /**
     * Добавить счёт пользователю.
     * @param user - Пользователь, которому будет добавлен счёт.
     * @param account - Счёт, который добавляется пользователю.
     */
    public void addAccountToUser(User user, Account account) {
        List<Account> accounts = getUserAccounts(user);
        accounts.add(account);
        collection.put(user, accounts);
    }

    /**
     * Удалить один счёт пользователя.
     * @param user - Пользователь у которого будет удален счёт.
     * @param account - Счёт, который будет удален у пользователя.
     */
    public void deleteAccountFromUser(User user, Account account) throws UserNotFoundException {
        if(collection.containsKey(user)) {
            List<Account> accounts = getUserAccounts(user);
            accounts.remove(account);
            collection.put(user, accounts);
        } else {
            throw new UserNotFoundException();
        }
    }

    /**
     * Получить список счетов для пользователя.
     * @param user - Пользователь, чьи счета будут получены.
     * @return accounts - Счета, которые будут получены.
     */
    public List<Account> getUserAccounts(User user) {
        List<Account> accounts = collection.get(user);
        return accounts;
    }

    /**
     * Метод для перечисления денег с одного счёта на другой счёт.
     * @param srcUser - Пользователь, который отдает деньги.
     * @param srcAccount - Счёт, с которого списываются деньги.
     * @param dstUser - Пользователь, который получит деньги.
     * @param dstAccount - Счёт, на который будут перечислены деньги.
     * @param amount - Сумма для перевода.
     * @return result - Если счёт не найден или не хватает денег на счёте srcAccount(с которого переводят) должен вернуть false.
     */
    public boolean transferMoney(User srcUser, Account srcAccount, User dstUser, Account dstAccount, double amount) throws UserNotFoundException {
        boolean result = true;
        double newAccountValue = 0.0;
        int newAccountRequisites = 0;
        List<Account> accountsOfSrcUser = collection.get(srcUser);
        List<Account> accountsOfDstUser = collection.get(dstUser);
        if (accountsOfSrcUser.contains(srcAccount) && srcAccount.getValue() >= amount) {
            // Add money to dstUser.
            if(accountsOfDstUser.contains(dstAccount)) {
                newAccountValue = dstAccount.getValue() + amount;
                newAccountRequisites = dstAccount.getRequisites();
                accountsOfDstUser.set(accountsOfDstUser.indexOf(dstAccount), new Account(newAccountValue, newAccountRequisites));
            } else {
                newAccountValue = dstAccount.getValue() + amount;
                newAccountRequisites = dstAccount.getRequisites();
                addAccountToUser(dstUser, new Account(newAccountValue, newAccountRequisites));
            }
            // Remove money from srcUser.
            newAccountValue = srcAccount.getValue() - amount;
            newAccountRequisites = srcAccount.getRequisites();
            accountsOfSrcUser.set(accountsOfSrcUser.indexOf(srcAccount), new Account(newAccountValue, newAccountRequisites));
        } else {
            result = false;
        }
        return result;
    }

    public class UserNotFoundException extends Throwable {
    }
}


text:
package load

import (
	"fmt"
	"sort"
	"sync"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
)

var (
	dropCategories = []string{"drop_for_real", "drop_for_fun"}
	localities     = []string{"locality-A", "locality-B"}
	errTest        = fmt.Errorf("test error")
)

// rpcData wraps the rpc counts and load data to be pushed to the store.
type rpcData struct {
	start, success, failure int
	serverData              map[string]float64 // Will be reported with successful RPCs.
}

// TestDrops spawns a bunch of goroutines which report drop data. After the
// goroutines have exited, the test dumps the stats from the Store and makes
// sure they are as expected.
func TestDrops(t *testing.T) {
	var (
		drops = map[string]int{
			dropCategories[0]: 30,
			dropCategories[1]: 40,
			"":                10,
		}
		wantStoreData = &Data{
			TotalDrops: 80,
			Drops: map[string]uint64{
				dropCategories[0]: 30,
				dropCategories[1]: 40,
			},
		}
	)

	ls := perClusterStore{}
	var wg sync.WaitGroup
	for category, count := range drops {
		for i := 0; i < count; i++ {
			wg.Add(1)
			go func(c string) {
				ls.CallDropped(c)
				wg.Done()
			}(category)
		}
	}
	wg.Wait()

	gotStoreData := ls.stats()
	if diff := cmp.Diff(wantStoreData, gotStoreData, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(Data{}, "ReportInterval")); diff != "" {
		t.Errorf("store.stats() returned unexpected diff (-want +got):\n%s", diff)
	}
}

// TestLocalityStats spawns a bunch of goroutines which report rpc and load
// data. After the goroutines have exited, the test dumps the stats from the
// Store and makes sure they are as expected.
func TestLocalityStats(t *testing.T) {
	var (
		localityData = map[string]rpcData{
			localities[0]: {
				start:      40,
				success:    20,
				failure:    10,
				serverData: map[string]float64{"net": 1, "disk": 2, "cpu": 3, "mem": 4},
			},
			localities[1]: {
				start:      80,
				success:    40,
				failure:    20,
				serverData: map[string]float64{"net": 1, "disk": 2, "cpu": 3, "mem": 4},
			},
		}
		wantStoreData = &Data{
			LocalityStats: map[string]LocalityData{
				localities[0]: {
					RequestStats: RequestData{Succeeded: 20, Errored: 10, InProgress: 10},
					LoadStats: map[string]ServerLoadData{
						"net":  {Count: 20, Sum: 20},
						"disk": {Count: 20, Sum: 40},
						"cpu":  {Count: 20, Sum: 60},
						"mem":  {Count: 20, Sum: 80},
					},
				},
				localities[1]: {
					RequestStats: RequestData{Succeeded: 40, Errored: 20, InProgress: 20},
					LoadStats: map[string]ServerLoadData{
						"net":  {Count: 40, Sum: 40},
						"disk": {Count: 40, Sum: 80},
						"cpu":  {Count: 40, Sum: 120},
						"mem":  {Count: 40, Sum: 160},
					},
				},
			},
		}
	)

	ls := perClusterStore{}
	var wg sync.WaitGroup
	for locality, data := range localityData {
		wg.Add(data.start)
		for i := 0; i < data.start; i++ {
			go func(l string) {
				ls.CallStarted(l)
				wg.Done()
			}(locality)
		}
		// The calls to callStarted() need to happen before the other calls are
		// made. Hence the wait here.
		wg.Wait()

		wg.Add(data.success)
		for i := 0; i < data.success; i++ {
			go func(l string, serverData map[string]float64) {
				ls.CallFinished(l, nil)
				for n, d := range serverData {
					ls.CallServerLoad(l, n, d)
				}
				wg.Done()
			}(locality, data.serverData)
		}
		wg.Add(data.failure)
		for i := 0; i < data.failure; i++ {
			go func(l string) {
				ls.CallFinished(l, errTest)
				wg.Done()
			}(locality)
		}
		wg.Wait()
	}

	gotStoreData := ls.stats()
	if diff := cmp.Diff(wantStoreData, gotStoreData, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(Data{}, "ReportInterval")); diff != "" {
		t.Errorf("store.stats() returned unexpected diff (-want +got):\n%s", diff)
	}
}

func TestResetAfterStats(t *testing.T) {
	// Push a bunch of drops, call stats and load stats, and leave inProgress to be non-zero.
	// Dump the stats. Verify expexted
	// Push the same set of loads as before
	// Now dump and verify the newly expected ones.
	var (
		drops = map[string]int{
			dropCategories[0]: 30,
			dropCategories[1]: 40,
		}
		localityData = map[string]rpcData{
			localities[0]: {
				start:      40,
				success:    20,
				failure:    10,
				serverData: map[string]float64{"net": 1, "disk": 2, "cpu": 3, "mem": 4},
			},
			localities[1]: {
				start:      80,
				success:    40,
				failure:    20,
				serverData: map[string]float64{"net": 1, "disk": 2, "cpu": 3, "mem": 4},
			},
		}
		wantStoreData = &Data{
			TotalDrops: 70,
			Drops: map[string]uint64{
				dropCategories[0]: 30,
				dropCategories[1]: 40,
			},
			LocalityStats: map[string]LocalityData{
				localities[0]: {
					RequestStats: RequestData{Succeeded: 20, Errored: 10, InProgress: 10},
					LoadStats: map[string]ServerLoadData{
						"net":  {Count: 20, Sum: 20},
						"disk": {Count: 20, Sum: 40},
						"cpu":  {Count: 20, Sum: 60},
						"mem":  {Count: 20, Sum: 80},
					},
				},
				localities[1]: {
					RequestStats: RequestData{Succeeded: 40, Errored: 20, InProgress: 20},
					LoadStats: map[string]ServerLoadData{
						"net":  {Count: 40, Sum: 40},
						"disk": {Count: 40, Sum: 80},
						"cpu":  {Count: 40, Sum: 120},
						"mem":  {Count: 40, Sum: 160},
					},
				},
			},
		}
	)

	reportLoad := func(ls *perClusterStore) {
		for category, count := range drops {
			for i := 0; i < count; i++ {
				ls.CallDropped(category)
			}
		}
		for locality, data := range localityData {
			for i := 0; i < data.start; i++ {
				ls.CallStarted(locality)
			}
			for i := 0; i < data.success; i++ {
				ls.CallFinished(locality, nil)
				for n, d := range data.serverData {
					ls.CallServerLoad(locality, n, d)
				}
			}
			for i := 0; i < data.failure; i++ {
				ls.CallFinished(locality, errTest)
			}
		}
	}

	ls := perClusterStore{}
	reportLoad(&ls)
	gotStoreData := ls.stats()
	if diff := cmp.Diff(wantStoreData, gotStoreData, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(Data{}, "ReportInterval")); diff != "" {
		t.Errorf("store.stats() returned unexpected diff (-want +got):\n%s", diff)
	}

	// The above call to stats() should have reset all load reports except the
	// inProgress rpc count. We are now going to push the same load data into
	// the store. So, we should expect to see twice the count for inProgress.
	for _, l := range localities {
		ls := wantStoreData.LocalityStats[l]
		ls.RequestStats.InProgress *= 2
		wantStoreData.LocalityStats[l] = ls
	}
	reportLoad(&ls)
	gotStoreData = ls.stats()
	if diff := cmp.Diff(wantStoreData, gotStoreData, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(Data{}, "ReportInterval")); diff != "" {
		t.Errorf("store.stats() returned unexpected diff (-want +got):\n%s", diff)
	}
}

var sortDataSlice = cmp.Transformer("SortDataSlice", func(in []*Data) []*Data {
	out := append([]*Data(nil), in...) // Copy input to avoid mutating it
	sort.Slice(out,
		func(i, j int) bool {
			if out[i].Cluster < out[j].Cluster {
				return true
			}
			if out[i].Cluster == out[j].Cluster {
				return out[i].Service < out[j].Service
			}
			return false
		},
	)
	return out
})

// Test all load are returned for the given clusters, and all clusters are
// reported if no cluster is specified.
func TestStoreStats(t *testing.T) {
	var (
		testClusters = []string{"c0", "c1", "c2"}
		testServices = []string{"s0", "s1"}
		testLocality = "test-locality"
	)

	store := NewStore()
	for _, c := range testClusters {
		for _, s := range testServices {
			store.PerCluster(c, s).CallStarted(testLocality)
			store.PerCluster(c, s).CallServerLoad(testLocality, "abc", 123)
			store.PerCluster(c, s).CallDropped("dropped")
			store.PerCluster(c, s).CallFinished(testLocality, nil)
		}
	}

	wantC0 := []*Data{
		{
			Cluster: "c0", Service: "s0",
			TotalDrops: 1, Drops: map[string]uint64{"dropped": 1},
			LocalityStats: map[string]LocalityData{
				"test-locality": {
					RequestStats: RequestData{Succeeded: 1},
					LoadStats:    map[string]ServerLoadData{"abc": {Count: 1, Sum: 123}},
				},
			},
		},
		{
			Cluster: "c0", Service: "s1",
			TotalDrops: 1, Drops: map[string]uint64{"dropped": 1},
			LocalityStats: map[string]LocalityData{
				"test-locality": {
					RequestStats: RequestData{Succeeded: 1},
					LoadStats:    map[string]ServerLoadData{"abc": {Count: 1, Sum: 123}},
				},
			},
		},
	}
	// Call Stats with just "c0", this should return data for "c0", and not
	// touch data for other clusters.
	gotC0 := store.Stats([]string{"c0"})
	if diff := cmp.Diff(wantC0, gotC0, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(Data{}, "ReportInterval"), sortDataSlice); diff != "" {
		t.Errorf("store.stats() returned unexpected diff (-want +got):\n%s", diff)
	}

	wantOther := []*Data{
		{
			Cluster: "c1", Service: "s0",
			TotalDrops: 1, Drops: map[string]uint64{"dropped": 1},
			LocalityStats: map[string]LocalityData{
				"test-locality": {
					RequestStats: RequestData{Succeeded: 1},
					LoadStats:    map[string]ServerLoadData{"abc": {Count: 1, Sum: 123}},
				},
			},
		},
		{
			Cluster: "c1", Service: "s1",
			TotalDrops: 1, Drops: map[string]uint64{"dropped": 1},
			LocalityStats: map[string]LocalityData{
				"test-locality": {
					RequestStats: RequestData{Succeeded: 1},
					LoadStats:    map[string]ServerLoadData{"abc": {Count: 1, Sum: 123}},
				},
			},
		},
		{
			Cluster: "c2", Service: "s0",
			TotalDrops: 1, Drops: map[string]uint64{"dropped": 1},
			LocalityStats: map[string]LocalityData{
				"test-locality": {
					RequestStats: RequestData{Succeeded: 1},
					LoadStats:    map[string]ServerLoadData{"abc": {Count: 1, Sum: 123}},
				},
			},
		},
		{
			Cluster: "c2", Service: "s1",
			TotalDrops: 1, Drops: map[string]uint64{"dropped": 1},
			LocalityStats: map[string]LocalityData{
				"test-locality": {
					RequestStats: RequestData{Succeeded: 1},
					LoadStats:    map[string]ServerLoadData{"abc": {Count: 1, Sum: 123}},
				},
			},
		},
	}
	// Call Stats with empty slice, this should return data for all the
	// remaining clusters, and not include c0 (because c0 data was cleared).
	gotOther := store.Stats(nil)
	if diff := cmp.Diff(wantOther, gotOther, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(Data{}, "ReportInterval"), sortDataSlice); diff != "" {
		t.Errorf("store.stats() returned unexpected diff (-want +got):\n%s", diff)
	}
}

// Test the cases that if a cluster doesn't have load to report, its data is not
// appended to the slice returned by Stats().
func TestStoreStatsEmptyDataNotReported(t *testing.T) {
	var (
		testServices = []string{"s0", "s1"}
		testLocality = "test-locality"
	)

	store := NewStore()
	// "c0"'s RPCs all finish with success.
	for _, s := range testServices {
		store.PerCluster("c0", s).CallStarted(testLocality)
		store.PerCluster("c0", s).CallFinished(testLocality, nil)
	}
	// "c1"'s RPCs never finish (always inprocess).
	for _, s := range testServices {
		store.PerCluster("c1", s).CallStarted(testLocality)
	}

	want0 := []*Data{
		{
			Cluster: "c0", Service: "s0",
			LocalityStats: map[string]LocalityData{
				"test-locality": {RequestStats: RequestData{Succeeded: 1}},
			},
		},
		{
			Cluster: "c0", Service: "s1",
			LocalityStats: map[string]LocalityData{
				"test-locality": {RequestStats: RequestData{Succeeded: 1}},
			},
		},
		{
			Cluster: "c1", Service: "s0",
			LocalityStats: map[string]LocalityData{
				"test-locality": {RequestStats: RequestData{InProgress: 1}},
			},
		},
		{
			Cluster: "c1", Service: "s1",
			LocalityStats: map[string]LocalityData{
				"test-locality": {RequestStats: RequestData{InProgress: 1}},
			},
		},
	}
	// Call Stats with empty slice, this should return data for all the
	// clusters.
	got0 := store.Stats(nil)
	if diff := cmp.Diff(want0, got0, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(Data{}, "ReportInterval"), sortDataSlice); diff != "" {
		t.Errorf("store.stats() returned unexpected diff (-want +got):\n%s", diff)
	}

	want1 := []*Data{
		{
			Cluster: "c1", Service: "s0",
			LocalityStats: map[string]LocalityData{
				"test-locality": {RequestStats: RequestData{InProgress: 1}},
			},
		},
		{
			Cluster: "c1", Service: "s1",
			LocalityStats: map[string]LocalityData{
				"test-locality": {RequestStats: RequestData{InProgress: 1}},
			},
		},
	}
	// Call Stats with empty slice again, this should return data only for "c1",
	// because "c0" data was cleared, but "c1" has in-progress RPCs.
	got1 := store.Stats(nil)
	if diff := cmp.Diff(want1, got1, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(Data{}, "ReportInterval"), sortDataSlice); diff != "" {
		t.Errorf("store.stats() returned unexpected diff (-want +got):\n%s", diff)
	}
}


text:
/* global HD */

'use strict';

var CHAT = (typeof global !== 'undefined' ? global.CHAT : window.CHAT) || {};

/**
 * Rendszer által kiírt szövegek
 * @type {Object}
 */
CHAT.Labels = {
    // Rendszerüzenetek
    system : {
        join : (fromUserName) =>
            `${fromUserName} csatlakozott`,
        leave : (fromUserName) =>
            `${fromUserName} kilépett`,
        forceJoinYou : (fromUserName) =>
            `${fromUserName} hozzáadott ehhez a csatornához`,
        forceJoinOther : (fromUserName, toUserName) =>
            `${fromUserName} hozzáadta ${toUserName} felhasználót ehhez a csatornához`,
        forceLeaveYou : (fromUserName) =>
            `${fromUserName} kidobott`,
        forceLeaveOther : (fromUserName, toUserName) =>
            `${fromUserName} kidobta ${toUserName} felhasználót`
    },
    // Tájékoztató feliratok
    legend : {
        haveToLogIn : 'A chat használatához be kell jelentkezned!',
        message : 'Üzenet',
        sendMode : 'Küldés enter megnyomására',
        dropFile : 'Ide húzd a fájlokat amiket át akarsz küldeni!'
    },
    // Felhasználó által kiváltott műveletek
    action : {
        chatStart : 'Chat',
        sendMessage : 'Küldés',
        sendFile : 'Fájlküldés',
        smiley : 'Emoticon beszúrása',
        leave : 'Kilépés',
        minimize : 'Összecsukás',
        resize : {
            toggle : 'Átméretezés',
            box : 'Doboz méret',
            container : 'Konténer méret',
            window : 'Teljes ablak méret',
            screen : 'Teljes képernyő méret'
        },
        sound : 'Hangos értesítések',
        settings : 'Beállítások',
        forceJoin : 'Hozzáadás',
        forceLeave : 'Kidobás'
    },
    // Felhasználó státusza
    status : {
        on : 'Elérhető',
        busy : 'Elfoglalt',
        away : 'Elment',
        inv : 'Lopakodó',
        off : 'Offline',
        idle : 'Tétlen'
    },
    // Fájlátvitel
    file : {
        read : 'Fájl beolvasása...',
        send : 'Fájlküldés...',
        get : 'Fájlfogadás...',
        abort : 'Fájlátvitel megszakítva',
        forceAbort : 'A fájlátvitelt a rendszer megszakította',
        sendEnd : 'Fájlküldés befejeződött',
        getEnd : 'Fájlfogadás befejeződött',
        cancel : 'Megszakítás',
        percent : (p) => `${p}%`,
        error : 'Hiba a fájl betöltése közben',
        deleted : 'A fájlküldés meg lett szakítva vagy a fájl törölve lett',
        types : {
            image : 'Kép',
            text  : 'Szöveges fájl',
            code  : 'Forráskód',
            pdf   : 'PDF dokumentum',
            doc   : 'Word dokumentum',
            xls   : 'Excel dokumentum',
            ppt   : 'Diavetítés',
            zip   : 'Tömörített állomány',
            audio : 'Hangfájl',
            video : 'Videófájl',
            exec  : 'Futtatható állomány',
            file  : 'Ismeretlen fájltípus'
        }
    },
    // Üzenetátvitel
    message : {
        stillWrite : (userName) => `${userName} éppen ír...`,
        stopWrite : (userName) => `${userName} szöveget írt be`
    },
    // Értesítések
    notification : {
        // Általános értesítések
        general : {
            message : (fromUserName) =>
                `${fromUserName} üzenetet írt`,
            file : (fromUserName) =>
                `${fromUserName} fájlt küldött`,
            create : (fromUserName) =>
                `${fromUserName} létrehozott egy csatornát`,
            join : (fromUserName) =>
                `${fromUserName} csatlakozott a csatornához`,
            leave : (fromUserName) =>
                `${fromUserName} elhagyta a csatornát`,
            forceJoinYou : (fromUserName) =>
                `${fromUserName} csatlakoztatott egy csatornához`,
            forceJoinOther : (fromUserName, toUserName) =>
                `${fromUserName} hozzáadta ${toUserName} felhasználót egy csatornához`,
            forceLeaveYou : (fromUserName) =>
                `${fromUserName} kidobott egy csatornából`,
            forceLeaveOther : (fromUserName, toUserName) =>
                `${fromUserName} kidobta ${toUserName} felhasználót az egyik csatornából`
        },
        // Helyi értesítések
        local : {
            message : (fromUserName) =>
                `${fromUserName} üzenetet írt`,
            file : (fromUserName) =>
                `${fromUserName} fájlt küldött`,
            join : (fromUserName) =>
                `${fromUserName} csatlakozott ehhez a csatornához`,
            leave : (fromUserName) =>
                `${fromUserName} elhagyta ezt a csatornát`,
            forceJoinOther : (fromUserName, toUserName) =>
                `${fromUserName} hozzáadta ${toUserName} felhasználót ehhez a csatornához`,
            forceLeaveYou : (fromUserName) =>
                `${fromUserName} kidobott`,
            forceLeaveOther : (fromUserName, toUserName) =>
                `${fromUserName} kidobta ${toUserName} felhasználót`
        },
        // Asztali értestések
        desktop : {
            options : {
                // Írás iránya ('auto'|'ltr'|'rtl')
                dir : 'auto',
                // Nyelv
                lang : 'HU',
                // Az értesítés "title" része alatti szöveg
                // body : '',
                // A szöveg melletti kép
                icon : '/images/notification.png'
            },
            message : (fromUserName) =>
                `${fromUserName} üzenetet írt`,
            file : (fromUserName) =>
                `${fromUserName} fájlt küldött`,
            create : (fromUserName) =>
                `${fromUserName} létrehozott egy csatornát`,
            join : (fromUserName) =>
                `${fromUserName} csatlakozott a csatornához`,
            leave : (fromUserName) =>
                `${fromUserName} elhagyta a csatornát`,
            forceJoinYou : (fromUserName) =>
                `${fromUserName} csatlakoztatott egy csatornához`,
            forceJoinOther : (fromUserName, toUserName) =>
                `${fromUserName} hozzáadta ${toUserName} felhasználót egy csatornához`,
            forceLeaveYou : (fromUserName) =>
                `${fromUserName} kidobott egy csatornából`,
            forceLeaveOther : (fromUserName, toUserName) =>
                `${fromUserName} kidobta ${toUserName} felhasználót az egyik csatornából`
        }
    },
    // Idő kijelzése
    time : {
        // Idő mértékegységek
        idleTimer : ['nap', 'óra', 'perc', 'másodperc'],
        // Még sosem volt aktív
        notYetOnline : '-',
        // Kevesebb, mint 1 perce volt aktív
        lessThanMin : 'most'
    },
    // Hibaüzenetek
    error : {
        maxUsers : (maxUser) =>
            `Legfeljebb ${maxUser} felhasználó lehet egy csatornában!`,
        fileAllowed : () =>
            `Fájlfeltöltés nincs engedélyezve!`,
        fileSize : (size, maxSize) =>
            `Túl nagy a fájl mérete (${HD.Number.displaySize(size)})!
            Maximális méret: ${HD.Number.displaySize(maxSize)}.`,
        fileType : (type, allowedTypes) =>
            `Nem megfelelő a fájl típusa (${CHAT.Labels.file.types[type]})!
            Megengedett típusok: ${allowedTypes.map(t => CHAT.Labels.file.types[t]).join(', ')}.`
    }
};

if (typeof exports !== 'undefined'){
    exports.Labels = CHAT.Labels;
}


text:
'use strict';

var path = require("path"),
    fs = require("fs");

module.exports = function(fixture) {
  return fs.readFileSync(path.resolve('test/support/fixtures', fixture), 'utf-8');
};


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'workflow_fork'
require 'active_record'
require 'sqlite3'
require 'pry'

require 'minitest/autorun'

# 关闭migrate 输出
ActiveRecord::Migration.verbose = false

class << Minitest::Test
  def test(name, &block)
    test_name = :"test_#{name.gsub(' ','_')}"
    raise ArgumentError, "#{test_name} is already defined" if self.instance_methods.include? test_name.to_s
    if block
      define_method test_name, &block
    else
      puts "PENDING: #{name}"
    end
  end
end

class ActiveRecordTestCase < Minitest::Test
  def setup
    ActiveRecord::Base.establish_connection(
      :adapter => "sqlite3",
      :database  => ":memory:" #"tmp/test"
    )
    # eliminate ActiveRecord warning. TODO: delete as soon as ActiveRecord is fixed
    ActiveRecord::Base.connection.reconnect!
  end
end


text:
ENV['SFR_BOX_MAC']="44:ce:7d:99:99:99"

RSpec.describe SfrBoxHelper, :type => :helper do
    describe "is connected to correct network" do
        it "validates on a correct network" do
            content = "garbage   s f   d44:ce:7d:99:99:99gdd garbage"
            expect(SfrBoxHelper.isCorrectNetwork(content)).to eq(true)
        end
        it "does not validate on a incorrect network" do
            content = "garbage   s f   d44:ce:7d:66:66:66gdd garbage"
            expect(SfrBoxHelper.isCorrectNetwork(content)).to eq(false)
        end
        it "does not validate on a missing content" do
            content = nil
            expect(SfrBoxHelper.isCorrectNetwork(content)).to eq(false)
        end
        it "does not validate on a empty content" do
            content = ""
            expect(SfrBoxHelper.isCorrectNetwork(content)).to eq(false)
        end
    end
end


text:
package com.boldradius.astrolabe.core

import com.typesafe.scalalogging.{ Logger, LazyLogging }

import scala.language.implicitConversions

/**
 * @author patrick.premont@boldradius.com
 */
trait LogF extends LazyLogging {
  implicit val loggerF = logger
  def withValue[V](v: V)(f: V => Unit): V = { f(v); v }
  implicit def toLogging[V](v: V): Logging[V] = Logging(v)

  def time[A](f: => A): (A, Long) = {
    val s = System.currentTimeMillis; val v: A = f; (v, System.currentTimeMillis - s)
  }
  def logTime[A](show: Long => String)(f: => A): A = time(f).logTest { case (_, t) => show(t) }._1

}

case class Logging[V](v: V) extends LazyLogging {
  def logInfo(f: V => String)(implicit loggerF: Logger): V = { loggerF.info(f(v)); v }
  def logDebug(f: V => String)(implicit loggerF: Logger): V = { loggerF.debug(f(v)); v }
  def logError(f: V => String)(implicit loggerF: Logger): V = { loggerF.error(f(v)); v }

  def logTest(f: V => String)(implicit loggerF: Logger): V = { loggerF.debug(f(v)); v }
}


text:
namespace extensions {

namespace {

class TestPredicateEvaluator;

class TestPredicate : public ContentPredicate {
 public:
  explicit TestPredicate(ContentPredicateEvaluator* evaluator)
      : evaluator_(evaluator) {
  }

  TestPredicate(const TestPredicate&) = delete;
  TestPredicate& operator=(const TestPredicate&) = delete;

  ContentPredicateEvaluator* GetEvaluator() const override {
    return evaluator_;
  }

 private:
  raw_ptr<ContentPredicateEvaluator> evaluator_;
};

class TestPredicateEvaluator : public ContentPredicateEvaluator {
 public:
  explicit TestPredicateEvaluator(ContentPredicateEvaluator::Delegate* delegate)
      : delegate_(delegate),
        contents_for_next_operation_evaluation_(nullptr),
        next_evaluation_result_(false) {
  }

  TestPredicateEvaluator(const TestPredicateEvaluator&) = delete;
  TestPredicateEvaluator& operator=(const TestPredicateEvaluator&) = delete;

  std::string GetPredicateApiAttributeName() const override {
    return "test_predicate";
  }

  std::unique_ptr<const ContentPredicate> CreatePredicate(
      const Extension* extension,
      const base::Value& value,
      std::string* error) override {
    RequestEvaluationIfSpecified();
    return std::make_unique<TestPredicate>(this);
  }

  void TrackPredicates(
      const std::map<const void*,
          std::vector<const ContentPredicate*>>& predicates) override {
    RequestEvaluationIfSpecified();
  }

  void StopTrackingPredicates(
      const std::vector<const void*>& predicate_groups) override {
    RequestEvaluationIfSpecified();
  }

  void TrackForWebContents(content::WebContents* contents) override {
    RequestEvaluationIfSpecified();
  }

  void OnWebContentsNavigation(
      content::WebContents* contents,
      content::NavigationHandle* navigation_handle) override {
    RequestEvaluationIfSpecified();
  }

  void OnWatchedPageChanged(
      content::WebContents* contents,
      const std::vector<std::string>& css_selectors) override {
    RequestEvaluationIfSpecified();
  }

  bool EvaluatePredicate(const ContentPredicate* predicate,
                         content::WebContents* tab) const override {
    bool result = next_evaluation_result_;
    next_evaluation_result_ = false;
    return result;
  }

  void RequestImmediateEvaluation(content::WebContents* contents,
                                  bool evaluation_result) {
    next_evaluation_result_ = evaluation_result;
    delegate_->RequestEvaluation(contents);
  }

  void RequestEvaluationOnNextOperation(content::WebContents* contents,
                                        bool evaluation_result) {
    contents_for_next_operation_evaluation_ = contents;
    next_evaluation_result_ = evaluation_result;
  }

 private:
  void RequestEvaluationIfSpecified() {
    if (contents_for_next_operation_evaluation_)
      delegate_->RequestEvaluation(contents_for_next_operation_evaluation_);
    contents_for_next_operation_evaluation_ = nullptr;
  }

  raw_ptr<ContentPredicateEvaluator::Delegate> delegate_;
  raw_ptr<content::WebContents> contents_for_next_operation_evaluation_;
  mutable bool next_evaluation_result_;
};

// Create the test evaluator and set |evaluator| to its pointer.
std::vector<std::unique_ptr<ContentPredicateEvaluator>> CreateTestEvaluator(
    TestPredicateEvaluator** evaluator,
    ContentPredicateEvaluator::Delegate* delegate) {
  std::vector<std::unique_ptr<ContentPredicateEvaluator>> evaluators;
  *evaluator = new TestPredicateEvaluator(delegate);
  evaluators.push_back(std::unique_ptr<ContentPredicateEvaluator>(*evaluator));
  return evaluators;
}

}  // namespace

class DeclarativeChromeContentRulesRegistryTest : public testing::Test {
 public:
  DeclarativeChromeContentRulesRegistryTest() {}

  DeclarativeChromeContentRulesRegistryTest(
      const DeclarativeChromeContentRulesRegistryTest&) = delete;
  DeclarativeChromeContentRulesRegistryTest& operator=(
      const DeclarativeChromeContentRulesRegistryTest&) = delete;

 protected:
  TestExtensionEnvironment* env() { return &env_; }

 private:
  TestExtensionEnvironment env_;

  // Must come after |env_| so only one UI MessageLoop is created.
  content::RenderViewHostTestEnabler rvh_enabler_;
};

TEST_F(DeclarativeChromeContentRulesRegistryTest, ActiveRulesDoesntGrow) {
  TestPredicateEvaluator* evaluator = nullptr;
  scoped_refptr<ChromeContentRulesRegistry> registry(
      new ChromeContentRulesRegistry(
          env()->profile(), nullptr,
          base::BindOnce(&CreateTestEvaluator, &evaluator)));

  EXPECT_EQ(0u, registry->GetActiveRulesCountForTesting());

  std::unique_ptr<content::WebContents> tab = env()->MakeTab();
  registry->MonitorWebContentsForRuleEvaluation(tab.get());
  content::MockNavigationHandle navigation_handle;
  navigation_handle.set_has_committed(true);

  registry->DidFinishNavigation(tab.get(), &navigation_handle);
  EXPECT_EQ(0u, registry->GetActiveRulesCountForTesting());

  // Add a rule.
  api::events::Rule rule;
  api::events::Rule::Populate(base::test::ParseJson(R"({
          "id": "rule1",
          "priority": 100,
          "conditions": [
           {
             "instanceType": "declarativeContent.PageStateMatcher",
             "test_predicate": []
           }],
          "actions": [
            {"instanceType": "declarativeContent.ShowAction"}
          ]
      })"),
                              &rule);
  std::vector<const api::events::Rule*> rules({&rule});

  const Extension* extension =
      env()->MakeExtension(base::test::ParseJson("{\"page_action\": {}}"));
  registry->AddRulesImpl(extension->id(), rules);

  registry->DidFinishNavigation(tab.get(), &navigation_handle);
  EXPECT_EQ(0u, registry->GetActiveRulesCountForTesting());

  evaluator->RequestImmediateEvaluation(tab.get(), true);
  EXPECT_EQ(1u, registry->GetActiveRulesCountForTesting());

  // Closing the tab should erase its entry from active_rules_. Invoke
  // WebContentsDestroyed on the registry to mock it being notified that the tab
  // has closed.
  registry->WebContentsDestroyed(tab.get());
  tab.reset();
  EXPECT_EQ(0u, registry->GetActiveRulesCountForTesting());

  tab = env()->MakeTab();
  content::MockNavigationHandle navigation_handle2;
  navigation_handle2.set_has_committed(true);
  registry->MonitorWebContentsForRuleEvaluation(tab.get());
  evaluator->RequestImmediateEvaluation(tab.get(), true);
  EXPECT_EQ(1u, registry->GetActiveRulesCountForTesting());

  evaluator->RequestEvaluationOnNextOperation(tab.get(), false);
  registry->DidFinishNavigation(tab.get(), &navigation_handle2);
  EXPECT_EQ(0u, registry->GetActiveRulesCountForTesting());
}

}  // namespace extensions


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

using System;
using System.Diagnostics;
using System.Windows;
using ITCC.NetworkView.AdvancedSample.NetworkModel;
using ITCC.NetworkView.Utils;

namespace ITCC.NetworkView.AdvancedSample
{
    /// <summary>
    /// The view-model for the main window.
    /// </summary>
    public class MainWindowViewModel : AbstractModelBase
    {
        #region Internal Data Members

        /// <summary>
        /// This is the network that is displayed in the window.
        /// It is the main part of the view-model.
        /// </summary>
        public NetworkViewModel network;

        ///
        /// The current scale at which the content is being viewed.
        ///
        private double _contentScale = 1;

        ///
        /// The X coordinate of the offset of the viewport onto the content (in content coordinates).
        ///
        private double _contentOffsetX;

        ///
        /// The Y coordinate of the offset of the viewport onto the content (in content coordinates).
        ///
        private double _contentOffsetY;

        ///
        /// The width of the content (in content coordinates).
        ///
        private double _contentWidth = 1000;

        ///
        /// The heigth of the content (in content coordinates).
        ///
        private double _contentHeight = 1000;

        ///
        /// The width of the viewport onto the content (in content coordinates).
        /// The value for this is actually computed by the main window's ZoomAndPanControl and update in the
        /// view-model so that the value can be shared with the overview window.
        ///
        private double _contentViewportWidth;

        ///
        /// The height of the viewport onto the content (in content coordinates).
        /// The value for this is actually computed by the main window's ZoomAndPanControl and update in the
        /// view-model so that the value can be shared with the overview window.
        ///
        private double _contentViewportHeight;

        #endregion Internal Data Members

        public MainWindowViewModel()
        {
            // Add some test data to the view-model.
            PopulateWithTestData();
        }

        /// <summary>
        /// This is the network that is displayed in the window.
        /// It is the main part of the view-model.
        /// </summary>
        public NetworkViewModel Network
        {
            get
            {
                return network;
            }
            set
            {
                network = value;

                OnPropertyChanged();
            }
        }

        ///
        /// The current scale at which the content is being viewed.
        ///
        public double ContentScale
        {
            get
            {
                return _contentScale;
            }
            set
            {
                _contentScale = value;

                OnPropertyChanged();
            }
        }

        ///
        /// The X coordinate of the offset of the viewport onto the content (in content coordinates).
        ///
        public double ContentOffsetX
        {
            get
            {
                return _contentOffsetX;
            }
            set
            {
                _contentOffsetX = value;

                OnPropertyChanged();
            }
        }

        ///
        /// The Y coordinate of the offset of the viewport onto the content (in content coordinates).
        ///
        public double ContentOffsetY
        {
            get
            {
                return _contentOffsetY;
            }
            set
            {
                _contentOffsetY = value;

                OnPropertyChanged();
            }
        }

        ///
        /// The width of the content (in content coordinates).
        ///
        public double ContentWidth
        {
            get
            {
                return _contentWidth;
            }
            set
            {
                _contentWidth = value;

                OnPropertyChanged();
            }
        }

        ///
        /// The heigth of the content (in content coordinates).
        ///
        public double ContentHeight
        {
            get
            {
                return _contentHeight;
            }
            set
            {
                _contentHeight = value;

                OnPropertyChanged();
            }
        }

        ///
        /// The width of the viewport onto the content (in content coordinates).
        /// The value for this is actually computed by the main window's ZoomAndPanControl and update in the
        /// view-model so that the value can be shared with the overview window.
        ///
        public double ContentViewportWidth
        {
            get
            {
                return _contentViewportWidth;
            }
            set
            {
                _contentViewportWidth = value;

                OnPropertyChanged();
            }
        }

        ///
        /// The heigth of the viewport onto the content (in content coordinates).
        /// The value for this is actually computed by the main window's ZoomAndPanControl and update in the
        /// view-model so that the value can be shared with the overview window.
        ///
        public double ContentViewportHeight
        {
            get
            {
                return _contentViewportHeight;
            }
            set
            {
                _contentViewportHeight = value;

                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Called when the user has started to drag out a connector, thus creating a new connection.
        /// </summary>
        public ConnectionViewModel ConnectionDragStarted(ConnectorViewModel draggedOutConnector, Point curDragPoint)
        {
            //
            // Create a new connection to add to the view-model.
            //
            var connection = new ConnectionViewModel();

            if (draggedOutConnector.Type == ConnectorType.Output)
            {
                //
                // The user is dragging out a source connector (an output) and will connect it to a destination connector (an input).
                //
                connection.SourceConnector = draggedOutConnector;
                connection.DestConnectorHotspot = curDragPoint;
            }
            else
            {
                //
                // The user is dragging out a destination connector (an input) and will connect it to a source connector (an output).
                //
                connection.DestConnector = draggedOutConnector;
                connection.SourceConnectorHotspot = curDragPoint;
            }

            //
            // Add the new connection to the view-model.
            //
            Network.Connections.Add(connection);

            return connection;
        }

        /// <summary>
        /// Called to query the application for feedback while the user is dragging the connection.
        /// </summary>
        public void QueryConnnectionFeedback(ConnectorViewModel draggedOutConnector, ConnectorViewModel draggedOverConnector, out object feedbackIndicator, out bool connectionOk)
        {
            if (draggedOutConnector == draggedOverConnector)
            {
                //
                // Can't connect to self!
                // Provide feedback to indicate that this connection is not valid!
                //
                feedbackIndicator = new ConnectionBadIndicator();
                connectionOk = false;
            }
            else
            {
                var sourceConnector = draggedOutConnector;
                var destConnector = draggedOverConnector;

                //
                // Only allow connections from output connector to input connector (ie each
                // connector must have a different type).
                // Also only allocation from one node to another, never one node back to the same node.
                //
                connectionOk = sourceConnector.ParentNode != destConnector.ParentNode &&
                                 sourceConnector.Type != destConnector.Type;

                if (connectionOk)
                {
                    //
                    // Yay, this is a valid connection!
                    // Provide feedback to indicate that this connection is ok!
                    //
                    feedbackIndicator = new ConnectionOkIndicator();
                }
                else
                {
                    //
                    // Connectors with the same connector type (eg input & input, or output & output)
                    // can't be connected.
                    // Only connectors with separate connector type (eg input & output).
                    // Provide feedback to indicate that this connection is not valid!
                    //
                    feedbackIndicator = new ConnectionBadIndicator();
                }
            }
        }

        /// <summary>
        /// Called as the user continues to drag the connection.
        /// </summary>
        public void ConnectionDragging(Point curDragPoint, ConnectionViewModel connection)
        {
            if (connection.DestConnector == null)
            {
                connection.DestConnectorHotspot = curDragPoint;
            }
            else
            {
                connection.SourceConnectorHotspot = curDragPoint;
            }
        }

        /// <summary>
        /// Called when the user has finished dragging out the new connection.
        /// </summary>
        public void ConnectionDragCompleted(ConnectionViewModel newConnection, ConnectorViewModel connectorDraggedOut, ConnectorViewModel connectorDraggedOver)
        {
            if (connectorDraggedOver == null)
            {
                //
                // The connection was unsuccessful.
                // Maybe the user dragged it out and dropped it in empty space.
                //
                Network.Connections.Remove(newConnection);
                return;
            }

            //
            // Only allow connections from output connector to input connector (ie each
            // connector must have a different type).
            // Also only allocation from one node to another, never one node back to the same node.
            //
            var connectionOk = connectorDraggedOut.ParentNode != connectorDraggedOver.ParentNode &&
                                connectorDraggedOut.Type != connectorDraggedOver.Type;

            if (!connectionOk)
            {
                //
                // Connections between connectors that have the same type,
                // eg input -> input or output -> output, are not allowed,
                // Remove the connection.
                //
                Network.Connections.Remove(newConnection);
                return;
            }

            //
            // The user has dragged the connection on top of another valid connector.
            //

            //
            // Remove any existing connection between the same two connectors.
            //
            var existingConnection = FindConnection(connectorDraggedOut, connectorDraggedOver);
            if (existingConnection != null)
            {
                Network.Connections.Remove(existingConnection);
            }

            //
            // Finalize the connection by attaching it to the connector
            // that the user dragged the mouse over.
            //
            if (newConnection.DestConnector == null)
            {
                newConnection.DestConnector = connectorDraggedOver;
            }
            else
            {
                newConnection.SourceConnector = connectorDraggedOver;
            }
        }

        /// <summary>
        /// Retrieve a connection between the two connectors.
        /// Returns null if there is no connection between the connectors.
        /// </summary>
        public ConnectionViewModel FindConnection(ConnectorViewModel connector1, ConnectorViewModel connector2)
        {
            Trace.Assert(connector1.Type != connector2.Type);

            //
            // Figure out which one is the source connector and which one is the
            // destination connector based on their connector types.
            //
            var sourceConnector = connector1.Type == ConnectorType.Output ? connector1 : connector2;
            var destConnector = connector1.Type == ConnectorType.Output ? connector2 : connector1;

            //
            // Now we can just iterate attached connections of the source
            // and see if it each one is attached to the destination connector.
            //

            foreach (var connection in sourceConnector.AttachedConnections)
            {
                if (connection.DestConnector == destConnector)
                {
                    //
                    // Found a connection that is outgoing from the source connector
                    // and incoming to the destination connector.
                    //
                    return connection;
                }
            }

            return null;
        }

        /// <summary>
        /// Delete the currently selected nodes from the view-model.
        /// </summary>
        public void DeleteSelectedNodes()
        {
            // Take a copy of the selected nodes list so we can delete nodes while iterating.
            var nodesCopy = Network.Nodes.ToArray();
            foreach (var node in nodesCopy)
            {
                if (node.IsSelected)
                {
                    DeleteNode(node);
                }
            }
        }

        /// <summary>
        /// Delete the node from the view-model.
        /// Also deletes any connections to or from the node.
        /// </summary>
        public void DeleteNode(NodeViewModel node)
        {
            //
            // Remove all connections attached to the node.
            //
            Network.Connections.RemoveRange(node.AttachedConnections);

            //
            // Remove the node from the network.
            //
            Network.Nodes.Remove(node);
        }

        /// <summary>
        /// Create a node and add it to the view-model.
        /// </summary>
        public NodeViewModel CreateNode(string name, Point nodeLocation, bool centerNode)
        {
            var node = new NodeViewModel(name);
            node.X = nodeLocation.X;
            node.Y = nodeLocation.Y;

            node.InputConnectors.Add(new ConnectorViewModel("In1"));
            node.InputConnectors.Add(new ConnectorViewModel("In2"));
            node.OutputConnectors.Add(new ConnectorViewModel("Out1"));
            node.OutputConnectors.Add(new ConnectorViewModel("Out2"));

            if (centerNode)
            {
                //
                // We want to center the node.
                //
                // For this to happen we need to wait until the UI has determined the
                // size based on the node's data-template.
                //
                // So we define an anonymous method to handle the SizeChanged event for a node.
                //
                // Note: If you don't declare sizeChangedEventHandler before initializing it you will get
                //       an error when you try and unsubscribe the event from within the event handler.
                //
                EventHandler<EventArgs> sizeChangedEventHandler = null;
                sizeChangedEventHandler =
                    delegate
                    {
                        //
                        // This event handler will be called after the size of the node has been determined.
                        // So we can now use the size of the node to modify its position.
                        //
                        node.X -= node.Size.Width / 2;
                        node.Y -= node.Size.Height / 2;

                        //
                        // Don't forget to unhook the event, after the initial centering of the node
                        // we don't need to be notified again of any size changes.
                        //
                        node.SizeChanged -= sizeChangedEventHandler;
                    };

                //
                // Now we hook the SizeChanged event so the anonymous method is called later
                // when the size of the node has actually been determined.
                //
                node.SizeChanged += sizeChangedEventHandler;
            }

            //
            // Add the node to the view-model.
            //
            Network.Nodes.Add(node);

            return node;
        }

        /// <summary>
        /// Utility method to delete a connection from the view-model.
        /// </summary>
        public void DeleteConnection(ConnectionViewModel connection) => Network.Connections.Remove(connection);

        #region Private Methods

        /// <summary>
        /// A function to conveniently populate the view-model with test data.
        /// </summary>
        private void PopulateWithTestData()
        {
            //
            // Create a network, the root of the view-model.
            //
            Network = new NetworkViewModel();

            //
            // Create some nodes and add them to the view-model.
            //
            var node1 = CreateNode("Node1", new Point(100, 60), false);
            var node2 = CreateNode("Node2", new Point(350, 80), false);

            //
            // Create a connection between the nodes.
            //
            var connection = new ConnectionViewModel();
            connection.SourceConnector = node1.OutputConnectors[0];
            connection.DestConnector = node2.InputConnectors[0];

            //
            // Add the connection to the view-model.
            //
            Network.Connections.Add(connection);
        }

        #endregion Private Methods
    }
}


text:
<!--
Copyright (C) 2010 Google Inc.
See COPYING for license.
-->
<project name="client-scheduler">
  <import file="${build.common.path}"/>
  <property name="libname" value="client-scheduler"/>
  <patternset id="srcs">
    <include name="org/waveprotocol/wave/client/scheduler/**"/>
  </patternset>
</project>


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Diagnostics;
using System.Text;

namespace Lidgren.Network
{
	public partial class NetIncomingMessage
	{
		/// <summary>
		/// Ensures the buffer can hold this number of bits
		/// </summary>
		private void InternalEnsureBufferSize(int numberOfBits)
		{
			int byteLen = ((numberOfBits + 7) >> 3);
			if (m_data == null)
			{
				m_data = new byte[byteLen];
				return;
			}
			if (m_data.Length < byteLen)
				Array.Resize<byte>(ref m_data, byteLen);
			return;
		}

		//
		// 1 bit
		//
		internal void Write(bool value)
		{
			InternalEnsureBufferSize(m_bitLength + 1);
			NetBitWriter.WriteByte((value ? (byte)1 : (byte)0), 1, m_data, m_bitLength);
			m_bitLength += 1;
		}

		//
		// 8 bit
		//
		internal void Write(byte source)
		{
			InternalEnsureBufferSize(m_bitLength + 8);
			NetBitWriter.WriteByte(source, 8, m_data, m_bitLength);
			m_bitLength += 8;
		}

		internal void Write(sbyte source)
		{
			InternalEnsureBufferSize(m_bitLength + 8);
			NetBitWriter.WriteByte((byte)source, 8, m_data, m_bitLength);
			m_bitLength += 8;
		}

		internal void Write(byte source, int numberOfBits)
		{
			NetException.Assert((numberOfBits > 0 && numberOfBits <= 8), "Write(byte, numberOfBits) can only write between 1 and 8 bits");
			InternalEnsureBufferSize(m_bitLength + numberOfBits);
			NetBitWriter.WriteByte(source, numberOfBits, m_data, m_bitLength);
			m_bitLength += numberOfBits;
		}

		internal void Write(byte[] source)
		{
			if (source == null)
				throw new ArgumentNullException("source");
			int bits = source.Length * 8;
			InternalEnsureBufferSize(m_bitLength + bits);
			NetBitWriter.WriteBytes(source, 0, source.Length, m_data, m_bitLength);
			m_bitLength += bits;
		}

		internal void Write(byte[] source, int offsetInBytes, int numberOfBytes)
		{
			if (source == null)
				throw new ArgumentNullException("source");
			int bits = numberOfBytes * 8;
			InternalEnsureBufferSize(m_bitLength + bits);
			NetBitWriter.WriteBytes(source, offsetInBytes, numberOfBytes, m_data, m_bitLength);
			m_bitLength += bits;
		}

		//
		// 16 bit
		//
		internal void Write(UInt16 source)
		{
			InternalEnsureBufferSize(m_bitLength + 16);
			NetBitWriter.WriteUInt32((uint)source, 16, m_data, m_bitLength);
			m_bitLength += 16;
		}

		internal void Write(UInt16 source, int numberOfBits)
		{
			NetException.Assert((numberOfBits > 0 && numberOfBits <= 16), "Write(ushort, numberOfBits) can only write between 1 and 16 bits");
			InternalEnsureBufferSize(m_bitLength + numberOfBits);
			NetBitWriter.WriteUInt32((uint)source, numberOfBits, m_data, m_bitLength);
			m_bitLength += numberOfBits;
		}

		internal void Write(Int16 source)
		{
			InternalEnsureBufferSize(m_bitLength + 16);
			NetBitWriter.WriteUInt32((uint)source, 16, m_data, m_bitLength);
			m_bitLength += 16;
		}

		//
		// 32 bit
		//
#if UNSAFE
		internal unsafe void Write(Int32 source)
		{
			EnsureBufferSize(m_bitLength + 32);

			// can write fast?
			if (m_bitLength % 8 == 0)
			{
				fixed (byte* numRef = &Data[m_bitLength / 8])
				{
					*((int*)numRef) = source;
				}
			}
			else
			{
				NetBitWriter.WriteUInt32((UInt32)source, 32, Data, m_bitLength);
			}
			m_bitLength += 32;
		}
#else
		internal void Write(Int32 source)
		{
			InternalEnsureBufferSize(m_bitLength + 32);
			NetBitWriter.WriteUInt32((UInt32)source, 32, m_data, m_bitLength);
			m_bitLength += 32;
		}
#endif

#if UNSAFE
		internal unsafe void Write(UInt32 source)
		{
			EnsureBufferSize(m_bitLength + 32);

			// can write fast?
			if (m_bitLength % 8 == 0)
			{
				fixed (byte* numRef = &Data[m_bitLength / 8])
				{
					*((uint*)numRef) = source;
				}
			}
			else
			{
				NetBitWriter.WriteUInt32(source, 32, Data, m_bitLength);
			}

			m_bitLength += 32;
		}
#else
		internal void Write(UInt32 source)
		{
			InternalEnsureBufferSize(m_bitLength + 32);
			NetBitWriter.WriteUInt32(source, 32, m_data, m_bitLength);
			m_bitLength += 32;
		}
#endif

		internal void Write(UInt32 source, int numberOfBits)
		{
			NetException.Assert((numberOfBits > 0 && numberOfBits <= 32), "Write(uint, numberOfBits) can only write between 1 and 32 bits");
			InternalEnsureBufferSize(m_bitLength + numberOfBits);
			NetBitWriter.WriteUInt32(source, numberOfBits, m_data, m_bitLength);
			m_bitLength += numberOfBits;
		}

		internal void Write(Int32 source, int numberOfBits)
		{
			NetException.Assert((numberOfBits > 0 && numberOfBits <= 32), "Write(int, numberOfBits) can only write between 1 and 32 bits");
			InternalEnsureBufferSize(m_bitLength + numberOfBits);

			if (numberOfBits != 32)
			{
				// make first bit sign
				int signBit = 1 << (numberOfBits - 1);
				if (source < 0)
					source = (-source - 1) | signBit;
				else
					source &= (~signBit);
			}

			NetBitWriter.WriteUInt32((uint)source, numberOfBits, m_data, m_bitLength);

			m_bitLength += numberOfBits;
		}

		//
		// 64 bit
		//
		internal void Write(UInt64 source)
		{
			InternalEnsureBufferSize(m_bitLength + 64);
			NetBitWriter.WriteUInt64(source, 64, m_data, m_bitLength);
			m_bitLength += 64;
		}

		internal void Write(UInt64 source, int numberOfBits)
		{
			InternalEnsureBufferSize(m_bitLength + numberOfBits);
			NetBitWriter.WriteUInt64(source, numberOfBits, m_data, m_bitLength);
			m_bitLength += numberOfBits;
		}

		internal void Write(Int64 source)
		{
			InternalEnsureBufferSize(m_bitLength + 64);
			ulong usource = (ulong)source;
			NetBitWriter.WriteUInt64(usource, 64, m_data, m_bitLength);
			m_bitLength += 64;
		}

		internal void Write(Int64 source, int numberOfBits)
		{
			InternalEnsureBufferSize(m_bitLength + numberOfBits);
			ulong usource = (ulong)source;
			NetBitWriter.WriteUInt64(usource, numberOfBits, m_data, m_bitLength);
			m_bitLength += numberOfBits;
		}

		//
		// Floating point
		//
#if UNSAFE
		internal unsafe void Write(float source)
		{
			uint val = *((uint*)&source);
#if BIGENDIAN
				val = NetUtility.SwapByteOrder(val);
#endif
			Write(val);
		}
#else
		internal void Write(float source)
		{
			byte[] val = BitConverter.GetBytes(source);
#if BIGENDIAN
			// swap byte order
			byte tmp = val[3];
			val[3] = val[0];
			val[0] = tmp;
			tmp = val[2];
			val[2] = val[1];
			val[1] = tmp;
#endif
			Write(val);
		}
#endif

#if UNSAFE
		internal unsafe void Write(double source)
		{
			ulong val = *((ulong*)&source);
#if BIGENDIAN
			val = NetUtility.SwapByteOrder(val);
#endif
			Write(val);
		}
#else
		internal void Write(double source)
		{
			byte[] val = BitConverter.GetBytes(source);
#if BIGENDIAN
			// 0 1 2 3   4 5 6 7

			// swap byte order
			byte tmp = val[7];
			val[7] = val[0];
			val[0] = tmp;

			tmp = val[6];
			val[6] = val[1];
			val[1] = tmp;

			tmp = val[5];
			val[5] = val[2];
			val[2] = tmp;

			tmp = val[4];
			val[4] = val[3];
			val[3] = tmp;
#endif
			Write(val);
		}
#endif

		//
		// Variable bits
		//

		/// <summary>
		/// Write Base128 encoded variable sized unsigned integer
		/// </summary>
		/// <returns>number of bytes written</returns>
		internal int WriteVariableUInt32(uint value)
		{
			int retval = 1;
			uint num1 = (uint)value;
			while (num1 >= 0x80)
			{
				this.Write((byte)(num1 | 0x80));
				num1 = num1 >> 7;
				retval++;
			}
			this.Write((byte)num1);
			return retval;
		}

		/// <summary>
		/// Write Base128 encoded variable sized signed integer
		/// </summary>
		/// <returns>number of bytes written</returns>
		internal int WriteVariableInt32(int value)
		{
			int retval = 1;
			uint num1 = (uint)((value << 1) ^ (value >> 31));
			while (num1 >= 0x80)
			{
				this.Write((byte)(num1 | 0x80));
				num1 = num1 >> 7;
				retval++;
			}
			this.Write((byte)num1);
			return retval;
		}

		/// <summary>
		/// Write Base128 encoded variable sized unsigned integer
		/// </summary>
		/// <returns>number of bytes written</returns>
		internal int WriteVariableUInt64(UInt64 value)
		{
			int retval = 1;
			UInt64 num1 = (UInt64)value;
			while (num1 >= 0x80)
			{
				this.Write((byte)(num1 | 0x80));
				num1 = num1 >> 7;
				retval++;
			}
			this.Write((byte)num1);
			return retval;
		}

		/// <summary>
		/// Compress (lossy) a float in the range -1..1 using numberOfBits bits
		/// </summary>
		internal void WriteSignedSingle(float value, int numberOfBits)
		{
			NetException.Assert(((value >= -1.0) && (value <= 1.0)), " WriteSignedSingle() must be passed a float in the range -1 to 1; val is " + value);

			float unit = (value + 1.0f) * 0.5f;
			int maxVal = (1 << numberOfBits) - 1;
			uint writeVal = (uint)(unit * (float)maxVal);

			Write(writeVal, numberOfBits);
		}

		/// <summary>
		/// Compress (lossy) a float in the range 0..1 using numberOfBits bits
		/// </summary>
		internal void WriteUnitSingle(float value, int numberOfBits)
		{
			NetException.Assert(((value >= 0.0) && (value <= 1.0)), " WriteUnitSingle() must be passed a float in the range 0 to 1; val is " + value);

			int maxValue = (1 << numberOfBits) - 1;
			uint writeVal = (uint)(value * (float)maxValue);

			Write(writeVal, numberOfBits);
		}

		/// <summary>
		/// Compress a float within a specified range using a certain number of bits
		/// </summary>
		internal void WriteRangedSingle(float value, float min, float max, int numberOfBits)
		{
			NetException.Assert(((value >= min) && (value <= max)), " WriteRangedSingle() must be passed a float in the range MIN to MAX; val is " + value);

			float range = max - min;
			float unit = ((value - min) / range);
			int maxVal = (1 << numberOfBits) - 1;
			Write((UInt32)((float)maxVal * unit), numberOfBits);
		}

		/// <summary>
		/// Writes an integer with the least amount of bits need for the specified range
		/// Returns number of bits written
		/// </summary>
		internal int WriteRangedInteger(int min, int max, int value)
		{
			NetException.Assert(value >= min && value <= max, "Value not within min/max range!");

			uint range = (uint)(max - min);
			int numBits = NetUtility.BitsToHoldUInt(range);

			uint rvalue = (uint)(value - min);
			Write(rvalue, numBits);

			return numBits;
		}

		/// <summary>
		/// Write a string
		/// </summary>
		internal void Write(string source)
		{
			if (string.IsNullOrEmpty(source))
			{
				InternalEnsureBufferSize(m_bitLength + 8);
				WriteVariableUInt32(0);
				return;
			}

			byte[] bytes = Encoding.UTF8.GetBytes(source);

			// determine number of bytes to store length
			int lenBytesNeeded = 1;
			uint num1 = (uint)bytes.Length;
			while (num1 >= 0x80)
			{
				num1 = num1 >> 7;
				lenBytesNeeded++;
			}
			InternalEnsureBufferSize(m_bitLength + ((bytes.Length + lenBytesNeeded) * 8));

			WriteVariableUInt32((uint)bytes.Length);
			Write(bytes);
		}

		/// <summary>
		/// Writes an endpoint description
		/// </summary>
		internal void Write(IPEndPoint endPoint)
		{
			byte[] bytes = endPoint.Address.GetAddressBytes();
			Write((byte)bytes.Length);
			Write(bytes);
			Write((ushort)endPoint.Port);
		}

		/// <summary>
		/// Pads data with enough bits to reach a full byte. Decreases cpu usage for subsequent byte writes.
		/// </summary>
		internal void WritePadBits()
		{
			m_bitLength = ((m_bitLength + 7) / 8) * 8;
			InternalEnsureBufferSize(m_bitLength);
		}

		/// <summary>
		/// Pads data with the specified number of bits.
		/// </summary>
		internal void WritePadBits(int numberOfBits)
		{
			m_bitLength += numberOfBits;
			InternalEnsureBufferSize(m_bitLength);
		}
	}
}


text:
/**
 * @fileoverview Global renderer and decorator registry.
 */

goog.provide('goog.ui.registry');

goog.require('goog.asserts');
goog.require('goog.dom.classlist');
goog.require('goog.object');
goog.requireType('goog.ui.Component');
goog.requireType('goog.ui.ControlRenderer');

/**
 * Given a {@link goog.ui.Component} constructor, returns an instance of its
 * default renderer.  If the default renderer is a singleton, returns the
 * singleton instance; otherwise returns a new instance of the renderer class.
 * @param {!Function} componentCtor Component constructor function (for example
 *     `goog.ui.Button`).
 * @return {?goog.ui.ControlRenderer} Renderer instance (for example the
 *     singleton instance of `goog.ui.ButtonRenderer`), or null if
 *     no default renderer was found.
 */
goog.ui.registry.getDefaultRenderer = function(componentCtor) {
  'use strict';
  // TODO(user): This should probably be implemented with a `WeakMap`.
  // Locate the default renderer based on the constructor's unique ID.  If no
  // renderer is registered for this class, walk up the superClass_ chain.
  var key;
  var /** ?Function|undefined */ ctor = componentCtor;
  var /** ?Function|undefined */ rendererCtor;
  while (ctor) {
    key = goog.getUid(ctor);
    if ((rendererCtor = goog.ui.registry.defaultRenderers_[key])) break;
    ctor = /** @type {?Function|undefined} */ (goog.object.getSuperClass(ctor));
  }

  // If the renderer has a static getInstance method, return the singleton
  // instance; otherwise create and return a new instance.
  if (rendererCtor) {
    return typeof rendererCtor.getInstance === 'function' ?
        rendererCtor.getInstance() :
        new rendererCtor();
  }

  return null;
};

/**
 * Sets the default renderer for the given {@link goog.ui.Component}
 * constructor.
 * @param {Function} componentCtor Component constructor function (for example
 *     `goog.ui.Button`).
 * @param {Function} rendererCtor Renderer constructor function (for example
 *     `goog.ui.ButtonRenderer`).
 * @throws {Error} If the arguments aren't functions.
 */
goog.ui.registry.setDefaultRenderer = function(componentCtor, rendererCtor) {
  'use strict';
  // In this case, explicit validation has negligible overhead (since each
  // renderer is only registered once), and helps catch subtle bugs.
  if (typeof componentCtor !== 'function') {
    throw new Error('Invalid component class ' + componentCtor);
  }
  if (typeof rendererCtor !== 'function') {
    throw new Error('Invalid renderer class ' + rendererCtor);
  }

  // Map the component constructor's unique ID to the renderer constructor.
  var key = goog.getUid(componentCtor);
  goog.ui.registry.defaultRenderers_[key] = rendererCtor;
};

/**
 * Returns the {@link goog.ui.Component} instance created by the decorator
 * factory function registered for the given CSS class name, or null if no
 * decorator factory function was found.
 * @param {string} className CSS class name.
 * @return {goog.ui.Component?} Component instance.
 */
goog.ui.registry.getDecoratorByClassName = function(className) {
  'use strict';
  return className in goog.ui.registry.decoratorFunctions_ ?
      goog.ui.registry.decoratorFunctions_[className]() :
      null;
};

/**
 * Maps a CSS class name to a function that returns a new instance of
 * {@link goog.ui.Component} or a subclass, suitable to decorate an element
 * that has the specified CSS class.
 * @param {string} className CSS class name.
 * @param {Function} decoratorFn No-argument function that returns a new
 *     instance of a {@link goog.ui.Component} to decorate an element.
 * @throws {Error} If the class name or the decorator function is invalid.
 */
goog.ui.registry.setDecoratorByClassName = function(className, decoratorFn) {
  'use strict';
  // In this case, explicit validation has negligible overhead (since each
  // decorator  is only registered once), and helps catch subtle bugs.
  if (!className) {
    throw new Error('Invalid class name ' + className);
  }
  if (typeof decoratorFn !== 'function') {
    throw new Error('Invalid decorator function ' + decoratorFn);
  }

  goog.ui.registry.decoratorFunctions_[className] = decoratorFn;
};

/**
 * Returns an instance of {@link goog.ui.Component} or a subclass suitable to
 * decorate the given element, based on its CSS class.
 *
 * TODO(nnaze): Type of element should be {!Element}.
 *
 * @param {Element} element Element to decorate.
 * @return {goog.ui.Component?} Component to decorate the element (null if
 *     none).
 */
goog.ui.registry.getDecorator = function(element) {
  'use strict';
  var decorator;
  goog.asserts.assert(element);
  var classNames = goog.dom.classlist.get(element);
  for (var i = 0, len = classNames.length; i < len; i++) {
    if ((decorator = goog.ui.registry.getDecoratorByClassName(classNames[i]))) {
      return decorator;
    }
  }
  return null;
};

/**
 * Resets the global renderer and decorator registry.
 */
goog.ui.registry.reset = function() {
  'use strict';
  goog.ui.registry.defaultRenderers_ = {};
  goog.ui.registry.decoratorFunctions_ = {};
};

/**
 * Map of {@link goog.ui.Component} constructor unique IDs to the constructors
 * of their default {@link goog.ui.Renderer}s.
 * @type {Object}
 * @private
 */
goog.ui.registry.defaultRenderers_ = {};

/**
 * Map of CSS class names to registry factory functions.  The keys are
 * class names.  The values are function objects that return new instances
 * of {@link goog.ui.registry} or one of its subclasses, suitable to
 * decorate elements marked with the corresponding CSS class.  Used by
 * containers while decorating their children.
 * @type {Object}
 * @private
 */
goog.ui.registry.decoratorFunctions_ = {};


text:
ALTER TABLE users
ADD COLUMN createdate_old VARCHAR(8) NULL;

update users
  set createdate_old = TO_CHAR(createdate,'YYYYMMDD');

ALTER TABLE users
  DROP COLUMN createdate;

ALTER TABLE users
  RENAME COLUMN createdate_old TO createdate;


text:
/**
 * @author Vladimir Budilov
 *
 * This is the entry-way into the routing logic. This is the first component that's called when the app
 * loads.
 *
 */
import {Component, OnInit} from "@angular/core";
import {AwsUtil} from "./service/aws.service";
import {UserLoginService, CognitoUtil, LoggedInCallback} from "./service/cognito.service";

@Component({
    selector: 'app-root',
    templateUrl: 'template/app.html'
})
export class AppComponent implements OnInit, LoggedInCallback {

    constructor(public awsUtil: AwsUtil, public userService: UserLoginService, public cognito: CognitoUtil) {
        console.log("AppComponent: constructor");
    }

    ngOnInit() {
        console.log("AppComponent: Checking if the user is already authenticated");
        this.userService.isAuthenticated(this);
    }

    isLoggedIn(message: string, isLoggedIn: boolean) {
        console.log("AppComponent: the user is authenticated: " + isLoggedIn);
        let mythis = this;
        this.cognito.getIdToken({
            callback() {

            },
            callbackWithParam(token: any) {
                // Include the passed-in callback here as well so that it's executed downstream
                console.log("AppComponent: calling initAwsService in callback")
                mythis.awsUtil.initAwsService(null, isLoggedIn, token);
            }
        });
    }
}