text:
"""Partial dependence plots for tree ensembles. """

# Authors: Peter Prettenhofer
# License: BSD Style.

from itertools import count, izip

import numbers

import numpy as np

from scipy.stats.mstats import mquantiles

from ..utils.extmath import cartesian
from ..externals.joblib import Parallel, delayed
from ..externals import six
from ..externals.six.moves import xrange
from ..utils import array2d
from ..tree._tree import DTYPE

from ._gradient_boosting import _partial_dependence_tree
from .gradient_boosting import BaseGradientBoosting

def _grid_from_X(X, percentiles=(0.05, 0.95), grid_resolution=100):
    """Generate a grid of points based on the ``percentiles of ``X``.

    The grid is generated by placing ``grid_resolution`` equally
    spaced points between the ``percentiles`` of each column
    of ``X``.

    Parameters
    ----------
    X : ndarray
        The data
    percentiles : tuple of floats
        The percentiles which are used to construct the extreme
        values of the grid axes.
    grid_resolution : int
        The number of equally spaced points that are placed
        on the grid.

    Returns
    -------
    grid : ndarray
        All data points on the grid; ``grid.shape[1] == X.shape[1]``
        and ``grid.shape[0] == grid_resolution * X.shape[1]``.
    axes : seq of ndarray
        The axes with which the grid has been created.
    """
    if len(percentiles) != 2:
        raise ValueError('percentile must be tuple of len 2')
    if not all(map(lambda x: 0.0 <= x <= 1.0, percentiles)):
        raise ValueError('percentile values must be in [0, 1]')

    axes = []
    for col in range(X.shape[1]):
        uniques = np.unique(X[:, col])
        if uniques.shape[0] < grid_resolution:
            # feature has low resolution use unique vals
            axis = uniques
        else:
            emp_percentiles = mquantiles(X, prob=percentiles, axis=0)
            # create axis based on percentiles and grid resolution
            axis = np.linspace(emp_percentiles[0, col],
                               emp_percentiles[1, col],
                               num=grid_resolution, endpoint=True)
        axes.append(axis)

    return cartesian(axes), axes

def partial_dependence(gbrt, target_variables, grid=None, X=None,
                       percentiles=(0.05, 0.95), grid_resolution=100):
    """Partial dependence of ``target_variables``.

    Partial dependence plots show the dependence between the joint values
    of the ``target_variables`` and the function represented
    by the ``gbrt``.

    Parameters
    ----------
    gbrt : BaseGradientBoosting
        A fitted gradient boosting model.
    target_variables : array-like, dtype=int
        The target features for which the partial dependecy should be
        computed (size should be smaller than 3 for visual renderings).
    grid : array-like, shape=(n_points, len(target_variables))
        The grid of ``target_variables`` values for which the
        partial dependecy should be evaluted (either ``grid`` or ``X``
        must be specified).
    X : array-like, shape=(n_samples, n_features)
        The data on which ``gbrt`` was trained. It is used to generate
        a ``grid`` for the ``target_variables``. The ``grid`` comprises
        ``grid_resolution`` equally spaced points between the two
        ``percentiles``.
    percentiles : (low, high), default=(0.05, 0.95)
        The lower and upper percentile used create the extreme values
        for the ``grid``. Only if ``X`` is not None.
    grid_resolution : int, default=100
        The number of equally spaced points on the ``grid``.

    Returns
    -------
    pdp : array, shape=(n_classes, n_points)
        The partial dependence function evaluated on the ``grid``.
        For regression and binary classification ``n_classes==1``.
    axes : seq of ndarray or None
        The axes with which the grid has been created or None if
        the grid has been given.

    Examples
    --------
    >>> samples = [[0, 0, 2], [1, 0, 0]]
    >>> labels = [0, 1]
    >>> from sklearn.ensemble import GradientBoostingClassifier
    >>> gb = GradientBoostingClassifier().fit(samples, labels)
    >>> kwargs = dict(X=samples, percentiles=(0, 1), grid_resolution=2)
    >>> partial_dependence(gb, [0], **kwargs)
    (array([[-10.72892297,  10.72892297]]), [array([ 0.,  1.])])
    """
    if not isinstance(gbrt, BaseGradientBoosting):
        raise ValueError('gbrt has to be an instance of BaseGradientBoosting')
    if gbrt.estimators_.shape[0] == 0:
        raise ValueError('Call %s.fit before partial_dependence' %
                         gbrt.__class__.__name__)
    if (grid is None and X is None) or (grid is not None and X is not None):
        raise ValueError('Either grid or X must be specified')

    target_variables = np.asarray(target_variables, dtype=np.int32,
                                  order='C').ravel()

    if any([not (0 <= fx < gbrt.n_features) for fx in target_variables]):
        raise ValueError('target_variables must be in [0, %d]'
                         % (gbrt.n_features - 1))

    if X is not None:
        X = array2d(X, dtype=DTYPE, order='C')
        grid, axes = _grid_from_X(X[:, target_variables], percentiles,
                                  grid_resolution)
    else:
        assert grid is not None
        # dont return axes if grid is given
        axes = None
        # grid must be 2d
        if grid.ndim == 1:
            grid = grid[:, np.newaxis]
        if grid.ndim != 2:
            raise ValueError('grid must be 2d but is %dd' % grid.ndim)

    grid = np.asarray(grid, dtype=DTYPE, order='C')
    assert grid.shape[1] == target_variables.shape[0]

    n_trees_per_stage = gbrt.estimators_.shape[1]
    n_estimators = gbrt.estimators_.shape[0]
    pdp = np.zeros((n_trees_per_stage, grid.shape[0],), dtype=np.float64,
                   order='C')
    for stage in xrange(n_estimators):
        for k in range(n_trees_per_stage):
            tree = gbrt.estimators_[stage, k].tree_
            _partial_dependence_tree(tree, grid, target_variables,
                                     gbrt.learning_rate, pdp[k])

    return pdp, axes

def plot_partial_dependence(gbrt, X, features, feature_names=None,
                            label=None, n_cols=3, grid_resolution=100,
                            percentiles=(0.05, 0.95), n_jobs=1,
                            verbose=0, ax=None, line_kw=None,
                            contour_kw=None, **fig_kw):
    """Partial dependence plots for ``features``.

    The ``len(features)`` plots are aranged in a grid with ``n_cols``
    columns. Two-way partial dependence plots are plotted as contour
    plots.

    Parameters
    ----------
    gbrt : BaseGradientBoosting
        A fitted gradient boosting model.
    X : array-like, shape=(n_samples, n_features)
        The data on which ``gbrt`` was trained.
    features : seq of tuples or ints
        If seq[i] is an int or a tuple with one int value, a one-way
        PDP is created; if seq[i] is a tuple of two ints, a two-way
        PDP is created.
    feature_names : seq of str
        Name of each feature; feature_names[i] holds
        the name of the feature with index i.
    label : object
        The class label for which the PDPs should be computed.
        Only if gbrt is a multi-class model. Must be in ``gbrt.classes_``.
    n_cols : int
        The number of columns in the grid plot (default: 3).
    percentiles : (low, high), default=(0.05, 0.95)
        The lower and upper percentile used create the extreme values
        for the PDP axes.
    grid_resolution : int, default=100
        The number of equally spaced points on the axes.
    n_jobs : int
        The number of CPUs to use to compute the PDs. -1 means 'all CPUs'.
        Defaults to 1.
    verbose : int
        Verbose output during PD computations. Defaults to 0.
    ax : Matplotlib axis object, default None
        An axis object onto which the plots will be drawn.
    line_kw : dict
        Dict with keywords passed to the ``pylab.plot`` call.
        For one-way partial dependence plots.
    contour_kw : dict
        Dict with keywords passed to the ``pylab.plot`` call.
        For two-way partial dependence plots.
    fig_kw : dict
        Dict with keywords passed to the figure() call.
        Note that all keywords not recognized above will be automatically
        included here.

    Returns
    -------
    fig : figure
        The Matplotlib Figure object.
    axs : seq of Axis objects
        A seq of Axis objects, one for each subplot.

    Examples
    --------
    >>> from sklearn.datasets import make_friedman1
    >>> from sklearn.ensemble import GradientBoostingRegressor
    >>> X, y = make_friedman1()
    >>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y)
    >>> fig, axs = plot_partial_dependence(clf, X, [0, (0, 1)]) #doctest: +SKIP
    ...
    """
    import matplotlib.pyplot as plt
    from matplotlib import transforms
    from matplotlib.ticker import MaxNLocator
    from matplotlib.ticker import ScalarFormatter

    if not isinstance(gbrt, BaseGradientBoosting):
        raise ValueError('gbrt has to be an instance of BaseGradientBoosting')
    if gbrt.estimators_.shape[0] == 0:
        raise ValueError('Call %s.fit before partial_dependence' %
                         gbrt.__class__.__name__)

    # set label_idx for multi-class GBRT
    if hasattr(gbrt, 'classes_') and np.size(gbrt.classes_) > 2:
        if label is None:
            raise ValueError('label is not given for multi-class PDP')
        label_idx = np.searchsorted(gbrt.classes_, label)
        if gbrt.classes_[label_idx] != label:
            raise ValueError('label %s not in ``gbrt.classes_``' % str(label))
    else:
        # regression and binary classification
        label_idx = 0

    X = array2d(X, dtype=DTYPE, order='C')
    if gbrt.n_features != X.shape[1]:
        raise ValueError('X.shape[1] does not match gbrt.n_features')

    if line_kw is None:
        line_kw = {'color': 'green'}
    if contour_kw is None:
        contour_kw = {}

    # convert feature_names to list
    if feature_names is None:
        # if not feature_names use fx indices as name
        feature_names = map(str, range(gbrt.n_features))
    elif isinstance(feature_names, np.ndarray):
        feature_names = feature_names.tolist()

    def convert_feature(fx):
        if isinstance(fx, six.string_types):
            try:
                fx = feature_names.index(fx)
            except ValueError:
                raise ValueError('Feature %s not in feature_names' % fx)
        return fx

    # convert features into a seq of int tuples
    tmp_features = []
    for fxs in features:
        if isinstance(fxs, (numbers.Integral,) + six.string_types):
            fxs = (fxs,)
        try:
            fxs = np.array([convert_feature(fx) for fx in fxs], dtype=np.int32)
        except TypeError:
            raise ValueError('features must be either int, str, or tuple '
                             'of int/str')
        if not (1 <= np.size(fxs) <= 2):
            raise ValueError('target features must be either one or two')

        tmp_features.append(fxs)

    features = tmp_features

    names = []
    try:
        for fxs in features:
            names.append([feature_names[i] for i in fxs])
    except IndexError:
        raise ValueError('features[i] must be in [0, n_features) '
                         'but was %d' % i)

    # compute PD functions
    pd_result = Parallel(n_jobs=n_jobs, verbose=verbose)(
        delayed(partial_dependence)(gbrt, fxs, X=X,
                                    grid_resolution=grid_resolution)
        for fxs in features)

    # get global min and max values of PD grouped by plot type
    pdp_lim = {}
    for pdp, axes in pd_result:
        min_pd, max_pd = pdp[label_idx].min(), pdp[label_idx].max()
        n_fx = len(axes)
        old_min_pd, old_max_pd = pdp_lim.get(n_fx, (min_pd, max_pd))
        min_pd = min(min_pd, old_min_pd)
        max_pd = max(max_pd, old_max_pd)
        pdp_lim[n_fx] = (min_pd, max_pd)

    # create contour levels for two-way plots
    if 2 in pdp_lim:
        Z_level = np.linspace(*pdp_lim[2], num=8)

    if ax is None:
        fig = plt.figure(**fig_kw)
    else:
        fig = ax.get_figure()
        fig.clear()

    n_cols = min(n_cols, len(features))
    n_rows = int(np.ceil(len(features) / float(n_cols)))
    axs = []
    for i, fx, name, (pdp, axes) in izip(count(), features, names,
                                         pd_result):
        ax = fig.add_subplot(n_rows, n_cols, i + 1)

        if len(axes) == 1:
            ax.plot(axes[0], pdp[label_idx].ravel(), **line_kw)
        else:
            # make contour plot
            assert len(axes) == 2
            XX, YY = np.meshgrid(axes[0], axes[1])
            Z = pdp[label_idx].reshape(map(np.size, axes)).T
            CS = ax.contour(XX, YY, Z, levels=Z_level, linewidths=0.5,
                            colors='k')
            ax.contourf(XX, YY, Z, levels=Z_level, vmax=Z_level[-1],
                        vmin=Z_level[0], alpha=0.75, **contour_kw)
            ax.clabel(CS, fmt='%2.2f', colors='k', fontsize=10, inline=True)

        # plot data deciles + axes labels
        deciles = mquantiles(X[:, fx[0]], prob=np.arange(0.1, 1.0, 0.1))
        trans = transforms.blended_transform_factory(ax.transData,
                                                     ax.transAxes)
        ylim = ax.get_ylim()
        ax.vlines(deciles, [0], 0.05, transform=trans, color='k')
        ax.set_xlabel(name[0])
        ax.set_ylim(ylim)

        # prevent x-axis ticks from overlapping
        ax.xaxis.set_major_locator(MaxNLocator(nbins=6, prune='lower'))
        tick_formatter = ScalarFormatter()
        tick_formatter.set_powerlimits((-3, 4))
        ax.xaxis.set_major_formatter(tick_formatter)

        if len(axes) > 1:
            # two-way PDP - y-axis deciles + labels
            deciles = mquantiles(X[:, fx[1]], prob=np.arange(0.1, 1.0, 0.1))
            trans = transforms.blended_transform_factory(ax.transAxes,
                                                         ax.transData)
            xlim = ax.get_xlim()
            ax.hlines(deciles, [0], 0.05, transform=trans, color='k')
            ax.set_ylabel(name[1])
            # hline erases xlim
            ax.set_xlim(xlim)
        else:
            ax.set_ylabel('Partial dependence')

        if len(axes) == 1:
            ax.set_ylim(pdp_lim[1])
        axs.append(ax)

    fig.subplots_adjust(bottom=0.15, top=0.7, left=0.1, right=0.95, wspace=0.4,
                        hspace=0.3)
    return fig, axs


