text:
import { boxesReducer } from './boxes.reducer';
import { boxesInitialState } from './boxes.init';
//import { Boxes } from './boxes.interfaces';
import { LoadSuccess } from './boxes.actions';

describe('boxesReducer', () => {
  it('should work', () => {
    //    const state: Boxes = {};
    //    const action: LoadSuccess = { type: 'DATA_LOADED', payload: {} };
    //    const actual = boxesReducer(state, action);
    //    expect(actual).toEqual({});
  });
});


text:
import os
import re
import subprocess
import sys

def GetDefaultConcurrentLinks():
    # Inherit the legacy environment variable for people that have set it in GYP.
    pool_size = int(os.getenv('GYP_LINK_CONCURRENCY', 0))
    if pool_size:
        return pool_size

    if sys.platform in ('win32', 'cygwin'):
        import ctypes

        class MEMORYSTATUSEX(ctypes.Structure):
            _fields_ = [
                ("dwLength", ctypes.c_ulong),
                ("dwMemoryLoad", ctypes.c_ulong),
                ("ullTotalPhys", ctypes.c_ulonglong),
                ("ullAvailPhys", ctypes.c_ulonglong),
                ("ullTotalPageFile", ctypes.c_ulonglong),
                ("ullAvailPageFile", ctypes.c_ulonglong),
                ("ullTotalVirtual", ctypes.c_ulonglong),
                ("ullAvailVirtual", ctypes.c_ulonglong),
                ("sullAvailExtendedVirtual", ctypes.c_ulonglong),
            ]

        stat = MEMORYSTATUSEX(dwLength=ctypes.sizeof(MEMORYSTATUSEX))
        ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))

        mem_limit = max(1, stat.ullTotalPhys / (4 * (2**30)))  # total / 4GB
        hard_cap = max(1, int(os.getenv('GYP_LINK_CONCURRENCY_MAX', 2**32)))
        return min(mem_limit, hard_cap)
    elif sys.platform.startswith('linux'):
        if os.path.exists("/proc/meminfo"):
            with open("/proc/meminfo") as meminfo:
                memtotal_re = re.compile(r'^MemTotal:\s*(\d*)\s*kB')
                for line in meminfo:
                    match = memtotal_re.match(line)
                    if not match:
                        continue
                    # Allow 8Gb per link on Linux because Gold is quite memory hungry
                    return max(1, int(match.group(1)) / (8 * (2**20)))
        return 1
    elif sys.platform == 'darwin':
        try:
            avail_bytes = int(
                subprocess.check_output(['sysctl', '-n', 'hw.memsize']))
            # A static library debug build of Chromium's unit_tests takes ~2.7GB, so
            # 4GB per ld process allows for some more bloat.
            return max(1, avail_bytes / (4 * (2**30)))  # total / 4GB
        except Exception:
            return 1
    else:
        # TODO(scottmg): Implement this for other platforms.
        return 1

print GetDefaultConcurrentLinks()

redpajama_set_name: RedPajamaGithub


text:
package com.p6spy.engine.logging;

import java.util.regex.Pattern;

import com.p6spy.engine.spy.P6LoadableOptions;

public interface P6LogLoadableOptions extends P6LoadableOptions, P6LogOptionsMBean {

  // these we don't need to be exposed via JMX

  void setExcludebinary(String excludebinary);

  void setFilter(String filter);

  void setExecutionThreshold(String executionThreshold);

  Pattern getIncludeExcludePattern();

  Pattern getSQLExpressionPattern();

}


text:
.. _release-3004-1:

=========================
Salt 3004.1 Release Notes
=========================

Version 3004.1 is a CVE security fix release for :ref:`3004 <release-3004>`.

Important notice about upgrading
--------------------------------

Version 3004.1 is a security release. 3004.1 minions are not able to
communicate with masters older than 3004.1. You must upgrade your masters
before upgrading minions.

Minion authentication security
------------------------------

Authentication between masters and minions rely on public/private key
encryption and message signing. To secure minion authentication before you must
pre-seed the master's public key on minions. To pre-seed the minions' master
key, place a copy of the master's public key in the minion's pki directory as
``minion_master.pub``.

Security
--------