text:
package integrationTests.textFile;

import java.util.*;

import integrationTests.textFile.TextFile.*;
import static mockit.Mockit.*;
import static org.hamcrest.core.IsEqual.*;
import static org.junit.Assert.*;
import org.junit.*;

import mockit.*;

public final class TextFileUsingAnnotatedMockClassesTest
{
   @Test
   public void createTextFileUsingAnnotatedMockClass() throws Exception
   {
      setUpMocks(MockTextReader.class);

      new TextFile("file", 0);
   }

   @MockClass(realClass = DefaultTextReader.class)
   static class MockTextReader
   {
      @Mock(invocations = 1)
      void $init(String fileName)
      {
         assertThat(fileName, equalTo("file"));
      }
   }

   @Test
   public void createTextFileByMockingTheTextReaderThroughItsClassName() throws Exception
   {
      setUpMock("integrationTests.textFile.TextFile$DefaultTextReader", MockTextReader.class);

      new TextFile("file", 0);
   }

   @Test
   public void parseTextFileUsingConcreteClass() throws Exception
   {
      setUpMocks(MockTextReader.class, new MockTextReaderForParse());

      TextFile textFile = new TextFile("file", 200);
      List<String[]> result = textFile.parse();

      assertResultFromTextFileParsing(result);
   }

   @MockClass(realClass = DefaultTextReader.class)
   public static class MockTextReaderForParse
   {
      private static final String[] LINES = { "line1", "another,line", null};
      int invocation;

      @Mock(invocations = 1)
      public long skip(long n)
      {
         assertEquals(200, n);
         return n;
      }

      @Mock(invocations = 3)
      public String readLine() { return LINES[invocation++]; }

      @Mock(invocations = 1)
      public void close() {}
   }

   private void assertResultFromTextFileParsing(List<String[]> result)
   {
      assertEquals(2, result.size());
      String[] line1 = result.get(0);
      assertEquals(1, line1.length);
      assertEquals("line1", line1[0]);
      String[] line2 = result.get(1);
      assertEquals(2, line2.length);
      assertEquals("another", line2[0]);
      assertEquals("line", line2[1]);
   }

   @Test
   public void parseTextFileUsingInterface() throws Exception
   {
      TextReader textReader = newEmptyProxy(TextReader.class);
      setUpMock(textReader.getClass(), new MockTextReaderForParse());

      TextFile textFile = new TextFile(textReader, 200);
      List<String[]> result = textFile.parse();

      assertResultFromTextFileParsing(result);
   }
}

redpajama_set_name: RedPajamaGithub


text:
module Makesure

  class Summarize

    attr_reader :name, :cron, :blk

    def initialize(name, cron, blk)
      @name = name
      @cron = cron
      @blk  = blk
    end

    def run!
      begin

        blk.call

      rescue Exception => e
        Makesure.warn "Uh oh, something's up"
        Makesure.warn "\t" + e.message

        # send an email with the details

        return false
      end

      true
    end

  end

end


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.15 at 08:44:39 PM EDT
//

package org.sierraecg.schema.jaxb._1_04;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <attribute name="starttime" use="required" type="{http://www3.medical.philips.com}TYPEstarttime" />
 *       <attribute name="duration" use="required" type="{http://www3.medical.philips.com}TYPEduration" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "inop")
public class Inop {

    @XmlAttribute(name = "starttime", required = true)
    protected String starttime;
    @XmlAttribute(name = "duration", required = true)
    protected String duration;

    /**
     * Gets the value of the starttime property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getStarttime() {
        return starttime;
    }

    /**
     * Sets the value of the starttime property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setStarttime(String value) {
        this.starttime = value;
    }

    /**
     * Gets the value of the duration property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDuration() {
        return duration;
    }

    /**
     * Sets the value of the duration property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDuration(String value) {
        this.duration = value;
    }

}


text:
package com.metamx.common.guava;

/**
 * A YieldingAccumulator is used along with a Yielder in order to replicate continuations in Java.  I'm still not sure
 * this is such a great idea, but it's there.  We shall see.
 *
 * The accumulated has its accumulate() method called and has the option of "yielding" its response by calling
 * yield() before returning as response.  If it chooses not to yield its response, then it expects to get called
 * again with the next value and the value it just returned.
 */
public abstract class YieldingAccumulator<AccumulatedType, InType>
{
  private boolean yielded = false;

  public void yield()
  {
    yielded = true;
  }

  public boolean yielded()
  {
    return yielded;
  }

  public void reset()
  {
    yielded = false;
  }

  public abstract AccumulatedType accumulate(AccumulatedType accumulated, InType in);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <!-- see http://www.atomikos.com/Documentation/Tomcat7Integration35 -->
    <Transaction factory="com.atomikos.icatch.jta.UserTransactionFactory" />
</Context>


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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.Collections;

import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.cdi.BusinessProcess;
import org.camunda.bpm.engine.cdi.ProcessEngineCdiException;
import org.camunda.bpm.engine.cdi.test.CdiProcessEngineTestCase;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.engine.variable.type.ValueType;
import org.camunda.bpm.engine.variable.value.TypedValue;
import org.junit.Test;

/**
 * @author Daniel Meyer
 */
public class BusinessProcessBeanTest extends CdiProcessEngineTestCase {

  /* General test asserting that the business process bean is functional */
  @Test
  @Deployment
  public void test() throws Exception {

    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // start the process
    businessProcess.startProcessByKey("businessProcessBeanTest").getId();

    // ensure that the process is started:
    assertNotNull(processEngine.getRuntimeService().createProcessInstanceQuery().singleResult());

    // ensure that there is a single task waiting
    Task task = processEngine.getTaskService().createTaskQuery().singleResult();
    assertNotNull(task);

    String value = "value";
    businessProcess.setVariable("key", Variables.stringValue(value));
    assertEquals(value, businessProcess.getVariable("key"));

    // Typed variable API
    TypedValue typedValue = businessProcess.getVariableTyped("key");
    assertEquals(ValueType.STRING, typedValue.getType());
    assertEquals(value, typedValue.getValue());

    // Local variables
    String localValue = "localValue";
    businessProcess.setVariableLocal("localKey", Variables.stringValue(localValue));
    assertEquals(localValue, businessProcess.getVariableLocal("localKey"));

    // Local typed variable API
    TypedValue typedLocalValue = businessProcess.getVariableLocalTyped("localKey");
    assertEquals(ValueType.STRING, typedLocalValue.getType());
    assertEquals(localValue, typedLocalValue.getValue());

    // complete the task
    assertEquals(task.getId(), businessProcess.startTask(task.getId()).getId());
    businessProcess.completeTask();

    // assert the task is completed
    assertNull(processEngine.getTaskService().createTaskQuery().singleResult());

    // assert that the process is ended:
    assertNull(processEngine.getRuntimeService().createProcessInstanceQuery().singleResult());

  }