- Sign authentication replies to prevent MiTM (cve-2022-22935)
- Prevent job and fileserver replays (cve-2022-22936)
- Sign pillar data to prevent MiTM attacks. (cve-2202-22934)
- Fixed targeting bug, especially visible when using syndic and user auth. (CVE-2022-22941) (#60413)
- Fix denial of service in junos ifconfig output parsing.


text:
/*!
 * Export the middleware.
 * See discussion in Connect pull request #954 for more details
 * https://github.com/senchalabs/connect/pull/954.
 */
module.exports = urlNotFound;

/**
 * Convert any request not handled so far to a 404 error
 * to be handled by error-handling middleware.
 * @header loopback.urlNotFound()
 */
function urlNotFound() {
  return function raiseUrlNotFoundError(req, res, next) {
    var error = new Error('Cannot ' + req.method + ' ' + req.url);
    error.status = 404;
    next(error);
  };
}


text:
package com.timelesssoftware.popularmovies.UI.Fragments;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.timelesssoftware.popularmovies.R;

/**
 *
A fragment that shows a list of items as a modal bottom sheet.

 *
You can show this modal bottom sheet from your activity like this:

 *

 *     BottomSheetFragment.newInstance(30).show(getSupportFragmentManager(), "dialog");
 *

 *
You activity (or fragment) needs to implement {@link BottomSheetFragment.Listener}.

 */
public class BottomSheetFragment extends BottomSheetDialogFragment {

    // TODO: Customize parameter argument names
    private static final String ARG_ITEM_COUNT = "item_count";
    private Listener mListener;

    // TODO: Customize parameters
    public static BottomSheetFragment newInstance(int itemCount) {
        final BottomSheetFragment fragment = new BottomSheetFragment();
        final Bundle args = new Bundle();
        args.putInt(ARG_ITEM_COUNT, itemCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_moviereview_list_dialog, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        final Fragment parent = getParentFragment();
        if (parent != null) {
            mListener = (Listener) parent;
        } else {
            mListener = (Listener) context;
        }
    }

    @Override
    public void onDetach() {
        mListener = null;
        super.onDetach();
    }

    public interface Listener {
        void onMovieReviewClicked(int position);
    }
}


text:
@echo off
echo *** Building Microsoft.Recognizers.Text
setlocal
setlocal enabledelayedexpansion
setlocal enableextensions

for /f "usebackq tokens=*" %%i in (`..\packages\vswhere.2.2.7\tools\vswhere -latest -products * -requires Microsoft.Component.MSBuild -property installationPath`) do (
  set MSBuildDir=%%i\MSBuild\15.0\Bin\
)

if not exist ..\nuget mkdir ..\nuget
if exist ..\nuget\Microsoft.Recognizers.Text*.nupkg erase /s ..\nuget\Microsoft.Recognizers.Text*.nupkg
"%MSBuildDir%\MSBuild\15.0\Bin\MSBuild.exe" /property:Configuration=release Microsoft.Recognizers.Text.csproj
for /f %%v in ('powershell -noprofile "(Get-Command .\bin\release\netstandard2.0\Microsoft.Recognizers.Text.dll).FileVersionInfo.FileVersion"') do set basicVersion=%%v
..\packages\NuGet.CommandLine.4.3.0\tools\NuGet.exe pack Microsoft.Recognizers.Text.nuspec -symbols -properties version=%basicVersion% -OutputDirectory ..\nuget

set error=%errorlevel%
set packageName=Microsoft.Recognizers.Text
if %error% NEQ 0 (
	echo *** Failed to build %packageName%
	exit /b %error%
) else (
	echo *** Succeeded to build %packageName%
)


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Science new ser. , 18:438. 1903

#### Original name
null

### Remarks
null


text:
import pytest

from parsimonious.exceptions import UndefinedLabel
from parsimonious.expressions import Compound

from grammaropt.grammar import build_grammar
from grammaropt.grammar import extract_rules_from_grammar
from grammaropt.grammar import Walker
from grammaropt.grammar import DeterministicWalker
from grammaropt.grammar import _Decision
from grammaropt.grammar import _rule_depth
from grammaropt.grammar import Vectorizer
from grammaropt.terminal_types import Int

arith = r"""
    S = (T "+" S) / (T "*" S) / (T "/" S) / T
    T = (po S pc) / ("sin" po S pc) / ("cos" po S pc) / ("exp" po S pc) / "x" / int
    po = "("
    pc = ")"
"""

class DummyWalker(Walker):
    def next_rule(self, rules, depth=0):
        for r in rules:
            if not isinstance(r, Compound):
                return r
        return r

    def next_value(self, rule):
        return "1"

def test_build_grammar():
    rules = r"""
        a = (b c) / b / d
        b = "(" b e ")"
        c = ")" c d "("
    """
    with pytest.raises(UndefinedLabel):
        grammar = build_grammar(rules)
    types = {"d": Int(1, 10), "e": Int(1, 10)}
    grammar = build_grammar(rules, types=types)
    assert "e" in grammar
    assert "d" in grammar
    assert type(grammar["e"]) == Int
    assert type(grammar["d"]) == Int

def test_extract_rules_from_grammar():
    types = {"int": Int(1, 10)}
    grammar = build_grammar(arith, types=types)
    rules = extract_rules_from_grammar(grammar)
    assert len(rules) == 19

def test_walker():
    types = {"int": Int(1, 10)}
    grammar = build_grammar(arith, types=types)
    wl = DummyWalker(grammar)
    wl.walk()
    assert wl.terminals == ["x"]
    wl.walk()
    assert wl.terminals == ["x"]

def test_deterministic_walker():
    types = {"int": Int(1, 10)}
    grammar = build_grammar(arith, types=types)
    dec = [
        _Decision(rule=grammar["S"], choice=grammar["T"]),
        _Decision(rule=grammar["T"], choice=grammar["int"]),
        _Decision(rule=grammar["int"], choice=5),
    ]
    expr = "5"
    wl = DeterministicWalker(grammar, expr)
    for _ in range(2):
        wl.walk()
        assert wl.decisions == dec
        assert wl.terminals == [5]
    expr = "x+cos(x+5)"
    wl = DeterministicWalker(grammar, expr)
    for _ in range(2):
        wl.walk()
        assert len(wl.decisions) == 9
        assert wl.terminals == ["x", "+", "cos", "(", "x", "+", 5, ")"]

def test_rule_depth():
    types = {"int": Int(1, 10)}
    grammar = build_grammar(arith, types=types)
    assert _rule_depth(grammar["S"]) == 2  # S -> T -> "x"
    assert _rule_depth(grammar["T"]) == 1  # T -> "x"
    assert _rule_depth(grammar["int"]) == 0

def test_vectorizer():
    types = {"int": Int(1, 10)}
    grammar = build_grammar(arith, types=types)
    vect = Vectorizer(grammar, pad=True)
    doc = ["x+1", "x+2", "(x+1)*(x+3)"]
    with pytest.raises(AssertionError):
        vect.transform(doc)

    rules = r"""
        S = (T "+" S) / (T "*" S) / (T "/" S) / T
        T = (po S pc) / ("sin" po S pc) / ("cos" po S pc) / ("exp" po S pc) / "x" / int
        po = "("
        pc = ")"
        int = "1" / "2" / "3"
    """
    grammar = build_grammar(rules)
    vect = Vectorizer(grammar, pad=True)
    toks = vect.transform(doc)
    assert len(toks) == len(doc)
    doc_ = vect.inverse_transform(toks)
    assert doc_ == doc

    vect = Vectorizer(grammar, pad=True, max_length=5)
    assert vect.inverse_transform(vect.transform(["x+1"])) == ["x+1"]
    assert vect.inverse_transform(vect.transform(["x+1", "2+x"])) == ["x+1", "2+x"]
    with pytest.raises(AssertionError):
        vect.transform(["(x+1)*(x+3)"])

    vect = Vectorizer(grammar, pad=True, max_length=15)
    assert vect.inverse_transform(vect.transform(doc)) == doc
    toks = vect.transform(doc)
    assert all([len(t) == 15 for t in toks])


text:
/**
 * Created by szhernovoy on 10.01.2017.
 */
package ru.szhernovoy.dbase;


text:
package edu.cmu.ml.rtw.generic.model;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.function.Function;

import org.platanios.learn.classification.LogisticRegressionAdaGrad;
import org.platanios.learn.data.DataSet;
import org.platanios.learn.data.PredictedDataInstance;
import org.platanios.learn.math.matrix.SparseVector;
import org.platanios.learn.math.matrix.Vector;
import org.platanios.learn.math.matrix.VectorNorm;

import edu.cmu.ml.rtw.generic.data.Context;
import edu.cmu.ml.rtw.generic.data.annotation.Datum;
import edu.cmu.ml.rtw.generic.data.annotation.Datum.Tools.LabelIndicator;
import edu.cmu.ml.rtw.generic.data.annotation.DatumContext;
import edu.cmu.ml.rtw.generic.data.feature.DataFeatureMatrix;
import edu.cmu.ml.rtw.generic.model.evaluation.metric.SupervisedModelEvaluation;
import edu.cmu.ml.rtw.generic.parse.Assignment;
import edu.cmu.ml.rtw.generic.parse.AssignmentList;
import edu.cmu.ml.rtw.generic.parse.Obj;
import edu.cmu.ml.rtw.generic.util.OutputWriter;
import edu.cmu.ml.rtw.generic.util.Pair;
import edu.cmu.ml.rtw.generic.util.PlataniosUtil;

/**
 * SupervisedModelAreg is a wrapper around Platanios'
 * 'learn' library AdaGrad implementation of binary
 * logistic regression.
 *
 * Parameters:
 *  l1 - l1-regularization hyper parameter
 *
 *  l2 - l2-regularization hyper parameter
 *
 *  convergenceEpsilon - training procedure terminates if the weight
 *  change in an iteration is below this value
 *
 *  maxEvaluationConstantIterations - maximum number of training iterations during
 *  which the test evaluations can be constant without stopping the training procedure
 *  (only works if computeTestEvaluations is true)
 *
 *  maxTrainingExamples - maximum number of examples that are passed over by AdaGrad
 *
 *  batchSize - number of examples in each AdaGrad mini-batch iteration
 *
 *  evaluationIterations - Number of iterations after which evaluations are computed
 *
 *  weightedLabels - indicates whether weighted labels should be used (for EM... but from
 *  the theory, it seems to me that logistic regression cannot be used as part
 *  of an EM procedure in this way because it is not a generative model.  Should
 *  use CEM with non-weighted labels instead).
 *
 *  classificationThreshold - posterior threshold above which an example is labeled
 *  as positive
 *
 *  computeTestEvaluations - indicates whether test evaluations should be computed
 *  after every evaluationIterations iterations.
 *
 * @author Bill McDowell
 *
 * @param <D>
 * @param <L>
 */
public class SupervisedModelAreg<D extends Datum<L>, L> extends SupervisedModel<D, L> {
	private double l1;
	private double l2;
	private double convergenceEpsilon = -1.0;
	private int maxEvaluationConstantIterations = 100000;
	private double maxTrainingExamples = 10000;
	private int batchSize = 100;
	private int evaluationIterations = 500;
	private boolean weightedLabels = false;
	private double classificationThreshold = 0.5;
	private boolean computeTestEvaluations = true;
	private String[] hyperParameterNames = { "l1", "l2", "convergenceEpsilon", "maxEvaluationConstantIterations", "maxTrainingExamples", "batchSize", "evaluationIterations", "weightedLabels", "classificationThreshold", "computeTestEvaluations" };

	private LogisticRegressionAdaGrad classifier;
	private Vector classifierWeights;

	private Map<Integer, String> nonZeroFeatureNames;

	public SupervisedModelAreg() {

	}

	public SupervisedModelAreg(DatumContext<D, L> context) {
		this.context = context;
	}

	@Override
	public boolean train(DataFeatureMatrix<D, L> data, DataFeatureMatrix<D, L> testData, List<SupervisedModelEvaluation<D, L>> evaluations) {
		OutputWriter output = data.getData().getDatumTools().getDataTools().getOutputWriter();

		if (this.validLabels.size() > 2 || !this.validLabels.contains(true)) {
			output.debugWriteln("ERROR: Areg only supports binary classification.");
			return false;
		}

		@SuppressWarnings("unchecked")
		DataSet<PredictedDataInstance<Vector, Double>> plataniosData = PlataniosUtil.makePlataniosDataSet((DataFeatureMatrix<Datum<Boolean>, Boolean>)data, this.weightedLabels, 1.0/5.0, true, false);

		List<Double> initEvaluationValues = new ArrayList<Double>();
		for (int i = 0; i < evaluations.size(); i++) {
			initEvaluationValues.add(0.0);
		}

		//int iterationsPerDataSet = plataniosData.size()/this.batchSize;
		int maximumIterations =  (int)(this.maxTrainingExamples/this.batchSize);// (int)Math.floor(this.maxDataSetRuns*iterationsPerDataSet);

		NumberFormat format = new DecimalFormat("#0.000000");

		output.debugWriteln("Areg training platanios model...");

		/*FIXME Remove if (data.getReferenceName().contains("_business_business_operation") && Double.compare(l2, .000001) == 0) {
			StringBuilder str = new StringBuilder();
			for (int i = 0; i < plataniosData.size(); i++) {
				str.append(plataniosData.get(i).name() + "\t" + plataniosData.get(i).label()).append("\n");
			}
			output.debugWriteln(str.toString());
			System.exit(0);
		}*/

		SupervisedModel<D, L> thisModel = this;
		this.classifier =
				new LogisticRegressionAdaGrad.Builder(plataniosData.get(0).features().size())
					.sparse(true)
					.useBiasTerm(true)
					.useL1Regularization(this.l1 > 0)
					.useL2Regularization(this.l2 > 0)
					.l1RegularizationWeight(this.l1)
					.l2RegularizationWeight(this.l2)
					.batchSize(this.batchSize)
					.maximumNumberOfIterations(maximumIterations)
					.pointChangeTolerance(this.convergenceEpsilon)
					.additionalCustomConvergenceCriterion(new Function<Vector, Boolean>() {
						int iterations = 0;
						int evaluationConstantIterations = 0;
						Map<D, L> prevPredictions = null;
						List<Double> prevEvaluationValues = initEvaluationValues;
						SupervisedModel<D, L> model = thisModel;
						Vector prevWeights = null;

						@Override
						public Boolean apply(Vector weights) {
							this.iterations++;

							if (this.iterations % evaluationIterations != 0) {
								this.prevWeights = weights;
								classifierWeights = weights;
								return false;
							}

							double pointChange = weights.sub(this.prevWeights).norm(VectorNorm.L2_FAST);

							String amountDoneStr = format.format(this.iterations/(double)maximumIterations);
							String pointChangeStr = format.format(pointChange);
							String statusStr = data.getReferenceName() + " (l1=" + l1 + ", l2=" + l2 + ") #" + iterations +
									" [" + amountDoneStr + "] -- point-change: " + pointChangeStr + " ";

							if (!computeTestEvaluations) {
								output.debugWriteln(statusStr);
								return false;
							}

							LogisticRegressionAdaGrad tempClassifier = classifier;
							classifier = new LogisticRegressionAdaGrad.Builder(plataniosData.get(0).features().size(), weights)
								.sparse(true)
								.useBiasTerm(true)
								.build();

							Map<D, L> predictions = classify(testData);
							int labelDifferences = countLabelDifferences(prevPredictions, predictions);
							List<Double> evaluationValues = new ArrayList<Double>();
							for (SupervisedModelEvaluation<D, L> evaluation : evaluations) {
								evaluationValues.add(evaluation.evaluate(model, testData, predictions));
							}

							classifier = tempClassifier;

							statusStr += " predict-diff: " + labelDifferences + "/" + predictions.size() + " ";
							for (int i = 0; i < evaluations.size(); i++) {
								String evaluationName = evaluations.get(i).getGenericName();
								String evaluationDiffStr = format.format(evaluationValues.get(i) - this.prevEvaluationValues.get(i));
								String evaluationValueStr= format.format(evaluationValues.get(i));
								statusStr += evaluationName + " diff: " + evaluationDiffStr + " " + evaluationName + ": " + evaluationValueStr + " ";
							}
							output.debugWriteln(statusStr);

							double evaluationDiff = evaluationValues.get(0) - this.prevEvaluationValues.get(0);
							if (Double.compare(evaluationDiff, 0.0) == 0) {
								this.evaluationConstantIterations += evaluationIterations;
							} else {
								this.evaluationConstantIterations = 0;
							}

							this.prevPredictions = predictions;
							this.prevEvaluationValues = evaluationValues;
							this.prevWeights = weights;
							classifierWeights = weights;

							if (maxEvaluationConstantIterations < this.evaluationConstantIterations)
								return true;

							return false;
						}

						private int countLabelDifferences(Map<D, L> labels1, Map<D, L> labels2) {
							if (labels1 == null && labels2 != null)
								return labels2.size();
							if (labels1 != null && labels2 == null)
								return labels1.size();
							if (labels1 == null && labels2 == null)
								return 0;

							int count = 0;
							for (Entry<D, L> entry: labels1.entrySet()) {
								if (!labels2.containsKey(entry.getKey()) || !entry.getValue().equals(labels2.get(entry.getKey())))
									count++;
							}
							return count;
						}

					})
					.loggingLevel(0)
					.random(data.getData().getDatumTools().getDataTools().makeLocalRandom())
					.build();

		output.debugWriteln(data.getReferenceName() + " training for at most " + maximumIterations +
				" iterations (maximum " + this.maxTrainingExamples + " examples over size " + this.batchSize + " batches from " + plataniosData.size() + " examples)");

		if (!this.classifier.train(plataniosData)) {
			output.debugWriteln("ERROR: Areg failed to train platanios model.");
			return false;
		}

		double[] weightsArray = this.classifierWeights.getDenseArray();
		List<Integer> nonZeroWeightIndices = new ArrayList<Integer>();
		for (int i = 0; i < weightsArray.length - 1; i++) {
			if (Double.compare(weightsArray[i], 0) != 0) {
				nonZeroWeightIndices.add(i);
			}
		}

		this.nonZeroFeatureNames = data.getFeatures().getFeatureVocabularyNamesForIndices(nonZeroWeightIndices);

		// FIXME Remove if (data.getReferenceName().contains("_business_business_operation") && Double.compare(l2, .1) == 0) {
		//	output.debugWriteln(this.toParse(true).toString());
			/*System.out.println(this.nonZeroFeatureNames.size() + " " + weightsArray[weightsArray.length - 1]);
			System.exit(0);*/
		//}

		output.debugWriteln("Areg finished training platanios model.");

		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<D, Map<L, Double>> posterior(DataFeatureMatrix<D, L> data) {
		OutputWriter output = data.getData().getDatumTools().getDataTools().getOutputWriter();

		if (this.validLabels.size() > 2 || !this.validLabels.contains(true)) {
			output.debugWriteln("ERROR: Areg only supports binary classification.");
			return null;
		}

		DataSet<PredictedDataInstance<Vector, Double>> plataniosData = PlataniosUtil.makePlataniosDataSet((DataFeatureMatrix<Datum<Boolean>, Boolean>)data, this.weightedLabels, 0.0, false, false);

		plataniosData = this.classifier.predict(plataniosData);
		if (plataniosData == null) {
			output.debugWriteln("ERROR: Areg failed to compute data posteriors.");
			return null;
		}

		Map<D, Map<L, Double>> posteriors = new HashMap<D, Map<L, Double>>();
		for (PredictedDataInstance<Vector, Double> prediction : plataniosData) {
			int datumId = Integer.parseInt(prediction.name());
			D datum = data.getData().getDatumById(datumId);

			Map<L, Double> posterior = new HashMap<L, Double>();
			double p = (prediction.label() == 1) ? prediction.probability() : 1.0 - prediction.probability();

			// Offset bias term according to classification threshold so that
			// output posterior p >= 0.5 iff model_p >= classification threshold
			// i.e. log (p/(1-p)) = log (model_p/(1-model_p)) - log (threshold/(1-threshold))
			p = p*(1.0-this.classificationThreshold)/(this.classificationThreshold*(1.0-p)+p*(1.0-this.classificationThreshold));

			posterior.put((L)(new Boolean(true)), p);
			posterior.put((L)(new Boolean(false)), 1.0-p);

			posteriors.put(datum, posterior);
		}

		return posteriors;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<D, L> classify(DataFeatureMatrix<D, L> data) {
		OutputWriter output = data.getData().getDatumTools().getDataTools().getOutputWriter();

		if (this.validLabels.size() > 2 || !this.validLabels.contains(true)) {
			output.debugWriteln("ERROR: Areg only supports binary classification.");
			return null;
		}

		DataSet<PredictedDataInstance<Vector, Double>> plataniosData = PlataniosUtil.makePlataniosDataSet((DataFeatureMatrix<Datum<Boolean>, Boolean>)data, this.weightedLabels, 0.0, false, false);

		plataniosData = this.classifier.predict(plataniosData);
		if (plataniosData == null) {
			output.debugWriteln("ERROR: Areg failed to compute data classifications.");
			return null;
		}

		Map<D, Boolean> predictions = new HashMap<D, Boolean>();
		for (PredictedDataInstance<Vector, Double> prediction : plataniosData) {
			int datumId = Integer.parseInt(prediction.name());
			D datum = data.getData().getDatumById(datumId);

			if (this.fixedDatumLabels.containsKey(datum)) {
				predictions.put(datum, (Boolean)this.fixedDatumLabels.get(datum));
				continue;
			}

			double p = (prediction.label() == 1) ? prediction.probability() : 1.0 - prediction.probability();
			if (p >= this.classificationThreshold)
				predictions.put(datum, true);
			else
				predictions.put(datum, false);
		}

		return (Map<D, L>)predictions;
	}

	@Override
	public String getGenericName() {
		return "Areg";
	}

	@Override
	public Obj getParameterValue(String parameter) {
		if (parameter.equals("l1"))
			return Obj.stringValue(String.valueOf(this.l1));
		else if (parameter.equals("l2"))
			return Obj.stringValue(String.valueOf(this.l2));
		else if (parameter.equals("convergenceEpsilon"))
			return Obj.stringValue(String.valueOf(this.convergenceEpsilon));
		else if (parameter.equals("maxTrainingExamples"))
			return Obj.stringValue(String.valueOf(this.maxTrainingExamples));
		else if (parameter.equals("batchSize"))
			return Obj.stringValue(String.valueOf(this.batchSize));
		else if (parameter.equals("evaluationIterations"))
			return Obj.stringValue(String.valueOf(this.evaluationIterations));
		else if (parameter.equals("maxEvaluationConstantIterations"))
			return Obj.stringValue(String.valueOf(this.maxEvaluationConstantIterations));
		else if (parameter.equals("weightedLabels"))
			return Obj.stringValue(String.valueOf(this.weightedLabels));
		else if (parameter.equals("classificationThreshold"))
			return Obj.stringValue(String.valueOf(this.classificationThreshold));
		else if (parameter.equals("computeTestEvaluations"))
			return Obj.stringValue(String.valueOf(this.computeTestEvaluations));
		return null;
	}

	@Override
	public boolean setParameterValue(String parameter, Obj parameterValue) {
		if (parameter.equals("l1"))
			this.l1 = Double.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("l2"))
			this.l2 = Double.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("convergenceEpsilon"))
			this.convergenceEpsilon = Double.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("maxTrainingExamples"))
			this.maxTrainingExamples = Double.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("batchSize"))
			this.batchSize = Integer.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("evaluationIterations"))
			this.evaluationIterations = Integer.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("maxEvaluationConstantIterations"))
			this.maxEvaluationConstantIterations = Integer.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("weightedLabels"))
			this.weightedLabels = Boolean.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("classificationThreshold"))
			this.classificationThreshold = Double.valueOf(this.context.getMatchValue(parameterValue));
		else if (parameter.equals("computeTestEvaluations"))
			this.computeTestEvaluations = Boolean.valueOf(this.context.getMatchValue(parameterValue));
		else
			return false;
		return true;
	}

	@Override
	public String[] getParameterNames() {
		return this.hyperParameterNames;
	}

	@Override
	public SupervisedModel<D, L> makeInstance(DatumContext<D, L> context) {
		return new SupervisedModelAreg<D, L>(context);
	}

	@Override
	protected boolean fromParseInternalHelper(AssignmentList internalAssignments) {
		if (!internalAssignments.contains("featureVocabularySize")
				|| !internalAssignments.contains("nonZeroWeights")
				|| !internalAssignments.contains("bias"))
			return true;

		int weightVectorSize = Integer.valueOf(((Obj.Value)internalAssignments.get("featureVocabularySize").getValue()).getStr());
		double bias = Double.valueOf(((Obj.Value)internalAssignments.get("bias").getValue()).getStr());

		TreeMap<Integer, Double> nonZeroWeights = new TreeMap<Integer, Double>();
		this.nonZeroFeatureNames = new HashMap<Integer, String>();
		for (int i = 0; i < internalAssignments.size(); i++) {
			Assignment assignment = internalAssignments.get(i);
			if (assignment.getName().startsWith("w_")) {
				Obj.Array wArray = (Obj.Array)assignment.getValue();
				String name = wArray.getStr(0);
				int index = Integer.valueOf(wArray.getStr(2));
				double w = Double.valueOf(wArray.getStr(1));

				this.nonZeroFeatureNames.put(index, name);
				nonZeroWeights.put(index, w);
			}
		}

		nonZeroWeights.put(weightVectorSize-1, bias);

		this.classifierWeights = new SparseVector(weightVectorSize, nonZeroWeights);
		this.classifier = new LogisticRegressionAdaGrad.Builder(weightVectorSize - 1, this.classifierWeights)
			.sparse(true)
			.useBiasTerm(true)
			.build();

		return true;
	}

	@Override
	protected AssignmentList toParseInternalHelper(
			AssignmentList internalAssignments) {
		if (this.classifierWeights == null)
			return internalAssignments;

		double[] weightArray = this.classifierWeights.getDenseArray();
		internalAssignments.add(Assignment.assignmentTyped(null, Context.ObjectType.VALUE.toString(), "featureVocabularySize", Obj.stringValue(String.valueOf(weightArray.length))));

		List<Pair<Integer, Double>> sortedWeights = new ArrayList<Pair<Integer, Double>>();
		for (Integer index : this.nonZeroFeatureNames.keySet()) {
			sortedWeights.add(new Pair<Integer, Double>(index, weightArray[index]));
		}

		internalAssignments.add(Assignment.assignmentTyped(null, Context.ObjectType.VALUE.toString(), "nonZeroWeights", Obj.stringValue(String.valueOf(this.nonZeroFeatureNames.size()))));

		Collections.sort(sortedWeights, new Comparator<Pair<Integer, Double>>() {
			@Override
			public int compare(Pair<Integer, Double> w1,
					Pair<Integer, Double> w2) {
				if (Math.abs(w1.getSecond()) > Math.abs(w2.getSecond()))
					return -1;
				else if (Math.abs(w1.getSecond()) < Math.abs(w2.getSecond()))
					return 1;
				else
					return 0;
			} });

		internalAssignments.add(Assignment.assignmentTyped(null, Context.ObjectType.VALUE.toString(), "bias", Obj.stringValue(String.valueOf(weightArray[weightArray.length - 1]))));

		for (Pair<Integer, Double> weight : sortedWeights) {
			double w = weight.getSecond();
			int index = weight.getFirst();
			String featureName = this.nonZeroFeatureNames.get(index);
			Obj.Array weightArr = Obj.array(new String[]{ featureName, String.valueOf(w), String.valueOf(index) });
			internalAssignments.add(Assignment.assignmentTyped(null, Context.ObjectType.ARRAY.toString(), "w_" + index, weightArr));
		}

		// this.nonZeroFeatureNames = null; Assumes convert toParse only once... add back in if memory issues

		return internalAssignments;
	}

	@Override
	protected <T extends Datum<Boolean>> SupervisedModel<T, Boolean> makeBinaryHelper(
			DatumContext<T, Boolean> context, LabelIndicator<L> labelIndicator,
			SupervisedModel<T, Boolean> binaryModel) {
		return binaryModel;
	}

	@Override
	public boolean iterateTraining(DataFeatureMatrix<D, L> data,
			DataFeatureMatrix<D, L> testData,
			List<SupervisedModelEvaluation<D, L>> evaluations,
			Map<D, L> constrainedData) {
		throw new UnsupportedOperationException();
	}
}