  @Test
  @Deployment
  public void testProcessWithoutWatestate() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // start the process
    businessProcess.startProcessByKey("businessProcessBeanTest").getId();

    // assert that the process is ended:
    assertNull(processEngine.getRuntimeService().createProcessInstanceQuery().singleResult());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testResolveProcessInstanceBean() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    assertNull(getBeanInstance(ProcessInstance.class));
    assertNull(getBeanInstance("processInstanceId"));
    assertNull(getBeanInstance(Execution.class));
    assertNull(getBeanInstance("executionId"));

    String pid = businessProcess.startProcessByKey("businessProcessBeanTest").getId();

    // assert that now we can resolve the ProcessInstance-bean
    assertEquals(pid, getBeanInstance(ProcessInstance.class).getId());
    assertEquals(pid, getBeanInstance("processInstanceId"));
    assertEquals(pid, getBeanInstance(Execution.class).getId());
    assertEquals(pid, getBeanInstance("executionId"));

    taskService.complete(taskService.createTaskQuery().singleResult().getId());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testResolveTaskBean() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    assertNull(getBeanInstance(Task.class));
    assertNull(getBeanInstance("taskId"));

    businessProcess.startProcessByKey("businessProcessBeanTest");
    String taskId = taskService.createTaskQuery().singleResult().getId();

    businessProcess.startTask(taskId);

    // assert that now we can resolve the Task-bean
    assertEquals(taskId, getBeanInstance(Task.class).getId());
    assertEquals(taskId, getBeanInstance("taskId"));

    taskService.complete(taskService.createTaskQuery().singleResult().getId());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  @SuppressWarnings("deprecation")
  public void testGetVariableCache() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // initially the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getVariableCache());

    // set a variable
    businessProcess.setVariable("aVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("aVariableName", "aVariableValue"), businessProcess.getVariableCache());

    // getting the variable cache does not empty it:
    assertEquals(Collections.singletonMap("aVariableName", "aVariableValue"), businessProcess.getVariableCache());

    businessProcess.startProcessByKey("businessProcessBeanTest");

    // now the variable cache is empty again:
    assertEquals(Collections.EMPTY_MAP, businessProcess.getVariableCache());

    // set a variable
    businessProcess.setVariable("anotherVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getVariableCache());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testGetCachedVariableMap() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // initially the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getCachedVariableMap());

    // set a variable
    businessProcess.setVariable("aVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("aVariableName", "aVariableValue"), businessProcess.getCachedVariableMap());

    // getting the variable cache does not empty it:
    assertEquals(Collections.singletonMap("aVariableName", "aVariableValue"), businessProcess.getCachedVariableMap());

    businessProcess.startProcessByKey("businessProcessBeanTest");

    // now the variable cache is empty again:
    assertEquals(Collections.EMPTY_MAP, businessProcess.getCachedVariableMap());

    // set a variable
    businessProcess.setVariable("anotherVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getCachedVariableMap());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  @SuppressWarnings("deprecation")
  public void testGetAndClearVariableCache() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // initially the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearVariableCache());

    // set a variable
    businessProcess.setVariable("aVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("aVariableName", "aVariableValue"), businessProcess.getAndClearVariableCache());

    // now the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearVariableCache());

    businessProcess.startProcessByKey("businessProcessBeanTest");

    // now the variable cache is empty again:
    assertEquals(Collections.EMPTY_MAP, businessProcess.getVariableCache());

    // set a variable
    businessProcess.setVariable("anotherVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getVariableCache());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testGetAndClearCachedVariableMap() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // initially the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearCachedVariableMap());

    // set a variable
    businessProcess.setVariable("aVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("aVariableName", "aVariableValue"), businessProcess.getAndClearCachedVariableMap());

    // now the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearCachedVariableMap());

    businessProcess.startProcessByKey("businessProcessBeanTest");

    // now the variable cache is empty again:
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearCachedVariableMap());

    // set a variable
    businessProcess.setVariable("anotherVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getAndClearCachedVariableMap());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  @SuppressWarnings("deprecation")
  public void testGetVariableLocalCache() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // initially the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getVariableLocalCache());

    // set a variable - this should fail before the process is started
    try {
      businessProcess.setVariableLocal("aVariableName", "aVariableValue");
      fail("exception expected!");
    }
    catch(ProcessEngineCdiException e) {
      assertEquals("Cannot set a local cached variable: neither a Task nor an Execution is associated.", e.getMessage());
    }

    businessProcess.startProcessByKey("businessProcessBeanTest");

    // now the variable cache is empty again:
    assertEquals(Collections.EMPTY_MAP, businessProcess.getVariableLocalCache());

    // set a variable
    businessProcess.setVariableLocal("anotherVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getVariableLocalCache());

    // getting the variable cache does not empty it:
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getVariableLocalCache());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testGetCachedLocalVariableMap() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // initially the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getCachedLocalVariableMap());

    // set a variable - this should fail before the process is started
    try {
      businessProcess.setVariableLocal("aVariableName", "aVariableValue");
      fail("exception expected!");
    }
    catch(ProcessEngineCdiException e) {
      assertEquals("Cannot set a local cached variable: neither a Task nor an Execution is associated.", e.getMessage());
    }

    businessProcess.startProcessByKey("businessProcessBeanTest");

    // now the variable cache is empty again:
    assertEquals(Collections.EMPTY_MAP, businessProcess.getCachedLocalVariableMap());

    // set a variable
    businessProcess.setVariableLocal("anotherVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getCachedLocalVariableMap());

    // getting the variable cache does not empty it:
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getCachedLocalVariableMap());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testGetVariableLocal()
  {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);
    ProcessInstance processInstance = businessProcess.startProcessByKey("businessProcessBeanTest");

    TaskService taskService = getBeanInstance(TaskService.class);
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();

    assertNotNull(task);

    businessProcess.startTask(task.getId());

    businessProcess.setVariableLocal("aVariableName", "aVariableValue");

    // Flushing and re-getting should retain the value (CAM-1806):
    businessProcess.flushVariableCache();
    assertTrue(businessProcess.getCachedLocalVariableMap().isEmpty());
    assertEquals("aVariableValue", businessProcess.getVariableLocal("aVariableName"));
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  @SuppressWarnings("deprecation")
  public void testGetAndClearVariableLocalCache() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // initially the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearVariableLocalCache());

    // set a variable - this should fail before the process is started
    try {
      businessProcess.setVariableLocal("aVariableName", "aVariableValue");
      fail("exception expected!");
    }
    catch(ProcessEngineCdiException e) {
      assertEquals("Cannot set a local cached variable: neither a Task nor an Execution is associated.", e.getMessage());
    }

    // the variable cache is still empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearVariableLocalCache());

    businessProcess.startProcessByKey("businessProcessBeanTest");

    // now the variable cache is empty again:
    assertEquals(Collections.EMPTY_MAP, businessProcess.getVariableLocalCache());

    // set a variable
    businessProcess.setVariableLocal("anotherVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getVariableLocalCache());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testGetAndClearCachedLocalVariableMap() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // initially the variable cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearCachedLocalVariableMap());

    // set a variable - this should fail before the process is started
    try {
      businessProcess.setVariableLocal("aVariableName", "aVariableValue");
      fail("exception expected!");
    }
    catch(ProcessEngineCdiException e) {
      assertEquals("Cannot set a local cached variable: neither a Task nor an Execution is associated.", e.getMessage());
    }

    // the variable cache is still empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearCachedLocalVariableMap());

    businessProcess.startProcessByKey("businessProcessBeanTest");

    // now the variable cache is empty again:
    assertEquals(Collections.EMPTY_MAP, businessProcess.getAndClearCachedLocalVariableMap());

    // set a variable
    businessProcess.setVariableLocal("anotherVariableName", "aVariableValue");

    // now the variable is set
    assertEquals(Collections.singletonMap("anotherVariableName", "aVariableValue"), businessProcess.getAndClearCachedLocalVariableMap());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testFlushVariableCache() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // cannot flush variable cache in absence of an association:
    try {
      businessProcess.flushVariableCache();
      fail("exception expected!");

    } catch (ProcessEngineCdiException e) {
      assertEquals("Cannot flush variable cache: neither a Task nor an Execution is associated.", e.getMessage());

    }

    businessProcess.startProcessByKey("businessProcessBeanTest");

    // set a variable
    businessProcess.setVariable("aVariableName", "aVariable");

    // the variable is not yet present in the execution:
    assertNull(runtimeService.getVariable(businessProcess.getExecutionId(), "aVariableName"));

    // set a local variable
    businessProcess.setVariableLocal("aVariableLocalName", "aVariableLocal");

    // the local variable is not yet present in the execution:
    assertNull(runtimeService.getVariable(businessProcess.getExecutionId(), "aVariableLocalName"));

    // flush the cache
    businessProcess.flushVariableCache();

    // the variable is flushed to the execution
    assertNotNull(runtimeService.getVariable(businessProcess.getExecutionId(), "aVariableName"));

    // the local variable is flushed to the execution
    assertNotNull(runtimeService.getVariable(businessProcess.getExecutionId(), "aVariableLocalName"));

    // the cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getCachedVariableMap());

    // the cache is empty
    assertEquals(Collections.EMPTY_MAP, businessProcess.getCachedLocalVariableMap());

  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testSaveTask() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // cannot save task in absence of an association:
    try {
      businessProcess.saveTask();
      fail();
    } catch (ProcessEngineCdiException e) {
      assertEquals("No task associated. Call businessProcess.startTask() first.", e.getMessage());
    }

    // start the process
    String processInstanceId = businessProcess.startProcessByKey("businessProcessBeanTest", Collections.singletonMap("key", (Object) "value")).getId();
    assertEquals("value", runtimeService.getVariable(processInstanceId, "key"));

    businessProcess.startTask(taskService.createTaskQuery().singleResult().getId());

    // assignee is not set to jonny
    assertNull(taskService.createTaskQuery().taskAssignee("jonny").singleResult());
    Task task = businessProcess.getTask();
    task.setAssignee("jonny");

    assertNull(taskService.createTaskQuery().taskAssignee("jonny").singleResult());

    // if we save the task
    businessProcess.saveTask();

    // THEN

    // assignee is now set to jonny
    assertNotNull(taskService.createTaskQuery().taskAssignee("jonny").singleResult());
    // business process is still associated with task:
    assertTrue(businessProcess.isTaskAssociated());
  }

  @Test
  @Deployment(resources = "org/camunda/bpm/engine/cdi/test/api/BusinessProcessBeanTest.test.bpmn20.xml")
  public void testStopTask() {
    BusinessProcess businessProcess = getBeanInstance(BusinessProcess.class);

    // cannot stop task in absence of an association:
    try {
      businessProcess.stopTask();
      fail();
    } catch (ProcessEngineCdiException e) {
      assertEquals("No task associated. Call businessProcess.startTask() first.", e.getMessage());
    }

    // start the process
    String processInstanceId = businessProcess.startProcessByKey("businessProcessBeanTest", Collections.singletonMap("key", (Object) "value")).getId();
    assertEquals("value", runtimeService.getVariable(processInstanceId, "key"));

    businessProcess.startTask(taskService.createTaskQuery().singleResult().getId());

    // assignee is not set to jonny
    assertNull(taskService.createTaskQuery().taskAssignee("jonny").singleResult());
    Task task = businessProcess.getTask();
    task.setAssignee("jonny");

    // if we stop the task
    businessProcess.stopTask();

    // THEN

    // assignee is not set to jonny
    assertNull(taskService.createTaskQuery().taskAssignee("jonny").singleResult());
    // business process is not associated with task:
    assertFalse(businessProcess.isTaskAssociated());
    assertFalse(businessProcess.isAssociated());
  }

}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chapter 2 Example 13 - Scale and Rotate a Non Square</title>

    <script>

        var Debugger ={};

        Debugger.log = function(message){
            try{
                console.log(message);
            }catch(exception){
                return;
            }
        };

        window.addEventListener("load", eventWindowLoaded, false);

        function eventWindowLoaded(){
            Debugger.log('load event');
            canvasApp();
        }

        function canvasApp(){

            if(!canvasSupport()){
                return;
            };

            var theCanvas = document.getElementById("canvasOne");
            var context = theCanvas.getContext("2d");

            Debugger.log('loading canvas app');

            drawScreen();

            function canvasSupport(){
                return !!document.createElement("canvas").getContext;
            }

            function drawScreen(){
                Debugger.log('drawing screen');

                // scale and rotate a rectangle

                var x = 100;
                var y = 100;
                var width = 100;
                var height = 50;

                // find the center points
                var midpoint_x = x + width / 2;
                var midpoint_y = y + height / 2;

                // find the new origin points
                var new_origin_x = width * -.5;
                var new_origin_y = height * -.5;

                context.translate(midpoint_x, midpoint_y);
                context.fillStyle = 'blue';
                context.scale(2, 2);
                context.rotate(degressToRadians(90));
                context.fillRect(new_origin_x, new_origin_y, width, height);
            }

            function degressToRadians(degrees){
                return (Math.PI/180) * degrees;
            }
        }
    </script>
</head>
<body>
    <canvas id = "canvasOne" width="500" height="500">
        Your browser does not support HTML5 canvas.
    </canvas>
</body>
</html>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FakeItEasy;
using FluentAssertions;
using NUnit.Framework;
using Playground.Tests;
using Playground.TicketOffice.Theater.Data.Contracts;
using Playground.TicketOffice.Theater.Domain;
using Playground.TicketOffice.Theater.Read.Queries;
using Ploeh.AutoFixture;

namespace Playground.TicketOffice.Theater.Read.Handlers.UnitTests
{
    public class GetAllMovieTheatersQueryHandlerTests
        : TestBaseWithSut<GetAllMovieTheatersQueryHandler>
    {
        [Test]
        public async Task Handle_WillReturnMappedMovieTheaters_WhenThereAreAvailable()
        {
            // arrange
            var theaters = Fixture
                .Build<MovieTheater>()
                .FromFactory<Guid, string>((id, name) => new MovieTheater(id, name))
                .CreateMany()
                .ToList();

            A.CallTo(() => Faker.Resolve<IMovieTheaterRepository>()
                .GetAll())
                .Returns(theaters);

            var expectedResult = new GetAllMovieTheatersQueryResult
            {
                Theaters = theaters
            };

            // act
            var result = await Sut
                .Handle(new GetAllMovieTheatersQuery())
                .ConfigureAwait(false);

            // assert
            result.ShouldBeEquivalentTo(expectedResult);
        }

        [Test]
        public async Task Handle_WillReturnEmpty_WhenThereAreNoneAvailable()
        {
            // arrange
            var expectedResult = new GetAllMovieTheatersQueryResult
            {
                Theaters = new List<MovieTheater>()
            };

            // act
            var result = await Sut
                .Handle(new GetAllMovieTheatersQuery())
                .ConfigureAwait(false);

            // assert
            result.ShouldBeEquivalentTo(expectedResult);
        }

        [Test]
        public async Task Handle_WillReturnEmpty_WhenThereNull()
        {
            // arrange
            A.CallTo(() => Faker.Resolve<IMovieTheaterRepository>()
                .GetAll())
                .Returns(null as IEnumerable<MovieTheater>);

            var expectedResult = new GetAllMovieTheatersQueryResult
            {
                Theaters = new List<MovieTheater>()
            };

            // act
            var result = await Sut
                .Handle(new GetAllMovieTheatersQuery())
                .ConfigureAwait(false);

            // assert
            result.ShouldBeEquivalentTo(expectedResult);
        }
    }
}


text:
{% extends "base.html" %}
{% load i18n account_tags %}
{% block bodyclass %}user_purchases{% endblock %}
{% block title %}{% trans "Your purchases" %}{% endblock %}
{% block page_title %}{% trans "Your purchases" %}{% endblock %}
{% block content %}
    {% regroup tickets by purchase as purchase_list %}
    {% for purchase in purchase_list %}

{% trans "Invoice number" %}:

{{ purchase.grouper.full_invoice_number }}

{% trans "Date" %}:

{{ purchase.grouper.date_added|date }}

{% trans "Total price (incl. 19% VAT)" %}:

{{ purchase.grouper.payment_total|floatformat:2 }} EUR

            {% if purchase.grouper.state %}

{% trans "Status" %}:

{% if purchase.grouper.state == 'invoice_created' %}{% trans "Payment pending" %}{% else %}{{ purchase.grouper.get_state_display|capfirst }}{% endif %}

            {% endif %}

        {% if purchase.grouper.state == 'invoice_created' %}

{% trans "We have not yet received your payment. You can find account details on your invoice." %}

        {% endif %}
        {% if purchase.grouper.state == 'canceled' %}

{% trans "This purchase was canceled." %}

        {% endif %}

{% trans "Billing address" %}

                {{ purchase.grouper.first_name }} {{ purchase.grouper.last_name }}

                {{ purchase.grouper.street }}

                {{ purchase.grouper.zip_code }} {{ purchase.grouper.country }}

            {% if purchase.grouper.exported and purchase.grouper.state != 'canceled' %}

                <form action="{% url 'attendees_user_resend_invoice' %}" method="post">
                    {% csrf_token %}
                    <input type="hidden" value="{{ purchase.grouper.id }}" name="p" />
                    <input type="submit" value="{% trans "Resend invoice" %}" class="btn btn-primary" />
                </form>

            {% endif %}

{% trans "Tickets" %}

                {% for ticket in purchase.list %}

                    {% if ticket.canceled %}
                        {% trans "Canceled" %}
                        {{ ticket.ticket_type.name }}:
                        {{ ticket.real_ticket.first_name }} {{ ticket.real_ticket.last_name }}
                    {% else %}

                            {% if purchase.grouper.state == 'payment_received' %}
                                {% if not ticket.user or ticket.user == user %}
                                    {{ ticket.ticket_type.name }}:
                                {% else %}
                                    {{ ticket.ticket_type.name }}:
                                {% endif %}
                            {% else %}
                                {{ ticket.ticket_type.name }}:
                            {% endif %}

{{ ticket.real_ticket.first_name }} {{ ticket.real_ticket.last_name }}

                            {% if purchase.grouper.state == 'payment_received' %}
                                {% if ticket.user %}

{% blocktrans with username=ticket.user|display_name %}This ticket has been assigned to {{ username }}. Please contact the helpdesk if
                                    you want to change this.{% endblocktrans %}

                                {% else %}
                                    {% url 'attendees_assign_ticket' pk=ticket.pk as assign_url %}
                                    {% blocktrans %}This ticket is not assigned to a specific user account. Hence we will only print the name and organization given during the purchase process of the ticket on the badge. For more flexibility and more information on the badge, please  assign the ticket to a user. This may require the intended owner to sign-up if no account has been created before.{% endblocktrans %}
                                {% endif %}
                            {% else %}

{% trans "Please complete the purchase first for further ticket options." %}

                            {% endif %}

                    {% endif %}

                {% endfor %}

    {% empty %}

{% trans "You haven't made any purchases yet." %}
    {% endfor %}
{% endblock %}


text:
CKEDITOR.plugins.setLang( 'a11yhelp', 'eo', {
	title: 'Uzindikoj pri atingeblo',
	contents: 'Helpilenhavo. Por fermi tiun dialogon, premu la ESKAPAN klavon.',
	legend: [
		{
		name: 'Ĝeneralaĵoj',
		items: [
			{
			name: 'Ilbreto de la redaktilo',
			legend: 'Premu ${toolbarFocus} por atingi la ilbreton. Moviĝu al la sekva aŭ antaŭa grupoj de la ilbreto per la klavoj TABA kaj MAJUSKLIGA-TABA. Moviĝu al la sekva aŭ antaŭa butonoj de la ilbreto per la klavoj SAGO DEKSTREN kaj SAGO MALDEKSTREN. Premu la SPACETklavon aŭ la ENENklavon por aktivigi la ilbretbutonon.'
		},

			{
			name: 'Redaktildialogo',
			legend: 'En dialogo, premu la TABAN klavon por navigi al la sekva dialogkampo, premu la MAJUSKLIGAN + TABAN klavojn por reveni al la antaŭa kampo, premu la ENENklavon por sendi la dialogon, premu la ESKAPAN klavon por nuligi la dialogon. Por dialogoj kun pluraj retpaĝoj sub langetoj, premu ALT + F10 por navigi al la langetlisto. Poste moviĝu al la sekva langeto per la klavo TABA aŭ SAGO DEKSTREN. Moviĝu al la antaŭa langeto per la klavoj MAJUSKLIGA + TABA aŭ  SAGO MALDEKSTREN. Premu la SPACETklavon aŭ la ENENklavon por selekti la langetretpaĝon.'
		},

			{
			name: 'Kunteksta menuo de la redaktilo',
			legend: 'Premu ${contextMenu} aŭ entajpu la KLAVKOMBINAĴON por malfermi la kuntekstan menuon. Poste moviĝu al la sekva opcio de la menuo per la klavoj TABA aŭ SAGO SUBEN. Moviĝu al la antaŭa opcio per la klavoj MAJUSKLGA + TABA aŭ SAGO SUPREN. Premu la SPACETklavon aŭ ENENklavon por selekti la menuopcion. Malfermu la submenuon de la kuranta opcio per la SPACETklavo aŭ la ENENklavo aŭ la SAGO DEKSTREN. Revenu al la elemento de la patra menuo per la klavoj ESKAPA aŭ SAGO MALDEKSTREN. Fermu la kuntekstan menuon per la ESKAPA klavo.'
		},

			{
			name: 'Fallisto de la redaktilo',
			legend: 'En fallisto, moviĝu al la sekva listelemento per la klavoj TABA aŭ SAGO SUBEN. Moviĝu al la antaŭa listelemento per la klavoj MAJUSKLIGA + TABA aŭ SAGO SUPREN. Premu la SPACETklavon aŭ ENENklavon por selekti la opcion en la listo. Premu la ESKAPAN klavon por fermi la falmenuon.'
		},

			{
			name: 'Breto indikanta la vojon al la redaktilelementoj',
			legend: 'Premu ${elementsPathFocus} por navigi al la breto indikanta la vojon al la redaktilelementoj. Moviĝu al la butono de la sekva elemento per la klavoj TABA aŭ SAGO DEKSTREN. Moviĝu al la butono de la antaŭa elemento per la klavoj MAJUSKLIGA + TABA aŭ SAGO MALDEKSTREN. Premu la SPACETklavon aŭ ENENklavon por selekti la elementon en la redaktilo.'
		}
		]
	},
		{
		name: 'Komandoj',
		items: [
			{
			name: 'Komando malfari',
			legend: 'Premu ${undo}'
		},
			{
			name: 'Komando refari',
			legend: 'Premu ${redo}'
		},
			{
			name: 'Komando grasa',
			legend: 'Premu ${bold}'
		},
			{
			name: 'Komando kursiva',
			legend: 'Premu ${italic}'
		},
			{
			name: 'Komando substreki',
			legend: 'Premu ${underline}'
		},
			{
			name: 'Komando ligilo',
			legend: 'Premu ${link}'
		},
			{
			name: 'Komando faldi la ilbreton',
			legend: 'Premu ${toolbarCollapse}'
		},
			{
			name: ' Access previous focus space command', // MISSING
			legend: 'Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING
		},
			{
			name: ' Access next focus space command', // MISSING
			legend: 'Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING
		},
			{
			name: 'Helpilo pri atingeblo',
			legend: 'Premu ${a11yHelp}'
		}
		]
	}
	]
});


text:
package io.spine.server.command;

import io.spine.core.AcceptsContracts;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marks a method as a command assignee.
 *
 *
A command assignee method must:
 *

 *
be annotated with {@link Assign @Assign};
 *
return an event message derived from {@link io.spine.base.EventMessage EventMessage}
 *         if there is only one event generated;
 *         or an {@code Iterable} of event messages for two or
 *         more events;
 *
accept a command message derived from {@link io.spine.base.CommandMessage CommandMessage}
 *         as the first parameter.
 *

 *
 *
Like other message-handling methods, command assignees are designed to be called by
 * the framework only. Therefore, it is recommended to declare them package-private
 * (or {@code internal} in Kotlin). It discourages developers from calling these methods directly
 * from anywhere. It is also acceptable to use {@code protected} if the declaring class inherits
 * the method from a superclass.
 *
 *
This level of access declares that a command assignee method is a part
 * of the Bounded Context-level API. See the {@link io.spine.core.BoundedContext
 * BoundedContext} description on how the packages and Bounded Contexts relate.
 *
 *
Accepted Parameters

 *
 *
The first parameter of the method always declares a type of the handled command.
 *
 *
The method may accept a {@link io.spine.core.CommandContext
 * CommandContext} as the second parameter, if handling of the command requires its context.
 *
 *

 *
 * {@literal @}Assign
 *  TaskCreated handle(CreateTask command) { ... }
 *
 * {@literal @}Assign
 *  TaskCompleted handle(CompleteTask command, CommandContext context) { ... }
 *

 *
 *
In case a command may be rejected, a corresponding {@code Throwable} should be declared:
 *
 *

 *
 * {@literal @}Assign
 *  TaskStarted handle(StartTask command) throws TaskAlreadyInProgress { ... }
 *

 *
 *
If the annotation is applied to a method which doesn't satisfy any of these requirements,
 * this method is not considered a command assignee and is not registered for
 * command dispatching.
 *
 *
Returning Values

 *
 *
As a command is an imperative, it must lead to some outcome. Typically, a command results
 * in an emission of one or more events. Each of them must derive
 * from {@link io.spine.base.EventMessage EventMessage} in order to make the code less error-prone.
 *
 *
A command assignee method must return either
 *

 *
 *
an event message:
 *

 *
 * {@literal @}Assign
 *  TaskReassigned handle(ReassignTask command) { ... }
 *

 *
 *
 *
an {@code Iterable} of event messages:
 *

 *
 * {@literal @}Assign
 * {@literal Iterable<TaskCompleted>} handle(CompleteProject event) { ... }
 *

 *
 *
 *
a {@link io.spine.server.tuple.Tuple tuple} of event messages; being similar
 *  to {@code Iterable}, tuples allow to declare the exact types of returning values, including
 *  {@code Optional} values:
 *

 *
 * {@literal @}Assign
 * {@literal Pair<ProjectCreated, ProjectAssigned>} handle(CreateProject event) { ... }
 *
 * {@literal @}Assign
 * {@literal Pair<TaskCreated, Optional<TaskAssigned>>} handle(CreateTask event) { ... }
 *

 *
 *
 *
{@linkplain io.spine.server.tuple.Either one of} particular events:
 *

 *
 * {@literal @}Assign
 * {@literal EitherOf2<TaskRemovedFromProject, TaskDeleted>} handle(RemoveTask command) { ... }
 *

 *

 *
 *
One Handler per Command

 *
 *
An application must have one and only one handler per command message class.
 * This includes {@linkplain io.spine.server.command.Command the case} of transforming an incoming
 * command into one or more commands that will to be handled instead of the received one.
 *
 *
Declaring two methods that handle the same command class will result in run-time error.
 *
 * @see io.spine.server.tuple.Tuple Returning Two or More Event Messages
 * @see io.spine.server.tuple.Either Returning One of Event Messages
 * @see io.spine.server.command.Command Transforming Commands
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@AcceptsContracts
public @interface Assign {
}


text:
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you 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.
  -->

<ipojo>
    <component
            classname="org.apache.felix.ipojo.runtime.core.components.ComponentUsingField"
            name="CTX-Field-Component" architecture="true">
        <provides/>
        <!-- component is default -->
        <context field="context"/>
    </component>

    <component
            classname="org.apache.felix.ipojo.runtime.core.components.ComponentUsingField"
            name="CTX-Field-Instance" architecture="true">
        <provides/>
        <context field="context" context="instance"/>
    </component>

    <component
            classname="org.apache.felix.ipojo.runtime.core.components.ComponentUsingMethod"
            name="CTX-Method-Component" architecture="true">
        <provides/>
        <!-- component is default -->
        <context method="setContext"/>
    </component>

    <component
            classname="org.apache.felix.ipojo.runtime.core.components.ComponentUsingMethod"
            name="CTX-Method-Instance" architecture="true">
        <provides/>
        <!-- component is default -->
        <context method="setContext" context="instance"/>
    </component>

    <component
            classname="org.apache.felix.ipojo.runtime.core.components.ComponentUsingConstructor"
            name="CTX-Constructor-Component" architecture="true">
        <provides/>
        <context constructor-parameter="0" context="component"/>
    </component>

    <component
            classname="org.apache.felix.ipojo.runtime.core.components.ComponentUsingConstructor"
            name="CTX-Constructor-Instance" architecture="true">
        <provides/>
        <context constructor-parameter="0" context="instance"/>
    </component>
</ipojo>


text:
package com.liubing.mvc.core.cache.face.impl;

import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

import com.liubing.mvc.core.cache.face.ICache;

/**
 * LRU CACHE 实现
 *
 * @author liubingsmile@gmail.com
 *
 * @param <KEY>
 * @param <VALUE>
 */
public class CacheImpl<KEY, VALUE> implements ICache<KEY, VALUE> {

	private final ReentrantLock lock = new ReentrantLock();

	private final ConcurrentHashMap<KEY, VALUE> map = new ConcurrentHashMap<KEY, VALUE>();
	private final LinkedList<KEY> queue = new LinkedList<KEY>();
	private final int limit;

	public CacheImpl(int limit) {
		this.limit = limit;
	}

	public void put(KEY key, VALUE value) {
		VALUE oldValue = map.put(key, value);
		if (oldValue != null) {
			removeThenAddKey(key);
		} else {
			addKey(key);
		}
		if (map.size() > limit) {
			map.remove(removeLast());
		}
	}

	public VALUE get(KEY key) {
		removeThenAddKey(key);
		return map.get(key);
	}

	private void addKey(KEY key) {
		lock.lock();
		try {
			queue.addFirst(key);
		} finally {
			lock.unlock();
		}

	}

	private KEY removeLast() {
		lock.lock();
		try {
			final KEY removedKey = queue.removeLast();
			return removedKey;
		} finally {
			lock.unlock();
		}
	}

	private void removeThenAddKey(KEY key) {
		lock.lock();
		try {
			queue.removeFirstOccurrence(key);
			queue.addFirst(key);
		} finally {
			lock.unlock();
		}

	}

	private void removeFirstOccurrence(KEY key) {
		lock.lock();
		try {
			queue.removeFirstOccurrence(key);
		} finally {
			lock.unlock();
		}

	}

	public VALUE getSilent(KEY key) {
		return map.get(key);
	}

	public void remove(KEY key) {
		removeFirstOccurrence(key);
		map.remove(key);
	}

	public int size() {
		return map.size();
	}

	public String toString() {
		return map.toString();
	}

}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LibRbxl.Instances;
using NUnit.Framework;

namespace LibRbxl.Test
{
    [TestFixture]
    public class SerializeDeserializeTests
    {
        [Test, Explicit] // This test fails under mono, but runs on windows. This need to be looked into.
        public void WorkspaceOnly()
        {
            var doc = new RobloxDocument();
            var workspace = new Workspace();
            doc.Children.Add(workspace);

            var stream = new MemoryStream();
            doc.Save(stream);
            stream.Position = 0;

            var doc2 = RobloxDocument.FromStream(stream);
            Assert.IsNotNull(doc2.Workspace);
        }
    }
}


text:
This file is used for connecting the Application Manager
and the applications themselves together.

This file must be used at every application in order to
make it work well.

Server-side services are always running when the resource is started.
Client-side services are will only run when the user is logged in and has the Application installed.

Client-side files will be downloaded directly when the Application is installed.
The already-downloaded files will be updated when it differs with the servers' on the load.

--]]-----------------------------<
-- Exports
---------------------------------<

g_ResourceRoot = getResourceRootElement(getThisResource())

local files = {}
local services = {}
local alias = nil
local icon = nil

local isLoaded = false
local filesReady = 0
local servucesReady = 0

local Revision = 1

addEventHandler("onClientResourceStart", g_ResourceRoot,
	function(resource)
		data = xmlLoadFile("data.xml")
		nodes = xmlNodeGetChildren(data)

		for i,node in ipairs(nodes) do
			if (xmlNodeGetName(node) == "file") then
				value = xmlNodeGetValue(node)
				table.insert(files,value)
			end
			if (xmlNodeGetName(node) == "service") then
				value = xmlNodeGetValue(node)
				table.insert(services,value)
			end
			if (xmlNodeGetName(node) == "alias") then
				value = xmlNodeGetValue(node)
				alias = value
			end
			if (xmlNodeGetName(node) == "icon") then
				value = xmlNodeGetValue(node)
				icon = value
			end
		end

		xmlUnloadFile(data)

		loadServices()
	end
)

function loadServices()
	for _,service in ipairs(services) do
		triggerServerEvent("onRequestServiceDownload", g_ResourceRoot,getLocalPlayer(), service)
	end
end

function loadApplication()
	updateFiles()
	isLoaded = true
end

function openApplication()
	if(isLoaded == false) then
		loadApplication()
	end

	if filesReady ~= true then
		setTimer(function()
			openApplication()
		end,1000,1)
		return
	end

	local filename = "@:BB_AppManager/Versions.xml"
	local node = xmlLoadFile(filename)
	if node then
		local resourceName = getResourceName(getThisResource())
		local childNode = xmlFindChild(node, resourceName, 0) or xmlCreateChild(node, resourceName)
		local version = tonumber(xmlNodeGetAttribute(childNode, "version"))
		if type(version) == "number" then
			if version < Revision then
				exports.BB_Notify:Notify("Files of the application are outdated,\nrejoin to update.", 2, "Error", 5000)
				xmlUnloadFile(node)
				return
			end
		else
			exports.BB_Notify:Notify("#FF0000Error: APP_XML_Load_Failure\n#FFFFFFCan't open #FF9900"..alias.."#FFFFFF, look at the \n#FF9900Getting Started App#FFFFFF to find out how\nto fix this.", 4, "Error", 5000)
		end
	else
		return
	end

	main()
end

function closeApplication()
	closeAPP()
	triggerEvent("onAppClose", g_ResourceRoot)
	return true
end

function liveTileUpdate(tile,mode)
	if not filesReady then return false end

	updateTile(tile,mode)
end

function isStillUpdating()
	if filesReady == true then return false else return true end
end

function giveMeDetails()
	return alias, icon
end

---------------------------------<
-- File updater
---------------------------------<

function updateFiles()
	local filename = "@:BB_AppManager/Versions.xml"
	local node = xmlLoadFile(filename) or xmlCreateFile(filename, "Apps")
	if node then
		local resourceName = getResourceName(getThisResource())
		local childNode = xmlFindChild(node, resourceName, 0) or xmlCreateChild(node, resourceName)
		local version = tonumber(xmlNodeGetAttribute(childNode, "version"))
		if type(version) ~= "number" then
			xmlNodeSetAttribute(childNode, "version", Revision)
			xmlSaveFile(node)
		end
		xmlUnloadFile(node)
	else
		return
	end

	for _,file in pairs(files) do
		updateFile(file)
	end

end

function updateFile(filename)
	triggerServerEvent("onRequestChecksumOfFile", g_ResourceRoot, getLocalPlayer(), filename)
end

addEvent("onClientRequestChecksumOfFile",true)
addEventHandler("onClientRequestChecksumOfFile",g_ResourceRoot,
	function(checksumA,filename)
		local file = fileExists(filename) and fileOpen(filename) or fileCreate(filename)
		local buffer = ""
		while not fileIsEOF(file) do
		    buffer = buffer..fileRead(file, 500)
		end
		fileClose(file)
		checksumB = sha256(buffer)
		if checksumA ~= checksumB then
			downloadFileAgain(filename)
		else
			if string.sub(filename, -4) == ".lua" then
				local lcall,err = loadstring(buffer)
				if(lcall == nil) then
					outputDebugString(err,1)
				else
					lcall()
				end
			end
			sendNotification()
		end
	end
)

function downloadFileAgain(filename)
	triggerServerEvent("onRequestDownload", g_ResourceRoot,getLocalPlayer(), filename)
end

addEvent("onClientDownloaded", true)
addEventHandler("onClientDownloaded", g_ResourceRoot,
	function(buffer, filename)
		local file = fileOpen(filename)
		if not file then
			file = fileCreate(filename)
		else
			fileClose(file)
			fileDelete(filename)
			file = fileCreate(filename)
		end
		fileWrite(file, buffer)
		fileClose(file)

		if string.sub(filename, -4) == ".lua" then
			local lcall,err = loadstring(buffer)
			if(lcall == nil) then
				outputDebugString(err,1)
			else
				lcall()
			end
		end
		sendNotification()
	end
)

addEvent("onClientDownloadedService", true)
addEventHandler("onClientDownloadedService", g_ResourceRoot,
	function(buffer, filename)
		if string.sub(filename, -4) == ".lua" then
			local lcall,err = loadstring(buffer)
			if(lcall == nil) then
				outputDebugString(err,1)
			else
				lcall()
			end
		end
		sendServiceNotification()
	end
)

function sendNotification()
	filesReady = filesReady+1
	if filesReady == #files then
		triggerEvent("onClientFilesAreAllDownloaded", g_ResourceRoot)
		filesReady = true
	end
end

function sendServiceNotification()
	servicesReady = filesReady+1
	if servicesReady == #services then
		triggerEvent("onServiceStart", g_ResourceRoot)
		servicesReady = true
	end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/D:/GitRepository/love/love/sdk/pulltorefresh/res/values-ru/pull_refresh_strings.xml -->
    <eat-comment/>
    <string name="pull_to_refresh_pull_label">Потяните для обновления…</string>
    <string name="pull_to_refresh_refreshing_label">Загрузка…</string>
    <string name="pull_to_refresh_release_label">Отпустите для обновления…</string>
</resources>


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

using MarsRover.Business.Core;
using MarsRover.Business.Contract;

namespace MarsRover.Business.Domain
{
	public class SpaceStation : ISpaceStation
	{
		private Queue<string> _unprocessedCommands;
		public Queue<string> UnprocessedCommands {
			get {
				return _unprocessedCommands;
			}
		}

		private Queue<IResearchInfo> _researchInfos;
		public Queue<IResearchInfo> ResearchInfos {
			get {
				return _researchInfos;
			}
		}

		public IPlanet Mars {
			get { return _mars; }
		}

		private ICommandParser _commandParser;
		private IPlanet _mars;

		public SpaceStation (IPlanet mars, ICommandParser commandParser)
		{
			_mars = mars;
			_commandParser = commandParser;

			_unprocessedCommands = new Queue<string> ();
			_researchInfos = new Queue<IResearchInfo> ();
		}

		public void ValidateCommandsAndEnqueueResearchInfos ()
		{
			while (UnprocessedCommands.Count > 0) {
				var command = UnprocessedCommands.Dequeue ();

				if (Mars == null) {
					throw new Exception ("space station should connect to mars");
				}

				if (Mars.Plateau == null) {
					var plateauMetrics = _commandParser.GetPlateauMetrics (command);
					Mars.Plateau = DefinePlateau (plateauMetrics [0], plateauMetrics [1]);
				}

				var researchInfos = _commandParser.GetResearchInfos (command);
				foreach (var info in researchInfos) {
					ResearchInfos.Enqueue (info);
				}
			}
		}

		public IPlateau DefinePlateau (int width, int height)
		{
			return new Plateau (width, height);
		}

		public bool StartResearching ()
		{
			if (ResearchInfos.Count == 0)
				throw new Exception ("there is no research info to run rovers");

			DoNextResearch ();

			return true;
		}

		void roverResearchEnded (object sender, EventArgs e)
		{
			var args = (ResearchEndedEventArgs)e;
			Console.WriteLine ("rover research ended > " + args.Position);
			DoNextResearch ();
		}

		private void DoNextResearch ()
		{
			if (ResearchInfos.Count == 0) {
				Console.WriteLine ("all researches completed...");
				return;
			}

			var researchInfo = ResearchInfos.Dequeue ();
			var rover = ConnectToRover ();
			rover.ResearchEnded += roverResearchEnded;
			rover.Research (researchInfo);
		}

		IRover ConnectToRover ()
		{
			if (Mars.Rovers.Count == 0)
				throw new Exception ("there is no rover on mars");

			var rover = Mars.Rovers.FirstOrDefault (x => !x.IsResearching);
			if (rover == null)
				throw new Exception ("all rovers are busy please try again later");

			rover.IsResearching = true;
			return rover;
		}
	}
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.appservice.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Meta data about operation used for display in portal. */
@Fluent
public final class CsmOperationDisplay {
    /*
     * The provider property.
     */
    @JsonProperty(value = "provider")
    private String provider;

    /*
     * The resource property.
     */
    @JsonProperty(value = "resource")
    private String resource;

    /*
     * The operation property.
     */
    @JsonProperty(value = "operation")
    private String operation;

    /*
     * The description property.
     */
    @JsonProperty(value = "description")
    private String description;

    /**
     * Get the provider property: The provider property.
     *
     * @return the provider value.
     */
    public String provider() {
        return this.provider;
    }

    /**
     * Set the provider property: The provider property.
     *
     * @param provider the provider value to set.
     * @return the CsmOperationDisplay object itself.
     */
    public CsmOperationDisplay withProvider(String provider) {
        this.provider = provider;
        return this;
    }

    /**
     * Get the resource property: The resource property.
     *
     * @return the resource value.
     */
    public String resource() {
        return this.resource;
    }

    /**
     * Set the resource property: The resource property.
     *
     * @param resource the resource value to set.
     * @return the CsmOperationDisplay object itself.
     */
    public CsmOperationDisplay withResource(String resource) {
        this.resource = resource;
        return this;
    }

    /**
     * Get the operation property: The operation property.
     *
     * @return the operation value.
     */
    public String operation() {
        return this.operation;
    }

    /**
     * Set the operation property: The operation property.
     *
     * @param operation the operation value to set.
     * @return the CsmOperationDisplay object itself.
     */
    public CsmOperationDisplay withOperation(String operation) {
        this.operation = operation;
        return this;
    }

    /**
     * Get the description property: The description property.
     *
     * @return the description value.
     */
    public String description() {
        return this.description;
    }

    /**
     * Set the description property: The description property.
     *
     * @param description the description value to set.
     * @return the CsmOperationDisplay object itself.
     */
    public CsmOperationDisplay withDescription(String description) {
        this.description = description;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library

Public Module Extensions_546

	''' <summary>
	'''     Indicates whether the character at the specified position in a specified string is categorized as a decimal
	'''     digit.
	''' </summary>
	''' <param name="s">A string.</param>
	''' <param name="index">The position of the character to evaluate in .</param>
	''' <returns>true if the character at position  in  is a decimal digit; otherwise, false.</returns>
	<System.Runtime.CompilerServices.Extension> _
	Public Function IsDigit(s As [String], index As Int32) As [Boolean]
		Return [Char].IsDigit(s, index)
	End Function
End Module


text:
/* In combinatorics, the number of ways to choose k different members out of a group of n different elements (also known as the number of combinations) is calculated by the following formula: formula For example, there are 2598960 ways to withdraw 5 cards out of a standard deck of 52 cards.
Your task is to write a program that calculates n! / (k! * (n-k)!) for given n and k (1 < k < n < 100). Try to use only two loops. */

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter (1 < K < N < 100)");
        Console.Write("Enter N: ");
        int n = int.Parse(Console.ReadLine());
        Console.Write("Enter K: ");
        int k = int.Parse(Console.ReadLine());
        long factorielN = 1, factorielK = 1, factorielNMinusK = 1;
        int nMinusK = n - k;
        if ((n > 0 && k > 0) && (n < 100 && k < 100) && (n > k))
        {
            while (true)
            {
                if (n != 0)
                {
                    factorielN *= n;
                    n--;
                }
                else if (k != 0)
                {
                    factorielK *= k;
                    k--;
                }
                else
                {
                    break;
                }
            }
            while (true)
            {
                if (nMinusK != 0)
                {
                    factorielNMinusK *= nMinusK;
                    nMinusK--;
                }
                else
                {
                    break;
                }

            }
            Console.WriteLine(factorielN / (factorielK * factorielNMinusK)); // n! / (k! * (n-k)!)
        }
        else
        {
            Console.WriteLine("Wrong Input!");
        }
    }
}


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

/**
 * The ElevensBoard class represents the board in a game of Elevens.
 */
public class ElevensBoard extends Board {

	/**
	 * The size (number of cards) on the board.
	 */
	private static final int BOARD_SIZE = 9;

	/**
	 * The ranks of the cards for this game to be sent to the deck.
	 */
	private static final String[] RANKS =
		{"ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "jack", "queen", "king"};

	/**
	 * The suits of the cards for this game to be sent to the deck.
	 */
	private static final String[] SUITS =
		{"spades", "hearts", "diamonds", "clubs"};

	/**
	 * The values of the cards for this game to be sent to the deck.
	 */
	private static final int[] POINT_VALUES =
		{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0};

	/**
	 * Flag used to control debugging print statements.
	 */
	private static final boolean I_AM_DEBUGGING = false;

	/**
	 * Creates a new ElevensBoard instance.
	 */
	 public ElevensBoard() {
	 	super(BOARD_SIZE, RANKS, SUITS, POINT_VALUES);
	 }

	/**
	 * Determines if the selected cards form a valid group for removal.
	 * In Elevens, the legal groups are (1) a pair of non-face cards
	 * whose values add to 11, and (2) a group of three cards consisting of
	 * a jack, a queen, and a king in some order.
	 * @param selectedCards the list of the indices of the selected cards.
	 * @return true if the selected cards form a valid group for removal;
	 *         false otherwise.
	 */
	@Override
	public boolean isLegal(List<Integer> selectedCards) {
		if (selectedCards.size() == 2) {
			return containsPairSum11(selectedCards);
		} else if (selectedCards.size() == 3) {
			return containsJQK(selectedCards);
		} else {
			return false;
		}
	}

	/**
	 * Determine if there are any legal plays left on the board.
	 * In Elevens, there is a legal play if the board contains
	 * (1) a pair of non-face cards whose values add to 11, or (2) a group
	 * of three cards consisting of a jack, a queen, and a king in some order.
	 * @return true if there is a legal play left on the board;
	 *         false otherwise.
	 */
	@Override
	public boolean anotherPlayIsPossible() {
		List<Integer> cIndexes = cardIndexes();
		return containsPairSum11(cIndexes) || containsJQK(cIndexes);
	}

	/**
	 * Check for an 11-pair in the selected cards.
	 * @param selectedCards selects a subset of this board.  It is list
	 *                      of indexes into this board that are searched
	 *                      to find an 11-pair.
	 * @return true if the board entries in selectedCards
	 *              contain an 11-pair; false otherwise.
	 */
	private boolean containsPairSum11(List<Integer> selectedCards) {
		for (int sk1 = 0; sk1 < selectedCards.size(); sk1++) {
			int k1 = selectedCards.get(sk1).intValue();
			for (int sk2 = sk1 + 1; sk2 < selectedCards.size(); sk2++) {
				int k2 = selectedCards.get(sk2).intValue();
				if (cardAt(k1).pointValue() + cardAt(k2).pointValue() == 11) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * Check for a JQK in the selected cards.
	 * @param selectedCards selects a subset of this board.  It is list
	 *                      of indexes into this board that are searched
	 *                      to find a JQK group.
	 * @return true if the board entries in selectedCards
	 *              include a jack, a queen, and a king; false otherwise.
	 */
	private boolean containsJQK(List<Integer> selectedCards) {
		boolean foundJack = false;
		boolean foundQueen = false;
		boolean foundKing = false;
		for (Integer kObj : selectedCards) {
			int k = kObj.intValue();
			if (cardAt(k).rank().equals("jack")) {
				foundJack = true;
			} else if (cardAt(k).rank().equals("queen")) {
				foundQueen = true;
			} else if (cardAt(k).rank().equals("king")) {
				foundKing = true;
			}
		}
		return foundJack && foundQueen && foundKing;
	}
}


text:
package interfaces;

import java.util.Iterator;

/**
 * Created by kkp on 03.08.15.
 */

public interface IRadar {
    Iterator<ITarget> getTargets(); //возвращает цели на радаре
}


text:
:: Purpose:       Remove the "Libraries" icon that appears on the desktop after certain Windows Updates are applied
:: Requirements:  Run this script as an Administrator
:: Author:        reddit.com/user/vocatus ( vocatus.gate at gmail ) // PGP key: 0x07d1490f82a211a2
:: Version:       1.0.0   Initial write
SETLOCAL

:::::::::::::::
:: VARIABLES :: -------------- These are the defaults. Change them if you so desire. --------- ::
:::::::::::::::
:: No user-set variables for this script

:: --------------------------- Don't edit anything below this line --------------------------- ::

:::::::::::::::::::::
:: PREP AND CHECKS ::
:::::::::::::::::::::
@echo off
%SystemDrive% && cls
set SCRIPT_VERSION=1.0.0
set SCRIPT_UPDATED=2015-08-27
:: Get the date into ISO 8601 standard date format (yyyy-mm-dd) so we can use it
FOR /f %%a in ('WMIC OS GET LocalDateTime ^| find "."') DO set DTS=%%a
set CUR_DATE=%DTS:~0,4%-%DTS:~4,2%-%DTS:~6,2%

title [Remove desktop "Libraries" Icon v%SCRIPT_VERSION%]

:::::::::::::
:: EXECUTE ::
:::::::::::::
reg delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\{031E4825-7B94-4dc3-B131-E946B44C8DD5} /f


text:
<?php namespace Fannan\AdvertisingModule\Slot\Contract;

use Anomaly\Streams\Platform\Entry\Contract\EntryRepositoryInterface;

interface SlotRepositoryInterface extends EntryRepositoryInterface
{

}


text:
layout: doc_page
---
Coordinator Node
================
For Coordinator Node Configuration, see [Coordinator Configuration](../configuration/coordinator.html).

The Druid coordinator node is primarily responsible for segment management and distribution. More specifically, the Druid coordinator node communicates to historical nodes to load or drop segments based on configurations. The Druid coordinator is responsible for loading new segments, dropping outdated segments, managing segment replication, and balancing segment load.

The Druid coordinator runs periodically and the time between each run is a configurable parameter. Each time the Druid coordinator runs, it assesses the current state of the cluster before deciding on the appropriate actions to take. Similar to the broker and historical nodes, the Druid coordinator maintains a connection to a Zookeeper cluster for current cluster information. The coordinator also maintains a connection to a database containing information about available segments and rules. Available segments are stored in a segment table and list all segments that should be loaded in the cluster. Rules are stored in a rule table and indicate how segments should be handled.

Before any unassigned segments are serviced by historical nodes, the available historical nodes for each tier are first sorted in terms of capacity, with least capacity servers having the highest priority. Unassigned segments are always assigned to the nodes with least capacity to maintain a level of balance between nodes. The coordinator does not directly communicate with a historical node when assigning it a new segment; instead the coordinator creates some temporary information about the new segment under load queue path of the historical node. Once this request is seen, the historical node will load the segment and begin servicing it.

### Running

```
io.druid.cli.Main server coordinator
```

Rules
-----

Segments can be automatically loaded and dropped from the cluster based on a set of rules. For more information on rules, see [Rule Configuration](../operations/rule-configuration.html).

Cleaning Up Segments
--------------------

Each run, the Druid coordinator compares the list of available database segments in the database with the current segments in the cluster. Segments that are not in the database but are still being served in the cluster are flagged and appended to a removal list. Segments that are overshadowed (their versions are too old and their data has been replaced by newer segments) are also dropped.

Segment Availability
--------------------

If a historical node restarts or becomes unavailable for any reason, the Druid coordinator will notice a node has gone missing and treat all segments served by that node as being dropped. Given a sufficient period of time, the segments may be reassigned to other historical nodes in the cluster. However, each segment that is dropped is not immediately forgotten. Instead, there is a transitional data structure that stores all dropped segments with an associated lifetime. The lifetime represents a period of time in which the coordinator will not reassign a dropped segment. Hence, if a historical node becomes unavailable and available again within a short period of time, the historical node will start up and serve segments from its cache without any those segments being reassigned across the cluster.

Balancing Segment Load
----------------------

To ensure an even distribution of segments across historical nodes in the cluster, the coordinator node will find the total size of all segments being served by every historical node each time the coordinator runs. For every historical node tier in the cluster, the coordinator node will determine the historical node with the highest utilization and the historical node with the lowest utilization. The percent difference in utilization between the two nodes is computed, and if the result exceeds a certain threshold, a number of segments will be moved from the highest utilized node to the lowest utilized node. There is a configurable limit on the number of segments that can be moved from one node to another each time the coordinator runs. Segments to be moved are selected at random and only moved if the resulting utilization calculation indicates the percentage difference between the highest and lowest servers has decreased.

HTTP Endpoints
--------------

The coordinator node exposes several HTTP endpoints for interactions.

### GET

* `/status`

Returns the Druid version, loaded extensions, memory used, total memory and other useful information about the node.

#### Coordinator information

* `/druid/coordinator/v1/leader`

Returns the current leader coordinator of the cluster.

* `/druid/coordinator/v1/loadstatus`

Returns the percentage of segments actually loaded in the cluster versus segments that should be loaded in the cluster.

 * `/druid/coordinator/v1/loadstatus?simple`

Returns the number of segments left to load until segments that should be loaded in the cluster are available for queries. This does not include replication.

* `/druid/coordinator/v1/loadstatus?full`

Returns the number of segments left to load in each tier until segments that should be loaded in the cluster are all available. This includes replication.

* `/druid/coordinator/v1/loadqueue`

Returns the ids of segments to load and drop for each historical node.

* `/druid/coordinator/v1/loadqueue?simple`

Returns the number of segments to load and drop, as well as the total segment load and drop size in bytes for each historical node.

* `/druid/coordinator/v1/loadqueue?full`

Returns the serialized JSON of segments to load and drop for each historical node.

#### Metadata store information

* `/druid/coordinator/v1/metadata/datasources`

Returns a list of the names of enabled datasources in the cluster.

* `/druid/coordinator/v1/metadata/datasources?includeDisabled`

Returns a list of the names of enabled and disabled datasources in the cluster.

* `/druid/coordinator/v1/metadata/datasources?full`

Returns a list of all enabled datasources with all metadata about those datasources as stored in the metadata store.

* `/druid/coordinator/v1/metadata/datasources/{dataSourceName}`

Returns full metadata for a datasource as stored in the metadata store.

* `/druid/coordinator/v1/metadata/datasources/{dataSourceName}/segments`

Returns a list of all segments for a datasource as stored in the metadata store.

* `/druid/coordinator/v1/metadata/datasources/{dataSourceName}/segments?full`

Returns a list of all segments for a datasource with the full segment metadata as stored in the metadata store.

* `/druid/coordinator/v1/metadata/datasources/{dataSourceName}/segments/{segmentId}`

Returns full segment metadata for a specific segment as stored in the metadata store.

#### Datasources information

* `/druid/coordinator/v1/datasources`

Returns a list of datasource names found in the cluster.

* `/druid/coordinator/v1/datasources?simple`

Returns a list of JSON objects containing the name and properties of datasources found in the cluster.  Properties include segment count, total segment byte size, minTime, and maxTime.

* `/druid/coordinator/v1/datasources?full`

Returns a list of datasource names found in the cluster with all metadata about those datasources.

* `/druid/coordinator/v1/datasources/{dataSourceName}`

Returns a JSON object containing the name and properties of a datasource. Properties include segment count, total segment byte size, minTime, and maxTime.

* `/druid/coordinator/v1/datasources/{dataSourceName}?full`

Returns full metadata for a datasource .

* `/druid/coordinator/v1/datasources/{dataSourceName}/intervals`

Returns a set of segment intervals.

* `/druid/coordinator/v1/datasources/{dataSourceName}/intervals?simple`

Returns a map of an interval to a JSON object containing the total byte size of segments and number of segments for that interval.

* `/druid/coordinator/v1/datasources/{dataSourceName}/intervals?full`

Returns a map of an interval to a map of segment metadata to a set of server names that contain the segment for that interval.

* `/druid/coordinator/v1/datasources/{dataSourceName}/intervals/{interval}`

Returns a set of segment ids for an ISO8601 interval.

* `/druid/coordinator/v1/datasources/{dataSourceName}/intervals/{interval}?simple`

Returns a map of segment intervals contained within the specified interval to a JSON object containing the total byte size of segments and number of segments for an interval.

* `/druid/coordinator/v1/datasources/{dataSourceName}/intervals/{interval}?full`

Returns a map of segment intervals contained within the specified interval to a map of segment metadata to a set of server names that contain the segment for an interval.

* `/druid/coordinator/v1/datasources/{dataSourceName}/segments`

Returns a list of all segments for a datasource in the cluster.

* `/druid/coordinator/v1/datasources/{dataSourceName}/segments?full`

Returns a list of all segments for a datasource in the cluster with the full segment metadata.

* `/druid/coordinator/v1/datasources/{dataSourceName}/segments/{segmentId}`

Returns full segment metadata for a specific segment in the cluster.

* `/druid/coordinator/v1/datasources/{dataSourceName}/tiers`

Return the tiers that a datasource exists in.

#### Rules

* `/druid/coordinator/v1/rules`

Returns all rules as JSON objects for all datasources in the cluster including the default datasource.

* `/druid/coordinator/v1/rules/{dataSourceName}`

Returns all rules for a specified datasource.

* `/druid/coordinator/v1/rules/{dataSourceName}?full`

Returns all rules for a specified datasource and includes default datasource.

* `/druid/coordinator/v1/rules/history?interval=<interval>`

 Returns audit history of rules for all datasources. default value of interval can be specified by setting `druid.audit.manager.auditHistoryMillis` (1 week if not configured) in coordinator runtime.properties

* `/druid/coordinator/v1/rules/{dataSourceName}/history?interval=<interval>`

 Returns audit history of rules for a specified datasource. default value of interval can be specified by setting `druid.audit.manager.auditHistoryMillis` (1 week if not configured) in coordinator runtime.properties

#### Intervals

* `/druid/coordinator/v1/intervals`

Returns all intervals for all datasources with total size and count.

* `/druid/coordinator/v1/intervals/{interval}`

Returns aggregated total size and count for all intervals that intersect given isointerval.

* `/druid/coordinator/v1/intervals/{interval}?simple`

Returns total size and count for each interval within given isointerval.

* `/druid/coordinator/v1/intervals/{interval}?full`

Returns total size and count for each datasource for each interval within given isointerval.

### POST

#### Datasources

* `/druid/coordinator/v1/datasources/{dataSourceName}`

Enables a datasource.

* `/druid/coordinator/v1/datasources/{dataSourceName}/segments/{segmentId}`

Enables a segment.

#### Rules

* `/druid/coordinator/v1/rules/{dataSourceName}`

POST with a list of rules in JSON form to update rules.

Optional Header Parameters for auditing the config change can also be specified.

|Header Param Name| Description | Default |
|----------|-------------|---------|
|`X-Druid-Author`| author making the config change|""|
|`X-Druid-Comment`| comment describing the change being done|""|

### DELETE

#### Datasources

* `/druid/coordinator/v1/datasources/{dataSourceName}`

Disables a datasource.

* `/druid/coordinator/v1/datasources/{dataSourceName}?kill=true&interval={myISO8601Interval}>`

Runs a [Kill task](../misc/tasks.html) for a given interval and datasource.

* `/druid/coordinator/v1/datasources/{dataSourceName}/segments/{segmentId}`

Disables a segment.

The Coordinator Console
------------------

The Druid coordinator exposes a web GUI for displaying cluster information and rule configuration. After the coordinator starts, the console can be accessed at:

```
http://<COORDINATOR_IP>:<COORDINATOR_PORT>
```

 There exists a full cluster view (which shows only the realtime and historical nodes), as well as views for individual historical nodes, datasources and segments themselves. Segment information can be displayed in raw JSON form or as part of a sortable and filterable table.

The coordinator console also exposes an interface to creating and editing rules. All valid datasources configured in the segment database, along with a default datasource, are available for configuration. Rules of different types can be added, deleted or edited.

FAQ
---

1. **Do clients ever contact the coordinator node?**

    The coordinator is not involved in a query.

    historical nodes never directly contact the coordinator node. The Druid coordinator tells the historical nodes to load/drop data via Zookeeper, but the historical nodes are completely unaware of the coordinator.

    Brokers also never contact the coordinator. Brokers base their understanding of the data topology on metadata exposed by the historical nodes via ZK and are completely unaware of the coordinator.

2. **Does it matter if the coordinator node starts up before or after other processes?**

    No. If the Druid coordinator is not started up, no new segments will be loaded in the cluster and outdated segments will not be dropped. However, the coordinator node can be started up at any time, and after a configurable delay, will start running coordinator tasks.

    This also means that if you have a working cluster and all of your coordinators die, the cluster will continue to function, it just won't experience any changes to its data topology.