text:
/*
Create a function that:
*   Takes an array of students
    *   Each student has a `firstName`, `lastName` and `age` properties
*   **finds** the students whose age is between 18 and 24
*   **prints**  the fullname of found students, sorted lexicographically ascending
    *   fullname is the concatenation of `firstName`, ' ' (empty space) and `lastName`
*   **Use underscore.js for all operations**
*/

function solve() {
    'use strict';
    return function (students) {
        const matching = _.chain(students)
            .filter(std => {
                const isEligible = 18 <= std.age && std.age <= 24;
                return isEligible;
            })
            .map(std => `${std.firstName} ${std.lastName}`)
            .sortBy(std => std)
            .each(std => console.log(std));

    };
}

module.exports = solve;


text:
module BABYLON {
    export class ArcRotateCameraGamepadInput implements ICameraInput<ArcRotateCamera> {
        camera: ArcRotateCamera;

        public gamepad: Nullable<Gamepad>;
        private _onGamepadConnectedObserver : Nullable<Observer<Gamepad>>;
        private _onGamepadDisconnectedObserver : Nullable<Observer<Gamepad>>;

        @serialize()
        public gamepadRotationSensibility = 80;

        @serialize()
        public gamepadMoveSensibility = 40;

        attachControl(element: HTMLElement, noPreventDefault?: boolean) {
            let manager = this.camera.getScene().gamepadManager;
            this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add((gamepad) => {
                if (gamepad.type !== Gamepad.POSE_ENABLED) {
                    // prioritize XBOX gamepads.
                    if (!this.gamepad || gamepad.type === Gamepad.XBOX) {
                        this.gamepad = gamepad;
                    }
                }
            });

            this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add((gamepad)=> {
                if (this.gamepad === gamepad) {
                    this.gamepad = null;
                }
            });

            this.gamepad = manager.getGamepadByType(Gamepad.XBOX);
        }

        detachControl(element: Nullable<HTMLElement>) {
            this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
            this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
            this.gamepad = null;
        }

        checkInputs() {
            if (this.gamepad) {
                var camera = this.camera;
                var RSValues = this.gamepad.rightStick;

                if (RSValues) {
                    if (RSValues.x != 0) {
                        var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
                        if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
                            camera.inertialAlphaOffset += normalizedRX;
                        }
                    }

                    if (RSValues.y != 0) {
                        var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
                        if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
                            camera.inertialBetaOffset += normalizedRY;
                        }
                    }
                }

                var LSValues = this.gamepad.leftStick;
                if (LSValues && LSValues.y != 0) {
                    var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
                    if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
                        this.camera.inertialRadiusOffset -= normalizedLY;
                    }
                }

            }
        }

        getClassName(): string {
            return "ArcRotateCameraGamepadInput";
        }

        getSimpleName() {
            return "gamepad";
        }
    }

    (<any>CameraInputTypes)["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
}


text:
// U3.W9:JQuery

// I worked on this challenge [with:Scott Southard].
// This challenge took me [2] hours.

$(document).ready(function(){

//RELEASE 0:
  //link the image

//RELEASE 1:

  //Link this script and the jQuery library to the jQuery_example.html file and analyze what this code does.

$('body').css({'background-color': 'pink'})

//RELEASE 2:
  //Add code here to select elements of the DOM

//RELEASE 3:
  // Add code here to modify the css and html of DOM elements

bodyElement = $('body')

//RELEASE 4:
  // Add the code for the event listener here
$('body h1').css({'color': 'blue', 'border': '1px solid black', 'visibility': 'visible' })
$('.mascot h1').html('Fiery Skippers 2016')

//RELEASE 5:
$('img').on('mouseover', function(){
  $(this).attr('src', 'http://www.carolinanature.com/butterflies/fieryskipper80866.jpg')
  $(this).animate({
    'width': '100px',
    'border': '3px solid black'
  }, 5000);
});

$('img').on('mouseleave', function(){
  $(this).attr('src', 'dbc_logo.png')
});

})  // end of the document.ready function: do not remove or write DOM manipulation below this.

/*

Reflect

1. What is jQuery?

jQuery is a JavaScript library with many features that can be used to manipulate a web page.

2. What does jQuery do for you?

jQuery does HTML document manipulation, event handling, animation and Ajax.
My pair and I used jQuery to change font color, background color, added an image from the web,
and added animation to the image.

3. What did you learn about the DOM while working on this challenge?

I learned that in order to not target the h1 in the div, we had to specify the h1 in body element.
And I also learned we can manipulate the CSS and HTML directly using jQuery without a CSS file and
without the fiery skipper image on the HTML file.

*/


text:
package org.ictact.webproceedings.repository;

import org.ictact.webproceedings.model.ConferenceMeta;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ConferenceMetaRepository extends JpaRepository<ConferenceMeta, Long> {
	ConferenceMeta findByConferenceId(Long id);
}


text:
"use strict";
var $ = require("jquery"),
    messageLocalization = require("../localization/message"),
    clickEvent = require("../events/click"),
    commonUtils = require("../core/utils/common"),
    registerComponent = require("../core/component_registrator"),
    CheckBox = require("./check_box"),
    HierarchicalCollectionWidget = require("./hierarchical_collection/ui.hierarchical_collection_widget"),
    eventUtils = require("../events/utils"),
    pointerEvents = require("../events/pointer"),
    dblclickEvent = require("../events/double_click"),
    fx = require("../animation/fx"),
    Scrollable = require("./scroll_view/ui.scrollable"),
    LoadIndicator = require("./load_indicator"),
    deferredUtils = require("../integration/jquery/deferred");
var WIDGET_CLASS = "dx-treeview",
    NODE_CONTAINER_CLASS = "dx-treeview-node-container",
    OPENED_NODE_CONTAINER_CLASS = "dx-treeview-node-container-opened",
    NODE_CLASS = "dx-treeview-node",
    ITEM_CLASS = "dx-treeview-item",
    ITEM_WITH_CHECKBOX_CLASS = "dx-treeview-item-with-checkbox",
    ITEM_DATA_KEY = "dx-treeview-item-data",
    IS_LEAF = "dx-treeview-node-is-leaf",
    EXPAND_EVENT_NAMESPACE = "dxTreeView_expand",
    TOGGLE_ITEM_VISIBILITY_CLASS = "dx-treeview-toggle-item-visibility",
    LOAD_INDICATOR_CLASS = "dx-treeview-loadindicator",
    LOAD_INDICATOR_WRAPPER_CLASS = "dx-treeview-loadindicator-wrapper",
    NODE_LOAD_INDICATOR_CLASS = "dx-treeview-node-loadindicator",
    TOGGLE_ITEM_VISIBILITY_OPENED_CLASS = "dx-treeview-toggle-item-visibility-opened",
    SELECT_ALL_ITEM_CLASS = "dx-treeview-select-all-item",
    DISABLED_STATE_CLASS = "dx-state-disabled",
    SELECTED_ITEM_CLASS = "dx-state-selected",
    DATA_ITEM_ID = "data-item-id";
var TreeView = HierarchicalCollectionWidget.inherit({
    _supportedKeys: function(e) {
        var click = function(e) {
            var $itemElement = this.option("focusedElement");
            if (!$itemElement) {
                return
            }
            e.target = $itemElement;
            e.currentTarget = $itemElement;
            this._itemClickHandler(e, $itemElement.find(">." + ITEM_CLASS))
        };
        var select = function(e) {
            e.preventDefault();
            this._changeCheckBoxState(this.option("focusedElement"))
        };
        var toggleExpandedNestedItems = function(state, e) {
            if (!this.option("expandAllEnabled")) {
                return
            }
            e.preventDefault();
            var $rootElement = this.option("focusedElement");
            if (!$rootElement) {
                return
            }
            var rootItem = this._getItemData($rootElement.find("." + ITEM_CLASS));
            this._toggleExpandedNestedItems([rootItem], state)
        };
        return $.extend(this.callBase(), {
            enter: this._showCheckboxes() ? select : click,
            space: this._showCheckboxes() ? select : click,
            asterisk: $.proxy(toggleExpandedNestedItems, this, true),
            minus: $.proxy(toggleExpandedNestedItems, this, false)
        })
    },
    _changeCheckBoxState: function($element) {
        var checkboxInstance = this._getCheckBoxInstance($element),
            currentState = checkboxInstance.option("value");
        if (!checkboxInstance.option("disabled")) {
            this._updateItemSelection(!currentState, $element.find("." + ITEM_CLASS).get(0), true, $element)
        }
    },
    _toggleExpandedNestedItems: function(items, state) {
        if (!items) {
            return
        }
        for (var i = 0, len = items.length; i < len; i++) {
            var item = items[i],
                node = this._dataAdapter.getNodeByItem(item);
            this._toggleExpandedState(node, state);
            this._toggleExpandedNestedItems(item.items, state)
        }
    },
    _getNodeElement: function(node) {
        return this.element().find("[" + DATA_ITEM_ID + "='" + commonUtils.normalizeKey(node.internalFields.key) + "']")
    },
    _activeStateUnit: "." + ITEM_CLASS,
    _widgetClass: function() {
        return WIDGET_CLASS
    },
    _getDefaultOptions: function() {
        return $.extend(this.callBase(), {
            animationEnabled: true,
            dataStructure: "tree",
            expandAllEnabled: false,
            hasItemsExpr: "hasItems",
            selectNodesRecursive: true,
            expandNodesRecursive: true,
            showCheckBoxesMode: "none",
            selectAllText: messageLocalization.format("dxList-selectAll"),
            onItemSelectionChanged: null,
            onItemExpanded: null,
            onItemCollapsed: null,
            scrollDirection: "vertical",
            virtualModeEnabled: false,
            rootValue: 0,
            searchValue: "",
            focusStateEnabled: false,
            selectionMode: "multiple",
            expandEvent: "dblclick",
            selectByClick: false,
            createChildren: null
        })
    },
    _setDeprecatedOptions: function() {
        this.callBase();
        $.extend(this._deprecatedOptions, {
            showCheckBoxes: {
                since: "15.2",
                message: "use 'showCheckBoxesMode' option instead"
            },
            selectAllEnabled: {
                since: "15.2",
                message: "use 'showCheckBoxesMode' option instead"
            },
            onItemSelected: {
                since: "16.1",
                alias: "onItemSelectionChanged"
            }
        })
    },
    _initSelectedItems: $.noop,
    _syncSelectionOptions: $.noop,
    _fireSelectionChanged: function() {
        var selectionChangePromise = this._selectionChangePromise;
        deferredUtils.when(selectionChangePromise).done($.proxy(function() {
            this._createActionByOption("onSelectionChanged", {
                excludeValidators: ["disabled", "readOnly"]
            })()
        }, this))
    },
    _checkBoxModeChange: function(value, previousValue) {
        if ("none" === previousValue || "none" === value) {
            this.repaint();
            return
        }
        var selectAllExists = this._$selectAllItem && this._$selectAllItem.length;
        switch (value) {
            case "selectAll":
                !selectAllExists && this._renderSelectAllItem();
                break;
            case "normal":
                if (selectAllExists) {
                    this._$selectAllItem.remove();
                    delete this._$selectAllItem
                }
        }
    },
    _removeSelection: function() {
        var that = this;
        $.each(this._dataAdapter.getFullData(), function(_, node) {
            if (!that._hasChildren(node)) {
                return
            }
            that._dataAdapter.toggleSelection(node.internalFields.key, false, true)
        })
    },
    _optionChanged: function(args) {
        var name = args.name,
            value = args.value,
            previousValue = args.previousValue;
        switch (name) {
            case "showCheckBoxes":
                this.option("showCheckBoxesMode", value ? "normal" : "none");
                break;
            case "selectAllEnabled":
                this.option("showCheckBoxesMode", value ? "selectAll" : "normal");
                break;
            case "selectAllText":
                if (this._$selectAllItem) {
                    this._$selectAllItem.dxCheckBox("instance").option("text", value)
                }
                break;
            case "showCheckBoxesMode":
                this._checkBoxModeChange(value, previousValue);
                break;
            case "scrollDirection":
                this._scrollableContainer.option("direction", value);
                break;
            case "items":
                delete this._$selectAllItem;
                this.callBase(args);
                break;
            case "dataSource":
                this.callBase(args);
                this._initDataAdapter();
                this._filter = {};
                break;
            case "hasItemsExpr":
                this._initAccessors();
                this.repaint();
                break;
            case "expandEvent":
                this._initExpandEvent();
                break;
            case "dataStructure":
            case "rootValue":
            case "searchValue":
                if ((!value.length || value < previousValue) && "none" !== this.option("showCheckBoxesMode")) {
                    this._removeSelection()
                }
                this._initDataAdapter();
                this.repaint();
                break;
            case "createChildren":
            case "expandNodesRecursive":
            case "onItemSelectionChanged":
            case "onItemExpanded":
            case "onItemCollapsed":
            case "expandAllEnabled":
            case "animationEnabled":
            case "virtualModeEnabled":
            case "selectByClick":
                break;
            case "selectNodesRecursive":
                this._dataAdapter.setOption("recursiveSelection", args.value);
                this.repaint();
                break;
            default:
                this.callBase(args)
        }
    },
    _initDataSource: function() {
        if (this._useCustomChildrenLoader()) {
            this._loadChildrenByCustomLoader(null).done(function(newItems) {
                if (newItems && newItems.length) {
                    this.option("items", newItems)
                }
            }.bind(this))
        } else {
            this.callBase();
            this._isVirtualMode() && this._initVirtualMode()
        }
    },
    _initVirtualMode: function() {
        var that = this,
            filter = that._filter;
        if (!filter.custom) {
            filter.custom = that._dataSource.filter()
        }
        if (!filter.internal) {
            filter.internal = [that.option("parentIdExpr"), that.option("rootValue")]
        }
    },
    _useCustomChildrenLoader: function() {
        return commonUtils.isFunction(this.option("createChildren")) && this._isDataStructurePlain()
    },
    _loadChildrenByCustomLoader: function(parentNode) {
        var invocationResult = this.option("createChildren").call(this, parentNode);
        if (commonUtils.isArray(invocationResult)) {
            return $.Deferred().resolve(invocationResult).promise()
        }
        if (invocationResult && $.isFunction(invocationResult.then)) {
            return deferredUtils.fromPromise(invocationResult)
        }
        return $.Deferred().resolve([]).promise()
    },
    _combineFilter: function() {
        if (!this._filter.custom || !this._filter.custom.length) {
            return this._filter.internal
        }
        return [this._filter.custom, this._filter.internal]
    },
    _dataSourceLoadErrorHandler: function() {
        this._renderEmptyMessage()
    },
    _init: function() {
        this._filter = {};
        this.callBase();
        this._initStoreChangeHandlers();
        this._initCheckBoxesMode()
    },
    _dataSourceChangedHandler: function(newItems) {
        if (this._initialized && this._isVirtualMode() && this.option("items").length) {
            return
        }
        this.option("items", newItems)
    },
    _removeTreeViewLoadIndicator: function() {
        if (!this._treeViewLoadIndicator) {
            return
        }
        this._treeViewLoadIndicator.remove();
        this._treeViewLoadIndicator = null
    },
    _createTreeViewLoadIndicator: function() {
        this._treeViewLoadIndicator = $("<div>", {
            "class": LOAD_INDICATOR_CLASS
        });
        this._createComponent(this._treeViewLoadIndicator, LoadIndicator, {});
        return this._treeViewLoadIndicator
    },
    _dataSourceLoadingChangedHandler: function(isLoading) {
        var resultFilter;
        if (this._isVirtualMode()) {
            resultFilter = this._combineFilter();
            this._dataSource.filter(resultFilter)
        }
        if (isLoading && !this._dataSource.isLoaded()) {
            this.option("items", []);
            var $wrapper = $("<div>", {
                "class": LOAD_INDICATOR_WRAPPER_CLASS
            });
            this._createTreeViewLoadIndicator().appendTo($wrapper);
            this.itemsContainer().append($wrapper);
            if (this._isVirtualMode() && this._dataSource.filter() !== resultFilter) {
                this._dataSource.filter([])
            }
        } else {
            this._removeTreeViewLoadIndicator()
        }
    },
    _initStoreChangeHandlers: function() {
        if ("plain" !== this.option("dataStructure")) {
            return
        }
        var that = this;
        this._dataSource && this._dataSource.store().on("inserted", function(newItem) {
            that.option().items = that.option("items").concat(newItem);
            that._dataAdapter.addItem(newItem);
            if (!that._isFiltered(newItem)) {
                return
            }
            that._updateLevel(that._parentIdGetter(newItem))
        }).on("removed", function(removedKey) {
            var node = that._dataAdapter.getNodeByKey(removedKey);
            that.option("items")[that._dataAdapter.getIndexByKey(node.internalFields.key)] = 0;
            that._markChildrenItemsToRemove(node);
            that._removeItems();
            that._dataAdapter.removeItem(removedKey);
            that._updateLevel(that._parentIdGetter(node))
        })
    },
    _markChildrenItemsToRemove: function(node) {
        var that = this,
            keys = node.internalFields.childrenKeys;
        $.each(keys, function(_, key) {
            that.option("items")[that._dataAdapter.getIndexByKey(key)] = 0;
            that._markChildrenItemsToRemove(that._dataAdapter.getNodeByKey(key))
        })
    },
    _removeItems: function() {
        var that = this,
            counter = 0,
            items = $.extend(true, [], this.option("items"));
        $.each(items, function(index, item) {
            if (!item) {
                that.option("items").splice(index - counter, 1);
                counter++
            }
        })
    },
    _isFiltered: function(item) {
        var value = this.option("searchValue"),
            reg = new RegExp(value, "i");
        return reg.test(this._displayGetter(item))
    },
    _updateLevel: function(parentId) {
        var $container = this._getContainerByParentKey(parentId);
        this._renderItems($container, this._dataAdapter.getChildrenNodes(parentId))
    },
    _getOldContainer: function($itemElement) {
        if ($itemElement.length) {
            return $itemElement.find(" > ." + NODE_CONTAINER_CLASS)
        }
        if (this._scrollableContainer) {
            return this._scrollableContainer.content().children()
        }
        return $()
    },
    _getContainerByParentKey: function(parentId) {
        var $container, node = this._dataAdapter.getNodeByKey(parentId),
            $itemElement = node ? this._getNodeElement(node) : [];
        this._getOldContainer($itemElement).remove();
        $container = this._renderNodeContainer($itemElement);
        if (this._isRootLevel(parentId)) {
            if (!this._scrollableContainer) {
                this._renderScrollableContainer()
            }
            this._scrollableContainer.content().append($container)
        }
        return $container
    },
    _isRootLevel: function(parentId) {
        return parentId === this.option("rootValue")
    },
    _getAccessors: function() {
        return ["key", "display", "selected", "expanded", "items", "parentId", "disabled", "hasItems"]
    },
    _getDataAdapterOptions: function() {
        return {
            rootValue: this.option("rootValue"),
            multipleSelection: !this._isSingleSelection(),
            recursiveSelection: this._isRecursiveSelection(),
            recursiveExpansion: this.option("expandNodesRecursive"),
            searchValue: this.option("searchValue"),
            dataType: this.option("dataStructure")
        }
    },
    _render: function() {
        this.callBase();
        this.setAria("role", "tree")
    },
    _renderContentImpl: function() {
        if (!this.option("items") || !this.option("items").length) {
            return
        }
        var $nodeContainer = this._renderNodeContainer();
        this._renderScrollableContainer();
        this._scrollableContainer.content().append($nodeContainer);
        this._renderItems($nodeContainer, this._dataAdapter.getRootNodes());
        this._initExpandEvent();
        if (this._selectAllEnabled()) {
            this._renderSelectAllItem($nodeContainer)
        }
    },
    _isVirtualMode: function() {
        return this.option("virtualModeEnabled") && this._isDataStructurePlain() && !!this.option("dataSource")
    },
    _isDataStructurePlain: function() {
        return "plain" === this.option("dataStructure")
    },
    _fireContentReadyAction: function() {
        this.callBase();
        if (this._scrollableContainer) {
            this._scrollableContainer.update()
        }
    },
    _renderScrollableContainer: function() {
        this._scrollableContainer = this._createComponent($("<div>").appendTo(this.element()), Scrollable, {
            direction: this.option("scrollDirection"),
            useKeyboard: false
        })
    },
    _renderNodeContainer: function($parent) {
        var $container = $("<ul>").addClass(NODE_CONTAINER_CLASS);
        this.setAria("role", "group", $container);
        if ($parent && $parent.length) {
            var itemData = this._getItemData($parent.find("> ." + ITEM_CLASS));
            if (this._expandedGetter(itemData)) {
                $container.addClass(OPENED_NODE_CONTAINER_CLASS)
            }
            $container.appendTo($parent)
        }
        return $container
    },
    _createDOMElement: function($nodeContainer, node) {
        var $node = $("<li>").addClass(NODE_CLASS).attr(DATA_ITEM_ID, commonUtils.normalizeKey(node.internalFields.key)).prependTo($nodeContainer);
        this.setAria({
            role: "treeitem",
            label: this._displayGetter(node.internalFields.item) || "",
            expanded: node.internalFields.expanded || false,
            level: this._getLevel($nodeContainer)
        }, $node);
        return $node
    },
    _getLevel: function($nodeContainer) {
        var parent = $nodeContainer.parent();
        return parent.hasClass("dx-scrollable-content") ? 1 : parseInt(parent.attr("aria-level")) + 1
    },
    _showCheckboxes: function() {
        return "none" !== this.option("showCheckBoxesMode")
    },
    _selectAllEnabled: function() {
        return "selectAll" === this.option("showCheckBoxesMode")
    },
    _initCheckBoxesMode: function() {
        if (this._showCheckboxes()) {
            return
        }
        this._suppressDeprecatedWarnings();
        var showCheckboxes = this.option("showCheckBoxes"),
            selectAllEnabled = this.option("selectAllEnabled");
        this._resumeDeprecatedWarnings();
        this.option("showCheckBoxesMode", showCheckboxes ? selectAllEnabled ? "selectAll" : "normal" : "none")
    },
    _renderItems: function($nodeContainer, nodes) {
        var length = nodes.length - 1;
        for (var i = length; i >= 0; i--) {
            this._renderItem(nodes[i], $nodeContainer)
        }
        this._renderFocusTarget()
    },
    _renderItem: function(node, $nodeContainer) {
        var $node = this._createDOMElement($nodeContainer, node),
            nodeData = node.internalFields;
        this._showCheckboxes() && this._renderCheckBox($node, node);
        this.setAria("selected", nodeData.selected, $node);
        this._toggleSelectedClass($node, nodeData.selected);
        this.callBase(nodeData.key, nodeData.item, $node);
        if (false !== nodeData.item.visible) {
            this._renderChildren($node, node)
        }
    },
    _renderChildren: function($node, node) {
        if (!this._hasChildren(node)) {
            this._addLeafClass($node);
            return
        }
        this._renderToggleItemVisibilityIcon($node, node);
        if (!node.internalFields.expanded) {
            return
        }
        var that = this;
        that._loadSublevel(node).done(function(childNodes) {
            that._renderSublevel($node, that._getActualNode(node), childNodes)
        })
    },
    _getActualNode: function(cachedNode) {
        return this._dataAdapter.getNodeByKey(cachedNode.internalFields.key)
    },
    _hasChildren: function(node) {
        if (this._isVirtualMode() || this._useCustomChildrenLoader()) {
            return false !== this._hasItemsGetter(node.internalFields.item)
        }
        return this.callBase(node)
    },
    _loadSublevel: function(node) {
        var deferred = $.Deferred(),
            that = this,
            childrenNodes = that._getChildNodes(node);
        if (childrenNodes.length) {
            deferred.resolve(childrenNodes)
        } else {
            that._loadNestedItems(node).done(function(items) {
                deferred.resolve(that._dataAdapter.getNodesByItems(items))
            })
        }
        return deferred.promise()
    },
    _renderSublevel: function($node, node, childNodes) {
        var $nestedNodeContainer = this._renderNodeContainer($node, node);
        this._renderItems($nestedNodeContainer, childNodes);
        if (childNodes.length && !node.internalFields.selected) {
            var firstChild = childNodes[0];
            this._updateParentsState(firstChild, this._getNodeElement(firstChild))
        }
        this._normalizeIconState($node, childNodes.length);
        $nestedNodeContainer.addClass(OPENED_NODE_CONTAINER_CLASS)
    },
    _executeItemRenderAction: function(key, itemData, itemElement) {
        var node = this._dataAdapter.getNodeByKey(key);
        this._getItemRenderAction()({
            itemElement: itemElement,
            itemIndex: key,
            itemData: itemData,
            node: node
        })
    },
    _addLeafClass: function($node) {
        $node.addClass(IS_LEAF)
    },
    _initExpandEvent: function() {
        var that = this,
            expandedEventName = this._getEventNameByOption(this.option("expandEvent")),
            $itemsContainer = this._itemContainer(),
            itemSelector = this._itemSelector();
        $itemsContainer.off("." + EXPAND_EVENT_NAMESPACE, itemSelector).on(expandedEventName, itemSelector, function(e) {
            that._toggleExpandedState(e.currentTarget, void 0, e)
        })
    },
    _getEventNameByOption: function(name) {
        var event = "click" === name ? clickEvent : dblclickEvent;
        return eventUtils.addNamespace(event.name, EXPAND_EVENT_NAMESPACE)
    },
    _getNode: function(identifier) {
        if (identifier.internalFields) {
            return identifier
        }
        if (commonUtils.isPrimitive(identifier)) {
            return this._dataAdapter.getNodeByKey(identifier)
        }
        var itemElement = $(identifier).get(0);
        if (!itemElement) {
            return null
        }
        if (itemElement.nodeType) {
            return this._getNodeByElement(itemElement)
        }
        return this._dataAdapter.getNodeByItem(itemElement)
    },
    _getNodeByElement: function(itemElement) {
        var $node = $(itemElement).closest("." + NODE_CLASS),
            key = commonUtils.denormalizeKey($node.attr(DATA_ITEM_ID));
        return this._dataAdapter.getNodeByKey(key)
    },
    _toggleExpandedState: function(itemElement, state, e) {
        var node = this._getNode(itemElement),
            currentState = node.internalFields.expanded;
        if (node.internalFields.disabled || currentState === state) {
            return
        }
        if (!commonUtils.isDefined(state)) {
            state = !currentState
        }
        this._dataAdapter.toggleExpansion(node.internalFields.key, state);
        node.internalFields.expanded = state;
        if (!this._hasChildren(node)) {
            return
        }
        var $node = this._getNodeElement(node);
        this._createLoadIndicator($node);
        this._updateExpandedItemsUI(node, state, e)
    },
    _createLoadIndicator: function($node) {
        var $icon = $node.find(">." + TOGGLE_ITEM_VISIBILITY_CLASS),
            $nodeContainer = $node.find(" > ." + NODE_CONTAINER_CLASS);
        if ($icon.hasClass(TOGGLE_ITEM_VISIBILITY_OPENED_CLASS) || $nodeContainer.not(":empty").length) {
            return
        }
        this._createComponent($("<div>", {
            "class": NODE_LOAD_INDICATOR_CLASS
        }), LoadIndicator, {}).element().appendTo($node);
        $icon.hide()
    },
    _renderToggleItemVisibilityIcon: function($node, node) {
        var $icon = $("<div>").addClass(TOGGLE_ITEM_VISIBILITY_CLASS).appendTo($node);
        if (node.internalFields.expanded) {
            $icon.addClass(TOGGLE_ITEM_VISIBILITY_OPENED_CLASS);
            $node.parent().addClass(OPENED_NODE_CONTAINER_CLASS)
        }
        if (node.internalFields.disabled) {
            $icon.addClass(DISABLED_STATE_CLASS)
        }
        this._renderToggleItemVisibilityIconClick($icon, node)
    },
    _renderToggleItemVisibilityIconClick: function($icon, node) {
        var eventName = eventUtils.addNamespace(clickEvent.name, this.NAME),
            that = this;
        $icon.off(eventName).on(eventName, function(e) {
            that._toggleExpandedState(node, void 0, e)
        })
    },
    _updateExpandedItemsUI: function(node, state, e) {
        var $node = this._getNodeElement(node),
            $icon = $node.find(">." + TOGGLE_ITEM_VISIBILITY_CLASS),
            $nodeContainer = $node.find(" > ." + NODE_CONTAINER_CLASS);
        $icon.toggleClass(TOGGLE_ITEM_VISIBILITY_OPENED_CLASS, state);
        var nodeContainerExists = $nodeContainer.length > 0;
        if (!state || nodeContainerExists && !$nodeContainer.is(":empty")) {
            this._updateExpandedItem(node, state, e);
            return
        }
        if (this._isVirtualMode() || this._useCustomChildrenLoader()) {
            this._loadNestedItemsWithUpdate(node, state, e);
            return
        }
        this._renderSublevel($node, node, this._getChildNodes(node));
        this._fireContentReadyAction();
        this._updateExpandedItem(node, state, e)
    },
    _loadNestedItemsWithUpdate: function(node, state, e) {
        var that = this,
            $node = this._getNodeElement(node);
        that._loadNestedItems(node).done(function(items) {
            var actualNodeData = that._getActualNode(node);
            that._renderSublevel($node, actualNodeData, that._dataAdapter.getNodesByItems(items));
            if (!items || !items.length) {
                return
            }
            that._fireContentReadyAction();
            that._updateExpandedItem(actualNodeData, state, e)
        })
    },
    _loadNestedItems: function(node) {
        var that = this;
        if (that._useCustomChildrenLoader()) {
            var publicNode = this._dataAdapter.getPublicNode(node);
            return that._loadChildrenByCustomLoader(publicNode).done(function(newItems) {
                that._appendItems(newItems)
            })
        }
        if (!that._isVirtualMode()) {
            return $.Deferred().resolve([]).promise()
        }
        that._filter.internal = [that.option("parentIdExpr"), node.internalFields.key];
        that._dataSource.filter(that._combineFilter());
        return that._dataSource.load().done(function(newItems) {
            var areItemsAlreadyPresent = $.inArray(newItems[0], that.option("items")) + 1;
            !areItemsAlreadyPresent && that._appendItems(newItems)
        })
    },
    _appendItems: function(newItems) {
        this.option().items = this.option("items").concat(newItems);
        this._initDataAdapter()
    },
    _updateExpandedItem: function(node, state, e) {
        var $node = this._getNodeElement(node),
            $nodeContainer = $node.find(" > ." + NODE_CONTAINER_CLASS);
        this._animateNodeContainer($nodeContainer, state);
        this.setAria("expanded", state, $node);
        this._fireExpandedStateUpdatedEvent(state, node, e)
    },
    _animateNodeContainer: function($nodeContainer, state) {
        var nodeHeight = $nodeContainer.height();
        fx.stop($nodeContainer, true);
        fx.animate($nodeContainer, {
            type: "custom",
            duration: this.option("animationEnabled") ? 400 : 0,
            from: {
                "max-height": state ? 0 : nodeHeight
            },
            to: {
                "max-height": state ? nodeHeight : 0
            },
            start: function() {
                $nodeContainer.addClass(OPENED_NODE_CONTAINER_CLASS)
            },
            complete: $.proxy(function() {
                $nodeContainer.css("max-height", "none");
                $nodeContainer.toggleClass(OPENED_NODE_CONTAINER_CLASS, state);
                this._scrollableContainer.update()
            }, this)
        })
    },
    _fireExpandedStateUpdatedEvent: function(isExpanded, node, e) {
        var target, optionName = isExpanded ? "onItemExpanded" : "onItemCollapsed";
        if (!this._hasChildren(node)) {
            return
        }
        if (commonUtils.isDefined(e)) {
            this._itemJQueryEventHandler(e, optionName, {
                node: this._dataAdapter.getPublicNode(node)
            })
        } else {
            target = this._getNodeElement(node);
            this._itemEventHandler(target, optionName, {
                jQueryEvent: e,
                node: this._dataAdapter.getPublicNode(node)
            })
        }
    },
    _normalizeIconState: function($node, hasNewItems) {
        var $icon, $loadIndicator = $node.find(".dx-loadindicator");
        $loadIndicator.length && LoadIndicator.getInstance($loadIndicator).option("visible", false);
        if (hasNewItems) {
            $icon = $node.find("." + TOGGLE_ITEM_VISIBILITY_CLASS);
            $icon.show();
            return
        }
        $node.find("." + TOGGLE_ITEM_VISIBILITY_CLASS).removeClass(TOGGLE_ITEM_VISIBILITY_CLASS);
        $node.addClass(IS_LEAF)
    },
    _renderContent: function() {
        this._renderEmptyMessage();
        var items = this.option("items");
        if (items && items.length) {
            this._contentAlreadyRendered = true
        }
        this.callBase()
    },
    _renderSelectAllItem: function($container) {
        $container = $container || this.element().find("." + NODE_CONTAINER_CLASS).first();
        this._$selectAllItem = $("<div>").addClass(SELECT_ALL_ITEM_CLASS);
        var value = this._dataAdapter.isAllSelected();
        this._createComponent(this._$selectAllItem, CheckBox, {
            value: value,
            text: this.option("selectAllText"),
            onValueChanged: $.proxy(this._toggleSelectAll, this)
        });
        this._toggleSelectedClass(this._$selectAllItem, value);
        $container.before(this._$selectAllItem)
    },
    _toggleSelectAll: function(args) {
        this._dataAdapter.toggleSelectAll(args.value);
        this._updateItemsUI();
        this._fireSelectionChanged()
    },
    _renderCheckBox: function($node, node) {
        $node.addClass(ITEM_WITH_CHECKBOX_CLASS);
        var $checkbox = $("<div>").appendTo($node);
        this._createComponent($checkbox, CheckBox, {
            value: node.internalFields.selected,
            onValueChanged: $.proxy(this._changeCheckboxValue, this),
            focusStateEnabled: false,
            disabled: this._disabledGetter(node)
        })
    },
    _toggleSelectedClass: function($node, value) {
        $node.toggleClass(SELECTED_ITEM_CLASS, !!value)
    },
    _toggleNodeDisabledState: function(node, state) {
        var $node = this._getNodeElement(node),
            $item = $node.find("." + ITEM_CLASS).eq(0);
        this._dataAdapter.toggleNodeDisabledState(node.internalFields.key, state);
        $item.toggleClass(DISABLED_STATE_CLASS, !!state);
        if (this._showCheckboxes()) {
            var checkbox = this._getCheckBoxInstance($node);
            checkbox.option("disabled", !!state)
        }
    },
    _itemOptionChanged: function(item, property, value) {
        var node = this._dataAdapter.getNodeByItem(item);
        switch (property) {
            case this.option("disabledExpr"):
                this._toggleNodeDisabledState(node, value)
        }
    },
    _changeCheckboxValue: function(e) {
        var $node = e.element.parent("." + NODE_CLASS),
            $item = $node.find("> ." + ITEM_CLASS),
            item = this._getItemData($item),
            node = this._getNodeByElement($item),
            value = e.value;
        if (node.internalFields.selected === value) {
            return
        }
        this._updateItemSelection(value, item, e.jQueryEvent)
    },
    _isSingleSelection: function() {
        return "single" === this.option("selectionMode")
    },
    _isRecursiveSelection: function() {
        return this.option("selectNodesRecursive") && "single" !== this.option("selectionMode")
    },
    _updateItemSelection: function(value, itemElement, jQueryEvent) {
        var node = this._getNode(itemElement);
        if (!node || node.internalFields.selected === value) {
            return
        }
        if (this._isSingleSelection()) {
            this._toggleSelectAll({
                value: false
            })
        }
        this._dataAdapter.toggleSelection(node.internalFields.key, value);
        this._updateItemsUI();
        var initiator = jQueryEvent || this._findItemElementByItem(node.internalFields.item),
            handler = jQueryEvent ? this._itemJQueryEventHandler : this._itemEventHandler;
        handler.call(this, initiator, "onItemSelectionChanged", {
            node: this._dataAdapter.getPublicNode(node),
            itemData: node.internalFields.item
        });
        this._fireSelectionChanged()
    },
    _getCheckBoxInstance: function($node) {
        return $node.find("> .dx-checkbox").dxCheckBox("instance")
    },
    _updateItemsUI: function() {
        var that = this;
        $.each(this._dataAdapter.getData(), function(_, node) {
            var $node = that._getNodeElement(node),
                nodeSelection = node.internalFields.selected;
            if (!$node.length) {
                return
            }
            that._toggleSelectedClass($node, nodeSelection);
            that.setAria("selected", nodeSelection, $node);
            if (that._showCheckboxes()) {
                var checkbox = that._getCheckBoxInstance($node);
                checkbox.option("value", nodeSelection)
            }
        });
        if (this._selectAllEnabled()) {
            this._$selectAllItem.dxCheckBox("instance").option("value", this._dataAdapter.isAllSelected())
        }
    },
    _updateParentsState: function(node, $node) {
        var parentNode = this._dataAdapter.getNodeByKey(node.internalFields.parentKey);
        if (!$node) {
            return
        }
        var $parentNode = $($node.parents("." + NODE_CLASS)[0]);
        if (this._showCheckboxes()) {
            var parentValue = parentNode.internalFields.selected;
            this._getCheckBoxInstance($parentNode).option("value", parentValue);
            this._toggleSelectedClass($parentNode, parentValue)
        }
        if (parentNode.internalFields.parentKey !== this.option("rootValue")) {
            this._updateParentsState(parentNode, $parentNode)
        }
    },
    _itemEventHandlerImpl: function(initiator, action, actionArgs) {
        var $itemElement = $(initiator).closest("." + NODE_CLASS).find("> ." + ITEM_CLASS);
        return action($.extend(this._extendActionArgs($itemElement), actionArgs))
    },
    _itemContextMenuHandler: function(e) {
        this._createEventHandler("onItemContextMenu", e)
    },
    _itemHoldHandler: function(e) {
        this._createEventHandler("onItemHold", e)
    },
    _createEventHandler: function(eventName, e) {
        var node = this._getNodeByElement(e.currentTarget);
        this._itemJQueryEventHandler(e, eventName, {
            node: this._dataAdapter.getPublicNode(node)
        })
    },
    _itemClass: function() {
        return ITEM_CLASS
    },
    _itemDataKey: function() {
        return ITEM_DATA_KEY
    },
    _attachClickEvent: function() {
        var that = this,
            clickSelector = "." + this._itemClass(),
            pointerDownSelector = clickSelector + ", .dx-checkbox",
            eventName = eventUtils.addNamespace(clickEvent.name, that.NAME),
            pointerDownEvent = eventUtils.addNamespace(pointerEvents.down, this.NAME);
        that._itemContainer().off(eventName, clickSelector).off(pointerDownEvent, pointerDownSelector).on(eventName, clickSelector, function(e) {
            that._itemClickHandler(e, $(this))
        }).on(pointerDownEvent, pointerDownSelector, function(e) {
            that._itemPointerDownHandler(e)
        })
    },
    _itemClickHandler: function(e, $item) {
        var itemData = this._getItemData($item),
            node = this._getNodeByElement($item);
        this._itemJQueryEventHandler(e, "onItemClick", {
            node: this._dataAdapter.getPublicNode(node)
        });
        if (this.option("selectByClick")) {
            this._updateItemSelection(!node.internalFields.selected, itemData, e)
        }
    },
    _updateSelectionToFirstItem: function($items, startIndex) {
        var itemIndex = startIndex;
        while (itemIndex >= 0) {
            var $item = $($items[itemIndex]);
            this._updateItemSelection(true, $item.find("." + ITEM_CLASS).get(0));
            itemIndex--
        }
    },
    _updateSelectionToLastItem: function($items, startIndex) {
        var itemIndex = startIndex,
            length = $items.length;
        while (itemIndex < length) {
            var $item = $($items[itemIndex]);
            this._updateItemSelection(true, $item.find("." + ITEM_CLASS).get(0));
            itemIndex++
        }
    },
    _focusInHandler: function(e) {
        var currentTarget = e.currentTarget,
            focusTargets = this._focusTarget();
        if ($.inArray(currentTarget, focusTargets) !== -1) {
            this._toggleFocusClass(true, currentTarget)
        }
        var focusedElement = this.option("focusedElement");
        if (focusedElement) {
            this._setFocusedItem(focusedElement);
            return
        }
        var $activeItem = this._getActiveItem();
        this.option("focusedElement", $activeItem.closest("." + NODE_CLASS))
    },
    _setFocusedItem: function($target) {
        if (!$target || !$target.length) {
            return
        }
        if (!$target.children().hasClass(DISABLED_STATE_CLASS)) {
            this.callBase($target)
        }
        this._scrollableContainer.scrollToElement($target.find("." + ITEM_CLASS).first())
    },
    _itemPointerDownHandler: function(e) {
        if (!this.option("focusStateEnabled")) {
            return
        }
        var $target = $(e.target).closest("." + NODE_CLASS);
        if (!$target.hasClass(NODE_CLASS)) {
            return
        }
        var itemElement = $target.hasClass(DISABLED_STATE_CLASS) ? null : $target;
        this.option("focusedElement", itemElement)
    },
    _findNonDisabledNodes: function($nodes) {
        return $nodes.not(function() {
            return $(this).find(">." + ITEM_CLASS).hasClass(DISABLED_STATE_CLASS)
        })
    },
    _moveFocus: function(location, e) {
        var FOCUS_UP = "up",
            FOCUS_DOWN = "down",
            FOCUS_FIRST = "first",
            FOCUS_LAST = "last",
            FOCUS_LEFT = this.option("rtlEnabled") ? "right" : "left",
            FOCUS_RIGHT = this.option("rtlEnabled") ? "left" : "right";
        this.element().find("." + NODE_CONTAINER_CLASS).each(function() {
            fx.stop(this, true)
        });
        var $items = this._findNonDisabledNodes(this._nodeElements());
        if (!$items || !$items.length) {
            return
        }
        switch (location) {
            case FOCUS_UP:
                var $prevItem = this._prevItem($items);
                this.option("focusedElement", $prevItem);
                if (e.shiftKey && this._showCheckboxes()) {
                    this._updateItemSelection(true, $prevItem.find("." + ITEM_CLASS).get(0))
                }
                break;
            case FOCUS_DOWN:
                var $nextItem = this._nextItem($items);
                this.option("focusedElement", $nextItem);
                if (e.shiftKey && this._showCheckboxes()) {
                    this._updateItemSelection(true, $nextItem.find("." + ITEM_CLASS).get(0))
                }
                break;
            case FOCUS_FIRST:
                var $firstItem = $items.first();
                if (e.shiftKey && this._showCheckboxes()) {
                    this._updateSelectionToFirstItem($items, $items.index(this._prevItem($items)))
                }
                this.option("focusedElement", $firstItem);
                break;
            case FOCUS_LAST:
                var $lastItem = $items.last();
                if (e.shiftKey && this._showCheckboxes()) {
                    this._updateSelectionToLastItem($items, $items.index(this._nextItem($items)))
                }
                this.option("focusedElement", $lastItem);
                break;
            case FOCUS_RIGHT:
                this._expandFocusedContainer();
                break;
            case FOCUS_LEFT:
                this._collapseFocusedContainer();
                break;
            default:
                this.callBase.apply(this, arguments);
                return
        }
    },
    _nodeElements: function() {
        return this.element().find("." + NODE_CLASS).not(":hidden")
    },
    _expandFocusedContainer: function() {
        var $focusedNode = this.option("focusedElement");
        if (!$focusedNode || $focusedNode.hasClass(IS_LEAF)) {
            return
        }
        var $node = $focusedNode.find("." + NODE_CONTAINER_CLASS).eq(0);
        if ($node.hasClass(OPENED_NODE_CONTAINER_CLASS)) {
            this.option("focusedElement", this._nextItem(this._findNonDisabledNodes(this._nodeElements())));
            return
        }
        var node = this._getNodeByElement($focusedNode.find(">." + ITEM_CLASS));
        this._toggleExpandedState(node, true)
    },
    _getClosestNonDisabledNode: function($node) {
        do {
            $node = $node.parent().closest("." + NODE_CLASS)
        } while ($node.children(".dx-treeview-item.dx-state-disabled").length);
        return $node
    },
    _collapseFocusedContainer: function() {
        var $focusedNode = this.option("focusedElement");
        if (!$focusedNode) {
            return
        }
        var nodeElement = $focusedNode.find("." + NODE_CONTAINER_CLASS).eq(0);
        if (!$focusedNode.hasClass(IS_LEAF) && nodeElement.hasClass(OPENED_NODE_CONTAINER_CLASS)) {
            var node = this._getNodeByElement($focusedNode.find(">." + ITEM_CLASS));
            this._toggleExpandedState(node, false)
        } else {
            var collapsedNode = this._getClosestNonDisabledNode($focusedNode);
            collapsedNode.length && this.option("focusedElement", collapsedNode)
        }
    },
    updateDimensions: function() {
        var that = this,
            deferred = $.Deferred();
        if (that._scrollableContainer) {
            that._scrollableContainer.update().done(function() {
                deferred.resolveWith(that)
            })
        } else {
            deferred.resolveWith(that)
        }
        return deferred.promise()
    },
    selectItem: function(itemElement) {
        this._updateItemSelection(true, itemElement)
    },
    unselectItem: function(itemElement) {
        this._updateItemSelection(false, itemElement)
    },
    expandItem: function(itemElement) {
        this._toggleExpandedState(itemElement, true)
    },
    collapseItem: function(itemElement) {
        this._toggleExpandedState(itemElement, false)
    },
    getNodes: function() {
        return this._dataAdapter.getTreeNodes()
    },
    selectAll: function() {
        if (this._selectAllEnabled()) {
            this._$selectAllItem.dxCheckBox("instance").option("value", true)
        } else {
            this._toggleSelectAll({
                value: true
            })
        }
    },
    unselectAll: function() {
        if (this._selectAllEnabled()) {
            this._$selectAllItem.dxCheckBox("instance").option("value", false)
        } else {
            this._toggleSelectAll({
                value: false
            })
        }
    },
    collapseAll: function() {
        var that = this;
        $.each(this._dataAdapter.getExpandedNodesKeys(), function(_, key) {
            that._toggleExpandedState(key, false)
        })
    }
});
registerComponent("dxTreeView", TreeView);
module.exports = TreeView;
module.exports.default = module.exports;