text:
Some Issues and Questions
==================================

.. note::

    This FAQ is here only mostly for historic reasons.  Checkout
    `pytest Q&A at Stackoverflow <http://stackoverflow.com/search?q=pytest>`_
    for many questions and answers related to pytest and/or use
    :ref:`contact channels` to get help.

On naming, nosetests, licensing and magic
------------------------------------------------

How does pytest relate to nose and unittest?
+++++++++++++++++++++++++++++++++++++++++++++++++

``pytest`` and nose_ share basic philosophy when it comes
to running and writing Python tests.  In fact, you can run many tests
written for nose with ``pytest``.  nose_ was originally created
as a clone of ``pytest`` when ``pytest`` was in the ``0.8`` release
cycle.  Note that starting with pytest-2.0 support for running unittest
test suites is majorly improved.

how does pytest relate to twisted's trial?
++++++++++++++++++++++++++++++++++++++++++++++

Since some time ``pytest`` has builtin support for supporting tests
written using trial. It does not itself start a reactor, however,
and does not handle Deferreds returned from a test in pytest style.
If you are using trial's unittest.TestCase chances are that you can
just run your tests even if you return Deferreds.  In addition,
there also is a dedicated `pytest-twisted
<https://pypi.org/project/pytest-twisted/>`_ plugin which allows you to
return deferreds from pytest-style tests, allowing the use of
:ref:`fixtures` and other features.

how does pytest work with Django?
++++++++++++++++++++++++++++++++++++++++++++++

In 2012, some work is going into the `pytest-django plugin <https://pypi.org/project/pytest-django/>`_.  It substitutes the usage of Django's
``manage.py test`` and allows the use of all pytest features_ most of which
are not available from Django directly.

.. _features: features.html

What's this "magic" with pytest? (historic notes)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Around 2007 (version ``0.8``) some people thought that ``pytest``
was using too much "magic".  It had been part of the `pylib`_ which
contains a lot of unrelated python library code.  Around 2010 there
was a major cleanup refactoring, which removed unused or deprecated code
and resulted in the new ``pytest`` PyPI package which strictly contains
only test-related code.  This release also brought a complete pluginification
such that the core is around 300 lines of code and everything else is
implemented in plugins.  Thus ``pytest`` today is a small, universally runnable
and customizable testing framework for Python.   Note, however, that
``pytest`` uses metaprogramming techniques and reading its source is
thus likely not something for Python beginners.

A second "magic" issue was the assert statement debugging feature.
Nowadays, ``pytest`` explicitly rewrites assert statements in test modules
in order to provide more useful :ref:`assert feedback <assertfeedback>`.
This completely avoids previous issues of confusing assertion-reporting.
It also means, that you can use Python's ``-O`` optimization without losing
assertions in test modules.

You can also turn off all assertion interaction using the
``--assert=plain`` option.

.. _`py namespaces`: index.html
.. _`py/__init__.py`: http://bitbucket.org/hpk42/py-trunk/src/trunk/py/__init__.py

Why can I use both ``pytest`` and ``py.test`` commands?
+++++++++++++++++++++++++++++++++++++++++++++++++++++++

pytest used to be part of the py package, which provided several developer
utilities, all starting with ``py.<TAB>``, thus providing nice TAB-completion.
If you install ``pip install pycmd`` you get these tools from a separate
package. Once ``pytest`` became a separate package, the ``py.test`` name was
retained due to avoid a naming conflict with another tool. This conflict was
eventually resolved, and the ``pytest`` command was therefore introduced. In
future versions of pytest, we may deprecate and later remove the ``py.test``
command to avoid perpetuating the confusion.

pytest fixtures, parametrized tests
-------------------------------------------------------

.. _funcargs: funcargs.html

Is using pytest fixtures versus xUnit setup a style question?
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

For simple applications and for people experienced with nose_ or
unittest-style test setup using `xUnit style setup`_ probably
feels natural.  For larger test suites, parametrized testing
or setup of complex test resources using fixtures_ may feel more natural.
Moreover, fixtures are ideal for writing advanced test support
code (like e.g. the monkeypatch_, the tmpdir_ or capture_ fixtures)
because the support code can register setup/teardown functions
in a managed class/module/function scope.

.. _monkeypatch: monkeypatch.html
.. _tmpdir: tmpdir.html
.. _capture: capture.html
.. _fixtures: fixture.html

.. _`why pytest_pyfuncarg__ methods?`:

.. _`Convention over Configuration`: http://en.wikipedia.org/wiki/Convention_over_Configuration

Can I yield multiple values from a fixture function?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

There are two conceptual reasons why yielding from a factory function
is not possible:

* If multiple factories yielded values there would
  be no natural place to determine the combination
  policy - in real-world examples some combinations
  often should not run.

* Calling factories for obtaining test function arguments
  is part of setting up and running a test.  At that
  point it is not possible to add new test calls to
  the test collection anymore.

However, with pytest-2.3 you can use the :ref:`@pytest.fixture` decorator
and specify ``params`` so that all tests depending on the factory-created
resource will run multiple times with different parameters.

You can also use the ``pytest_generate_tests`` hook to
implement the `parametrization scheme of your choice`_. See also
:ref:`paramexamples` for more examples.

.. _`parametrization scheme of your choice`: http://tetamap.wordpress.com/2009/05/13/parametrizing-python-tests-generalized/

pytest interaction with other packages
---------------------------------------------------

Issues with pytest, multiprocess and setuptools?
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++

On Windows the multiprocess package will instantiate sub processes
by pickling and thus implicitly re-import a lot of local modules.
Unfortunately, setuptools-0.6.11 does not ``if __name__=='__main__'``
protect its generated command line script.  This leads to infinite
recursion when running a test that instantiates Processes.

As of mid-2013, there shouldn't be a problem anymore when you
use the standard setuptools (note that distribute has been merged
back into setuptools which is now shipped directly with virtualenv).

.. _nose: https://nose.readthedocs.io/en/latest/
.. _pylib: https://py.readthedocs.io/en/latest/
.. _`xUnit style setup`: xunit_setup.html


text:
/*
 * @author max
 */
package com.intellij.extapi.psi;

import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.StubBasedPsiElement;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.stubs.*;
import org.jetbrains.annotations.Nullable;

import java.util.List;

public class StubPathBuilder {
  private StubPathBuilder() {
  }

  public static StubPath build(StubBasedPsiElement psi) {
    if (psi instanceof PsiFile) {
      return null;
    }

    final StubElement liveStub = psi.getStub();
    if (liveStub != null) {
      return build(liveStub);
    }

    return buildForPsi(psi, ((PsiFileImpl)psi.getContainingFile()).calcStubTree()).getFirst();
  }

  public static StubPath build(StubElement stub) {
    if (stub instanceof PsiFileStub || stub == null) {
      return null;
    }

    final IStubElementType type = stub.getStubType();
    return new StubPath(build(stub.getParentStub()), type.getId(stub), type);
  }

  private static Pair<StubPath, StubElement> buildForPsi(PsiElement psi, StubTree tree) {
    if (psi instanceof PsiFile) {
      return new Pair<StubPath, StubElement>(null, tree.getRoot());
    }

    if (psi instanceof StubBasedPsiElement) {
      final IStubElementType type = ((StubBasedPsiElement)psi).getElementType();
      if (type.shouldCreateStub(psi.getNode())) {
        final Pair<StubPath, StubElement> parentPair = buildForPsi(psi.getParent(), tree);

        final StubElement parentStub = parentPair.getSecond();
        final List<StubElement> childrenStubs = parentStub.getChildrenStubs();
        for (StubElement childStub : childrenStubs) {
          if (childStub.getPsi() == psi) {
            final IStubElementType type1 = childStub.getStubType();
            return new Pair<StubPath, StubElement>(new StubPath(parentPair.getFirst(), type1.getId(childStub), type1), childStub);
          }
        }

        return new Pair<StubPath, StubElement>(null, null);
      }
    }

    return buildForPsi(psi.getParent(), tree);
  }

  @Nullable
  public static PsiElement resolve(PsiFile file, StubPath path) {
    PsiFileImpl fileImpl = (PsiFileImpl)file;
    StubTree tree = fileImpl.getStubTree();

    boolean foreign = (tree == null);
    if (foreign) {
      tree = fileImpl.calcStubTree();
    }

    StubElement stub = resolveStub(tree, path);

    if (foreign) {
      final PsiElement cachedPsi = ((StubBase)stub).getCachedPsi();
      if (cachedPsi != null) return cachedPsi;

      final ASTNode ast = fileImpl.findTreeForStub(tree, stub);
      return ast != null ? ast.getPsi() : null;
    }
    else {
      return stub != null ? stub.getPsi() : null;
    }
  }

  @Nullable
  public static StubElement resolveStub(StubTree tree, StubPath path) {
    if (path == null) {
      return tree.getRoot();
    }

    StubElement parentStub = resolveStub(tree, path.getParentPath());
    if (parentStub == null) {
      return null;
    }

    final String id = path.getId();
    final IStubElementType type = (IStubElementType)path.getType();
    final List<StubElement> children = parentStub.getChildrenStubs();

    if (id.startsWith("#")) {
      int count = Integer.parseInt(id.substring(1));

      for (StubElement child : children) {
        if (child.getStubType() == type) {
          count--;
          if (count == 0) {
            return child;
          }
        }
      }
      return null;
    }

    for (StubElement child : children) {
      if (child.getStubType() == type && id.equals(type.getId(child))) {
        return child;
      }
    }

    return null;
  }
}

redpajama_set_name: RedPajamaGithub


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

namespace Kaazing.K3po.NUnit
{
    internal interface BarrierStateListener
    {
        void Initial();
        void Notified();
        void Notifying();
    }
}


text:
Imports System
Imports Microsoft.VisualBasic
Imports ChartDirector

Public Class percentbar
    Implements DemoModule

    'Name of demo module
    Public Function getName() As String Implements DemoModule.getName
        Return "Percentage Bar Chart"
    End Function

    'Number of charts produced in this demo module
    Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts
        Return 1
    End Function

    'Main code for creating chart.
    'Note: the argument chartIndex is unused because this demo only has 1 chart.
    Public Sub createChart(viewer As WinChartViewer, chartIndex As Integer) _
        Implements DemoModule.createChart

        ' The data for the bar chart
        Dim data0() As Double = {100, 125, 245, 147, 67}
        Dim data1() As Double = {85, 156, 179, 211, 123}
        Dim data2() As Double = {97, 87, 56, 267, 157}

        ' The labels for the bar chart
        Dim labels() As String = {"Mon", "Tue", "Wed", "Thu", "Fri"}

        ' Create a XYChart object of size 500 x 320 pixels. Use a vertical gradient color from pale
        ' blue (e8f0f8) to sky blue (aaccff) spanning half the chart height as background. Set
        ' border to blue (88aaee). Use rounded corners. Enable soft drop shadow.
        Dim c As XYChart = New XYChart(500, 320)
        c.setBackground(c.linearGradientColor(0, 0, 0, c.getHeight() / 2, &He8f0f8, &Haaccff), _
            &H88aaee)
        c.setRoundedFrame()
        c.setDropShadow()

        ' Add a title to the chart using 15 points Arial Italic. Set top/bottom margins to 15
        ' pixels.
        Dim title As ChartDirector.TextBox = c.addTitle("Weekly Product Sales", "Arial Italic", 15)
        title.setMargin2(0, 0, 15, 15)

        ' Tentatively set the plotarea to 50 pixels from the left edge, and to just under the title.
        ' Set the width to 60% of the chart width, and the height to 50 pixels from the bottom edge.
        ' Use pale blue (e8f0f8) background, transparent border, and grey (aaaaaa) grid lines.
        c.setPlotArea(50, title.getHeight(), c.getWidth() * 6 / 10, c.getHeight() - _
            title.getHeight() - 50, &He8f0f8, -1, Chart.Transparent, &Haaaaaa)

        ' Add a legend box where the top-right corner is anchored at 10 pixels from the right edge,
        ' and just under the title. Use vertical layout and 8 points Arial font.
        Dim legendBox As LegendBox = c.addLegend(c.getWidth() - 10, title.getHeight(), True, _
            "Arial", 8)
        legendBox.setAlignment(Chart.TopRight)

        ' Set the legend box background and border to transparent
        legendBox.setBackground(Chart.Transparent, Chart.Transparent)

        ' Set the legend box icon size to 16 x 32 pixels to match with custom icon size
        legendBox.setKeySize(16, 32)

        ' Set axes to transparent
        c.xAxis().setColors(Chart.Transparent)
        c.yAxis().setColors(Chart.Transparent)

        ' Set the labels on the x axis
        c.xAxis().setLabels(labels)

        ' Add a percentage bar layer
        Dim layer As BarLayer = c.addBarLayer2(Chart.Percentage)

        ' Add the three data sets to the bar layer, using icons images with labels as data set names
        layer.addDataSet(data0, &H66aaee, _
            "<*block,valign=absmiddle*><*img=service.png*> Service<*/*>")
        layer.addDataSet(data1, &Heebb22, _
            "<*block,valign=absmiddle*><*img=software.png*> Software<*/*>")
        layer.addDataSet(data2, &Hcc88ff, _
            "<*block,valign=absmiddle*><*img=computer.png*> Hardware<*/*>")

        ' Use soft lighting effect with light direction from top
        layer.setBorderColor(Chart.Transparent, Chart.softLighting(Chart.Top))

        ' Enable data label at the middle of the the bar
        layer.setDataLabelStyle().setAlignment(Chart.Center)

        ' For a vertical stacked chart with positive data only, the last data set is always on top.
        ' However, in a vertical legend box, the last data set is at the bottom. This can be
        ' reversed by using the setLegend method.
        layer.setLegend(Chart.ReverseLegend)

        ' Adjust the plot area size, such that the bounding box (inclusive of axes) is 15 pixels
        ' from the left edge, just below the title, 10 pixels to the right of the legend box, and 15
        ' pixels from the bottom edge.
        c.packPlotArea(15, title.getHeight(), c.layoutLegend().getLeftX() - 10, c.getHeight() - 15)

        ' Output the chart
        viewer.Chart = c

        'include tool tip for the chart
        viewer.ImageMap = c.getHTMLImageMap("clickable", "", _
            "title='{dataSetName} revenue on {xLabel}: US${value}K ({percent}%)'")

    End Sub

End Class


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="PhpIncludePathManager">
    <include_path>
      <path value="$PROJECT_DIR$/vendor/myclabs/deep-copy" />
      <path value="$PROJECT_DIR$/vendor/theseer/tokenizer" />
      <path value="$PROJECT_DIR$/vendor/paragonie/random_compat" />
      <path value="$PROJECT_DIR$/vendor/composer" />
      <path value="$PROJECT_DIR$/vendor/mustache/mustache" />
      <path value="$PROJECT_DIR$/vendor/ralouphie/getallheaders" />
      <path value="$PROJECT_DIR$/vendor/phpunit/phpunit" />
      <path value="$PROJECT_DIR$/vendor/defuse/php-encryption" />
      <path value="$PROJECT_DIR$/vendor/sebastian/comparator" />
      <path value="$PROJECT_DIR$/vendor/sebastian/environment" />
      <path value="$PROJECT_DIR$/vendor/psr/http-message" />
      <path value="$PROJECT_DIR$/vendor/psr/container" />
      <path value="$PROJECT_DIR$/vendor/sebastian/global-state" />
      <path value="$PROJECT_DIR$/vendor/sebastian/object-enumerator" />
      <path value="$PROJECT_DIR$/vendor/codeigniter/framework" />
      <path value="$PROJECT_DIR$/vendor/sebastian/object-reflector" />
      <path value="$PROJECT_DIR$/vendor/doctrine/instantiator" />
      <path value="$PROJECT_DIR$/vendor/sebastian/exporter" />
      <path value="$PROJECT_DIR$/vendor/sebastian/recursion-context" />
      <path value="$PROJECT_DIR$/vendor/sebastian/diff" />
      <path value="$PROJECT_DIR$/vendor/sebastian/version" />
      <path value="$PROJECT_DIR$/vendor/sebastian/resource-operations" />
      <path value="$PROJECT_DIR$/vendor/sebastian/code-unit-reverse-lookup" />
      <path value="$PROJECT_DIR$/vendor/pimple/pimple" />
      <path value="$PROJECT_DIR$/vendor/phpdocumentor/type-resolver" />
      <path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-common" />
      <path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-docblock" />
      <path value="$PROJECT_DIR$/vendor/phar-io/version" />
      <path value="$PROJECT_DIR$/vendor/webmozart/assert" />
      <path value="$PROJECT_DIR$/vendor/phar-io/manifest" />
      <path value="$PROJECT_DIR$/vendor/guzzlehttp/guzzle" />
      <path value="$PROJECT_DIR$/vendor/guzzlehttp/psr7" />
      <path value="$PROJECT_DIR$/vendor/guzzlehttp/promises" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-timer" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-token-stream" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-code-coverage" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-file-iterator" />
      <path value="$PROJECT_DIR$/vendor/behat/transliterator" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-text-template" />
      <path value="$PROJECT_DIR$/vendor/phpspec/prophecy" />
      <path value="$PROJECT_DIR$/vendor/symfony/polyfill-ctype" />
      <path value="$PROJECT_DIR$/vendor/axisofstevil/stop-words" />
      <path value="$PROJECT_DIR$/vendor/annexare/countries-list" />
      <path value="$PROJECT_DIR$/vendor/adrienrn/php-mimetyper" />
      <path value="$PROJECT_DIR$/vendor/katzien/php-mime-type" />
      <path value="$PROJECT_DIR$/vendor/dflydev/apache-mime-types" />
      <path value="$PROJECT_DIR$/vendor/sebastian/type" />
      <path value="$PROJECT_DIR$/vendor/symfony/polyfill-mbstring" />
      <path value="$PROJECT_DIR$/vendor/symfony/mime" />
      <path value="$PROJECT_DIR$/vendor/symfony/polyfill-php72" />
      <path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-idn" />
      <path value="$PROJECT_DIR$/vendor/symfony/http-foundation" />
      <path value="$PROJECT_DIR$/vendor/symfony/deprecation-contracts" />
      <path value="$PROJECT_DIR$/vendor/symfony/polyfill-php80" />
      <path value="$PROJECT_DIR$/vendor/sebastian/code-unit" />
      <path value="$PROJECT_DIR$/vendor/phpunit/php-invoker" />
      <path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-normalizer" />
      <path value="$PROJECT_DIR$/vendor/symfony/polyfill-php70" />
      <path value="$PROJECT_DIR$/vendor/psr/http-client" />
      <path value="$PROJECT_DIR$/vendor/psr/simple-cache" />
      <path value="$PROJECT_DIR$/vendor/psr/log" />
      <path value="$PROJECT_DIR$/vendor/jeremykendall/php-domain-parser" />
    </include_path>
  </component>
  <component name="PhpProjectSharedConfiguration" php_language_level="7.2" />
  <component name="PhpUnit">
    <phpunit_settings>
      <PhpUnitSettings configuration_file_path="$PROJECT_DIR$/phpunit.xml" custom_loader_path="$PROJECT_DIR$/vendor/autoload.php" use_configuration_file="true" />
    </phpunit_settings>
  </component>
</project>


text:
module Azure::Cosmosdb::Mgmt::V2020_06_01_preview
  module Models
    #
    # The List operation response, that contains the restorable MongoDB
    # resources.
    #
    class RestorableMongodbResourcesListResult

      include MsRestAzure

      # @return [Array<DatabaseRestoreResource>] List of restorable MongoDB
      # resources, including the database and collection names.
      attr_accessor :value

      #
      # Mapper for RestorableMongodbResourcesListResult class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'RestorableMongodbResourcesListResult',
          type: {
            name: 'Composite',
            class_name: 'RestorableMongodbResourcesListResult',
            model_properties: {
              value: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'value',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'DatabaseRestoreResourceElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'DatabaseRestoreResource'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package org.achtern.AchternEngine.core.scenegraph.entity.renderpasses.light;

import org.achtern.AchternEngine.core.math.Matrix4f;
import org.achtern.AchternEngine.core.math.Vector3f;
import org.achtern.AchternEngine.core.rendering.Color;
import org.achtern.AchternEngine.core.rendering.shader.forward.suits.phong.PhongDirectional;
import org.achtern.AchternEngine.core.rendering.shadow.ShadowInfo;

public class DirectionalLight extends BaseLight {

    public DirectionalLight(Color color, float intensity) {
        super(color, intensity);

        setShader(PhongDirectional.getInstance());

        setShadowInfo(new ShadowInfo(new Matrix4f().initOrthographic(-30, 30, -30, 30, -30, 30)));
    }

    public Vector3f getDirection() {
        return getTransform().getTransformedRotation().getForward();
    }
}


text:
import isNil from "lodash/isNil";
import isArray from "lodash/isArray";
import isFunction from "lodash/isFunction";
import isObject from "lodash/isObject";
import mergeWith from "lodash/mergeWith";

import Fakerator from "lib/fakerator";

module.exports = function() {
	let locale = require("lib/locales/fr-FR");
	let fbLocale = require("lib/locales/default");

	// Merge locale and fallback
	locale = mergeWith(locale, fbLocale, (objValue) => {
		// DON'T MERGE ARRAYS
		if (isArray(objValue) || isFunction(objValue))
			return objValue;

		if (!isNil(objValue) && !isObject(objValue))
			return objValue;
	});

	return new Fakerator(locale);
};


text:
package com.helger.commons.collection.impl;

import java.util.Collections;
import java.util.NavigableSet;

import javax.annotation.Nonnull;

import com.helger.commons.annotation.CodingStyleguideUnaware;
import com.helger.commons.annotation.ReturnsMutableCopy;

/**
 * A special {@link NavigableSet} based interface with extended functionality
 * based on {@link ICommonsSortedSet}.
 *
 * @author Philip Helger
 * @param <ELEMENTTYPE>
 *        Set element type
 */
public interface ICommonsNavigableSet <ELEMENTTYPE> extends NavigableSet <ELEMENTTYPE>, ICommonsSortedSet <ELEMENTTYPE>
{
  @Override
  @Nonnull
  @CodingStyleguideUnaware
  default NavigableSet <ELEMENTTYPE> getAsUnmodifiable ()
  {
    return Collections.unmodifiableNavigableSet (this);
  }

  @Nonnull
  @ReturnsMutableCopy
  ICommonsNavigableSet <ELEMENTTYPE> getClone ();
}


text:
package seedu.mypotato.storage;

import java.io.IOException;
import java.util.Optional;
import java.util.logging.Logger;

import com.google.common.eventbus.Subscribe;

import seedu.mypotato.commons.core.ComponentManager;
import seedu.mypotato.commons.core.LogsCenter;
import seedu.mypotato.commons.events.model.TaskManagerChangedEvent;
import seedu.mypotato.commons.events.storage.ChangedFileLocationRequestEvent;
import seedu.mypotato.commons.events.storage.DataSavingExceptionEvent;
import seedu.mypotato.commons.exceptions.DataConversionException;
import seedu.mypotato.model.ReadOnlyTaskManager;
import seedu.mypotato.model.UserPrefs;

/**
 * Manages storage of AddressBook data in local storage.
 */
public class StorageManager extends ComponentManager implements Storage {

    private static final Logger logger = LogsCenter.getLogger(StorageManager.class);
    private TaskManagerStorage taskManagerStorage;
    private UserPrefsStorage userPrefsStorage;

    public StorageManager(TaskManagerStorage addressBookStorage, UserPrefsStorage userPrefsStorage) {
        super();
        this.taskManagerStorage = addressBookStorage;
        this.userPrefsStorage = userPrefsStorage;
    }

    public StorageManager(String addressBookFilePath, String userPrefsFilePath) {
        this(new XmlTaskManagerStorage(addressBookFilePath), new JsonUserPrefsStorage(userPrefsFilePath));
    }

    // ================ UserPrefs methods ==============================

    @Override
    public Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOException {
        return userPrefsStorage.readUserPrefs();
    }

    @Override
    public void saveUserPrefs(UserPrefs userPrefs) throws IOException {
        userPrefsStorage.saveUserPrefs(userPrefs);
    }

    // ================ AddressBook methods ==============================

    @Override
    public String getAddressBookFilePath() {
        return taskManagerStorage.getAddressBookFilePath();
    }

    @Override
    public Optional<ReadOnlyTaskManager> readAddressBook() throws DataConversionException, IOException {
        return readAddressBook(taskManagerStorage.getAddressBookFilePath());
    }

    @Override
    public Optional<ReadOnlyTaskManager> readAddressBook(String filePath) throws DataConversionException, IOException {
        logger.fine("Attempting to read data from file: " + filePath);
        return taskManagerStorage.readAddressBook(filePath);
    }

    @Override
    public void saveTaskList(ReadOnlyTaskManager addressBook) throws IOException {
        saveTaskList(addressBook, taskManagerStorage.getAddressBookFilePath());
    }

    @Override
    public void saveTaskList(ReadOnlyTaskManager addressBook, String filePath) throws IOException {
        logger.fine("Attempting to write to data file: " + filePath);
        taskManagerStorage.saveTaskList(addressBook, filePath);
    }

  //@@author A0135807A
    @Override
    public void setFileLocation(String filepath) {
        taskManagerStorage.setFileLocation(filepath);
    }

    @Override
    @Subscribe
    public void handleTaskListChangedEvent(TaskManagerChangedEvent event) {
        logger.info(LogsCenter.getEventHandlingLogMessage(event, "Local data changed, saving to file"));
        try {
            if (taskManagerStorage == null) {
                saveTaskList(event.data);
            } else {
                saveTaskList(event.data, taskManagerStorage.getAddressBookFilePath());
            }
        } catch (IOException e) {
            raise(new DataSavingExceptionEvent(e));
        }
    }

    @Override
    @Subscribe
    public void handleTaskManagerChangedEvent(ChangedFileLocationRequestEvent event) {
        logger.info(LogsCenter.getEventHandlingLogMessage(event, "Setting Storage Location Path"));
        this.setFileLocation(event.config.getAddressBookFilePath());
    }

}


text:
/**
 * Resource controller example:
 * @route /authors/:author_id/tags/(:tag_id)
 * @type {PlainObject}
 */
module.exports = require('../_fakeController')();


text:
<form class="login" ng-submit="login()">

		Your name:
		<input class="form-control" ng-model="username" maxlength="15" autofocus>

	<button type="submit" class="btn btn-warning form-control">Login</button>
</form>


text:
package fr.acinq.eclair.wire

import fr.acinq.bitcoin.Crypto.{PrivateKey, PublicKey}
import fr.acinq.bitcoin.{ByteVector32, ByteVector64, Satoshi}
import fr.acinq.eclair.blockchain.fee.FeeratePerKw
import fr.acinq.eclair.crypto.Mac32
import fr.acinq.eclair.{CltvExpiry, CltvExpiryDelta, MilliSatoshi, UInt64}
import org.apache.commons.codec.binary.Base32
import scodec.bits.{BitVector, ByteVector}
import scodec.codecs._
import scodec.{Attempt, Codec, DecodeResult, Err, SizeBound}

import java.net.{Inet4Address, Inet6Address, InetAddress}
import scala.Ordering.Implicits._
import scala.util.Try

object CommonCodecs {
  def discriminatorWithDefault[A](discriminator: Codec[A], fallback: Codec[A]): Codec[A] = new Codec[A] {
    def sizeBound: SizeBound = discriminator.sizeBound | fallback.sizeBound

    def encode(e: A): Attempt[BitVector] = discriminator.encode(e).recoverWith { case _ => fallback.encode(e) }

    def decode(b: BitVector): Attempt[DecodeResult[A]] = discriminator.decode(b).recoverWith {
      case _: KnownDiscriminatorType[_]#UnknownDiscriminator => fallback.decode(b)
    }
  }

  // this codec can be safely used for values < 2^63 and will fail otherwise
  // (for something smarter see https://github.com/yzernik/bitcoin-scodec/blob/master/src/main/scala/io/github/yzernik/bitcoinscodec/structures/UInt64.scala)
  val uint64overflow: Codec[Long] = int64.narrow(l => if (l >= 0) Attempt.Successful(l) else Attempt.failure(Err(s"overflow for value $l")), l => l)
  val uint64: Codec[UInt64] = bytes(8).xmap(b => UInt64(b), a => a.toByteVector.padLeft(8))

  val satoshi: Codec[Satoshi] = uint64overflow.xmapc(l => Satoshi(l))(_.toLong)
  val millisatoshi: Codec[MilliSatoshi] = uint64overflow.xmapc(l => MilliSatoshi(l))(_.toLong)

  val feeratePerKw: Codec[FeeratePerKw] = uint32.xmapc(l => FeeratePerKw(Satoshi(l)))(_.toLong)

  val cltvExpiry: Codec[CltvExpiry] = uint32.xmapc(CltvExpiry)(_.underlying)
  val cltvExpiryDelta: Codec[CltvExpiryDelta] = uint16.xmapc(CltvExpiryDelta)(_.underlying)

  // this is needed because some millisatoshi values are encoded on 32 bits in the BOLTs
  // this codec will fail if the amount does not fit on 32 bits
  val millisatoshi32: Codec[MilliSatoshi] = uint32.xmapc(l => MilliSatoshi(l))(_.toLong)

  val text: Codec[String] = variableSizeBytes(uint16, utf8)
  val optionalText: Codec[Option[String]] = optional(bool, text)

  /**
   * We impose a minimal encoding on some values (such as varint and truncated int) to ensure that signed hashes can be
   * re-computed correctly.
   * If a value could be encoded with less bytes, it's considered invalid and results in a failed decoding attempt.
   *
   * @param codec the value codec (depends on the value).
   * @param min   the minimal value that should be encoded.
   */
  def minimalvalue[A: Ordering](codec: Codec[A], min: A): Codec[A] = codec.exmap({
    case i if i < min => Attempt.failure(Err("value was not minimally encoded"))
    case i => Attempt.successful(i)
  }, Attempt.successful)

  // Bitcoin-style varint codec (CompactSize).
  // See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers for reference.
  val varint: Codec[UInt64] = discriminatorWithDefault(
    discriminated[UInt64].by(uint8L)
      .\(0xff) { case i if i >= UInt64(0x100000000L) => i }(minimalvalue(uint64, UInt64(0x100000000L)))
      .\(0xfe) { case i if i >= UInt64(0x10000) => i }(minimalvalue(uint32.xmap(UInt64(_), _.toBigInt.toLong), UInt64(0x10000)))
      .\(0xfd) { case i if i >= UInt64(0xfd) => i }(minimalvalue(uint16.xmap(UInt64(_), _.toBigInt.toInt), UInt64(0xfd))),
    uint8L.xmap(UInt64(_), _.toBigInt.toInt)
  )

  // This codec can be safely used for values < 2^63 and will fail otherwise.
  // It is useful in combination with variableSizeBytesLong to encode/decode TLV lengths because those will always be < 2^63.
  val varintoverflow: Codec[Long] = varint.narrow(l => if (l <= UInt64(Long.MaxValue)) Attempt.successful(l.toBigInt.toLong) else Attempt.failure(Err(s"overflow for value $l")), l => UInt64(l))

  val bytes32: Codec[ByteVector32] = limitedSizeBytes(32, bytesStrict(32).xmap(d => ByteVector32(d), d => d.bytes))

  val bytes64: Codec[ByteVector64] = limitedSizeBytes(64, bytesStrict(64).xmap(d => ByteVector64(d), d => d.bytes))

  val sha256: Codec[ByteVector32] = bytes32

  val varsizebinarydata: Codec[ByteVector] = variableSizeBytes(uint16, bytes)

  def mapCodec[K, V](keyCodec: Codec[K], valueCodec: Codec[V]): Codec[Map[K, V]] = listOfN(uint16, keyCodec ~ valueCodec).xmap(_.toMap, _.toList)

  def setCodec[T](codec: Codec[T]): Codec[Set[T]] = listOfN(uint16, codec).xmap(_.toSet, _.toList)

  val listofsignatures: Codec[List[ByteVector64]] = listOfN(uint16, bytes64)

  val ipv4address: Codec[Inet4Address] = bytes(4).xmap(b => InetAddress.getByAddress(b.toArray).asInstanceOf[Inet4Address], a => ByteVector(a.getAddress))

  val ipv6address: Codec[Inet6Address] = bytes(16).exmap(b => Attempt.fromTry(Try(Inet6Address.getByAddress(null, b.toArray, null))), a => Attempt.fromTry(Try(ByteVector(a.getAddress))))

  def base32(size: Int): Codec[String] = bytes(size).xmap(b => new Base32().encodeAsString(b.toArray).toLowerCase, a => ByteVector(new Base32().decode(a.toUpperCase())))

  val nodeaddress: Codec[NodeAddress] =
    discriminated[NodeAddress].by(uint8)
      .typecase(1, (ipv4address :: uint16).as[IPv4])
      .typecase(2, (ipv6address :: uint16).as[IPv6])
      .typecase(3, (base32(10) :: uint16).as[Tor2])
      .typecase(4, (base32(35) :: uint16).as[Tor3])
      .typecase(5, (zeropaddedstring(64) :: uint16).as[Domain])

  // this one is a bit different from most other codecs: the first 'len' element is *not* the number of items
  // in the list but rather the  number of bytes of the encoded list. The rationale is once we've read this
  // number of bytes we can just skip to the next field
  val listofnodeaddresses: Codec[List[NodeAddress]] = variableSizeBytes(uint16, list(nodeaddress))

  val privateKey: Codec[PrivateKey] = Codec[PrivateKey](
    (priv: PrivateKey) => bytes(32).encode(priv.value),
    (wire: BitVector) => bytes(32).decode(wire).map(_.map(b => PrivateKey(b)))
  )

  val publicKey: Codec[PublicKey] = Codec[PublicKey](
    (pub: PublicKey) => bytes(33).encode(pub.value),
    (wire: BitVector) => bytes(33).decode(wire).map(_.map(b => PublicKey(b)))
  )

  val rgb: Codec[Color] = bytes(3).xmap(buf => Color(buf(0), buf(1), buf(2)), t => ByteVector(t.r, t.g, t.b))

  def zeropaddedstring(size: Int): Codec[String] = fixedSizeBytes(size, utf8).xmap(s => s.takeWhile(_ != '\u0000'), s => s)

  /**
   * When encoding, prepend a valid mac to the output of the given codec.
   * When decoding, verify that a valid mac is prepended.
   */
  def prependmac[A](codec: Codec[A], mac: Mac32): Codec[A] = Codec[A](
    (a: A) => codec.encode(a).map(bits => mac.mac(bits.toByteVector).bits ++ bits),
    (bits: BitVector) => ("mac" | bytes32).decode(bits) match {
      case Attempt.Successful(DecodeResult(msgMac, remainder)) if mac.verify(msgMac, remainder.toByteVector) => codec.decode(remainder)
      case Attempt.Successful(_) => Attempt.Failure(scodec.Err("invalid mac"))
      case Attempt.Failure(err) => Attempt.Failure(err)
    }
  )

}


text:
// Transport Security Layer (TLS)
// Copyright (c) 2003-2004 Carlos Guzman Alvarez

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

using Mono.Security.Protocol.Tls.Handshake;

namespace Mono.Security.Protocol.Tls
{
	public class SslServerStream : Stream, IDisposable
	{
		#region Internal Events

		internal event CertificateValidationCallback	ClientCertValidation;
		internal event PrivateKeySelectionCallback		PrivateKeySelection;

		#endregion

		#region Fields

		private ServerRecordProtocol	protocol;
		private BufferedStream			inputBuffer;
		private ServerContext			context;
		private Stream					innerStream;
		private bool					disposed;
		private bool					ownsStream;
		private bool					checkCertRevocationStatus;
		private object					read;
		private object					write;

		#endregion

		#region Properties

		public override bool CanRead
		{
			get { return this.innerStream.CanRead; }
		}

		public override bool CanWrite
		{
			get { return this.innerStream.CanWrite; }
		}

		public override bool CanSeek
		{
			get { return this.innerStream.CanSeek; }
		}

		public override long Length
		{
			get { throw new NotSupportedException(); }
		}

		public override long Position
		{
			get { throw new NotSupportedException(); }
			set { throw new NotSupportedException(); }
		}

		#endregion

		#region Security Properties

		public bool CheckCertRevocationStatus
		{
			get { return this.checkCertRevocationStatus ; }
			set { this.checkCertRevocationStatus = value; }
		}

		public CipherAlgorithmType CipherAlgorithm
		{
			get
			{
				if (this.context.HandshakeState == HandshakeState.Finished)
				{
					return this.context.Cipher.CipherAlgorithmType;
				}

				return CipherAlgorithmType.None;
			}
		}

		public int CipherStrength
		{
			get
			{
				if (this.context.HandshakeState == HandshakeState.Finished)
				{
					return this.context.Cipher.EffectiveKeyBits;
				}

				return 0;
			}
		}

		public X509Certificate ClientCertificate
		{
			get
			{
				if (this.context.HandshakeState == HandshakeState.Finished)
				{
					return this.context.ClientSettings.ClientCertificate;
				}

				return null;
			}
		}

		public HashAlgorithmType HashAlgorithm
		{
			get
			{
				if (this.context.HandshakeState == HandshakeState.Finished)
				{
					return this.context.Cipher.HashAlgorithmType;
				}

				return HashAlgorithmType.None;
			}
		}

		public int HashStrength
		{
			get
			{
				if (this.context.HandshakeState == HandshakeState.Finished)
				{
					return this.context.Cipher.HashSize * 8;
				}

				return 0;
			}
		}

		public int KeyExchangeStrength
		{
			get
			{
				if (this.context.HandshakeState == HandshakeState.Finished)
				{
					return this.context.ServerSettings.Certificates[0].RSA.KeySize;
				}

				return 0;
			}
		}

		public ExchangeAlgorithmType KeyExchangeAlgorithm
		{
			get
			{
				if (this.context.HandshakeState == HandshakeState.Finished)
				{
					return this.context.Cipher.ExchangeAlgorithmType;
				}

				return ExchangeAlgorithmType.None;
			}
		}

		public SecurityProtocolType SecurityProtocol
		{
			get
			{
				if (this.context.HandshakeState == HandshakeState.Finished)
				{
					return this.context.SecurityProtocol;
				}

				return 0;
			}
		}

		public X509Certificate ServerCertificate
		{
			get
			{
				if (this.context.HandshakeState == HandshakeState.Finished)
				{
					if (this.context.ServerSettings.Certificates != null &&
						this.context.ServerSettings.Certificates.Count > 0)
					{
						return new X509Certificate(this.context.ServerSettings.Certificates[0].RawData);
					}
				}

				return null;
			}
		}

		#endregion

		#region Callback Properties

		public CertificateValidationCallback ClientCertValidationDelegate
		{
			get { return this.ClientCertValidation; }
			set { this.ClientCertValidation = value; }
		}

		public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate
		{
			get { return this.PrivateKeySelection; }
			set { this.PrivateKeySelection = value; }
		}

		#endregion

		#region Constructors

		public SslServerStream(
			Stream			stream,
			X509Certificate serverCertificate) : this(
			stream,
			serverCertificate,
			false,
			false,
			SecurityProtocolType.Default)
		{
		}

		public SslServerStream(
			Stream			stream,
			X509Certificate serverCertificate,
			bool			clientCertificateRequired,
			bool			ownsStream): this(
			stream,
			serverCertificate,
			clientCertificateRequired,
			ownsStream,
			SecurityProtocolType.Default)
		{
		}

		public SslServerStream(
			Stream					stream,
			X509Certificate			serverCertificate,
			bool					clientCertificateRequired,
			bool					ownsStream,
			SecurityProtocolType	securityProtocolType)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream is null.");
			}
			if (!stream.CanRead || !stream.CanWrite)
			{
				throw new ArgumentNullException("stream is not both readable and writable.");
			}

			this.context = new ServerContext(
				this,
				securityProtocolType,
				serverCertificate,
				clientCertificateRequired);

			this.inputBuffer	= new BufferedStream(new MemoryStream());
			this.innerStream	= stream;
			this.ownsStream		= ownsStream;
			this.read			= new object ();
			this.write			= new object ();
			this.protocol		= new ServerRecordProtocol(innerStream, context);
		}

		#endregion

		#region Finalizer

		~SslServerStream()
		{
			this.Dispose(false);
		}

		#endregion

		#region IDisposable Methods

		void IDisposable.Dispose()
		{
			this.Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!this.disposed)
			{
				if (disposing)
				{
					if (this.innerStream != null)
					{
						if (this.context.HandshakeState == HandshakeState.Finished)
						{
							// Write close notify
							this.protocol.SendAlert(AlertDescription.CloseNotify);
						}

						if (this.ownsStream)
						{
							// Close inner stream
							this.innerStream.Close();
						}
					}
					this.ownsStream				= false;
					this.innerStream			= null;
					this.ClientCertValidation	= null;
					this.PrivateKeySelection	= null;
				}

				this.disposed = true;
			}
		}

		#endregion

		#region Methods

		public override IAsyncResult BeginRead(
			byte[]			buffer,
			int				offset,
			int				count,
			AsyncCallback	callback,
			object			state)
		{
			this.checkDisposed();

			if (buffer == null)
			{
				throw new ArgumentNullException("buffer is a null reference.");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset is less than 0.");
			}
			if (offset > buffer.Length)
			{
				throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
			}
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count is less than 0.");
			}
			if (count > (buffer.Length - offset))
			{
				throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
			}

			lock (this)
			{
				if (this.context.HandshakeState == HandshakeState.None)
				{
					this.doHandshake();	// Handshake negotiation
				}
			}

			IAsyncResult asyncResult;

			lock (this.read)
			{
				try
				{
					// If actual buffer is full readed reset it
					if (this.inputBuffer.Position == this.inputBuffer.Length &&
						this.inputBuffer.Length > 0)
					{
						this.resetBuffer();
					}

					if (!this.context.ConnectionEnd)
					{
						// Check if we have space in the middle buffer
						// if not Read next TLS record and update the inputBuffer
						while ((this.inputBuffer.Length - this.inputBuffer.Position) < count)
						{
							// Read next record and write it into the inputBuffer
							long	position	= this.inputBuffer.Position;
							byte[]	record		= this.protocol.ReceiveRecord(this.innerStream);

							if (record != null && record.Length > 0)
							{
								// Write new data to the inputBuffer
								this.inputBuffer.Seek(0, SeekOrigin.End);
								this.inputBuffer.Write(record, 0, record.Length);

								// Restore buffer position
								this.inputBuffer.Seek(position, SeekOrigin.Begin);
							}
							else
							{
								if (record == null)
								{
									break;
								}
							}

							// TODO: Review if we need to check the Length
							// property of the innerStream for other types
							// of streams, to check that there are data available
							// for read
							if (this.innerStream is NetworkStream &&
								!((NetworkStream)this.innerStream).DataAvailable)
							{
								break;
							}
						}
					}

					asyncResult = this.inputBuffer.BeginRead(
						buffer, offset, count, callback, state);
				}
				catch (TlsException ex)
				{
					this.protocol.SendAlert(ex.Alert);
					this.Close();

					throw new IOException("The authentication or decryption has failed.");
				}
				catch (Exception)
				{
					throw new IOException("IO exception during read.");
				}
			}

			return asyncResult;
		}

		public override IAsyncResult BeginWrite(
			byte[]			buffer,
			int				offset,
			int				count,
			AsyncCallback	callback,
			object			state)
		{
			this.checkDisposed();

			if (buffer == null)
			{
				throw new ArgumentNullException("buffer is a null reference.");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset is less than 0.");
			}
			if (offset > buffer.Length)
			{
				throw new ArgumentOutOfRangeException("offset is greater than the length of buffer.");
			}
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count is less than 0.");
			}
			if (count > (buffer.Length - offset))
			{
				throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter.");
			}

			lock (this)
			{
				if (this.context.HandshakeState == HandshakeState.None)
				{
					// Start handshake negotiation
					this.doHandshake();
				}
			}

			IAsyncResult asyncResult;

			lock (this.write)
			{
				try
				{
					// Send the buffer as a TLS record
					byte[] record = this.protocol.EncodeRecord(
						ContentType.ApplicationData, buffer, offset, count);

					asyncResult = this.innerStream.BeginWrite(
						record, 0, record.Length, callback, state);
				}
				catch (TlsException ex)
				{
					this.protocol.SendAlert(ex.Alert);
					this.Close();

					throw new IOException("The authentication or decryption has failed.");
				}
				catch (Exception)
				{
					throw new IOException("IO exception during Write.");
				}
			}

			return asyncResult;
		}

		public override int EndRead(IAsyncResult asyncResult)
		{
			this.checkDisposed();

			if (asyncResult == null)
			{
				throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead.");
			}

			return this.inputBuffer.EndRead(asyncResult);
		}

		public override void EndWrite(IAsyncResult asyncResult)
		{
			this.checkDisposed();

			if (asyncResult == null)
			{
				throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead.");
			}

			this.innerStream.EndWrite (asyncResult);
		}

		public override void Close()
		{
			((IDisposable)this).Dispose();
		}

		public override void Flush()
		{
			this.checkDisposed();

			this.innerStream.Flush();
		}

		public int Read(byte[] buffer)
		{
			return this.Read(buffer, 0, buffer.Length);
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			IAsyncResult res = this.BeginRead(buffer, offset, count, null, null);

			return this.EndRead(res);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException();
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public void Write(byte[] buffer)
		{
			this.Write(buffer, 0, buffer.Length);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			IAsyncResult res = this.BeginWrite (buffer, offset, count, null, null);

			this.EndWrite(res);
		}

		#endregion

		#region Misc Methods

		private void resetBuffer()
		{
			this.inputBuffer.SetLength(0);
			this.inputBuffer.Position = 0;
		}

		private void checkDisposed()
		{
			if (this.disposed)
			{
				throw new ObjectDisposedException("The SslClientStream is closed.");
			}
		}

		#endregion

		#region Handsake Methods

		/*
			Client											Server

			ClientHello                 -------->
															ServerHello
															Certificate*
															ServerKeyExchange*
															CertificateRequest*
										<--------			ServerHelloDone
			Certificate*
			ClientKeyExchange
			CertificateVerify*
			[ChangeCipherSpec]
			Finished                    -------->
															[ChangeCipherSpec]
										<--------           Finished
			Application Data            <------->			Application Data

					Fig. 1 - Message flow for a full handshake
		*/

		private void doHandshake()
		{
			try
			{
				// Reset the context if needed
				if (this.context.HandshakeState != HandshakeState.None)
				{
					this.context.Clear();
				}

				// Obtain supported cipher suites
				this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol);

				// Set handshake state
				this.context.HandshakeState = HandshakeState.Started;

				// Receive Client Hello message
				this.protocol.ReceiveRecord (this.innerStream);

				// If received message is not an ClientHello send a
				// Fatal Alert
				if (this.context.LastHandshakeMsg != HandshakeType.ClientHello)
				{
					this.protocol.SendAlert(AlertDescription.UnexpectedMessage);
				}

				// Send ServerHello message
				this.protocol.SendRecord(HandshakeType.ServerHello);

				// Send ServerCertificate message
				this.protocol.SendRecord(HandshakeType.Certificate);

				// If the negotiated cipher is a KeyEx cipher send ServerKeyExchange
				if (this.context.Cipher.ExchangeAlgorithmType == ExchangeAlgorithmType.RsaKeyX)
				{
					this.protocol.SendRecord(HandshakeType.ServerKeyExchange);
				}

				// If the negotiated cipher is a KeyEx cipher or
				// the client certificate is required send the CertificateRequest message
				if (this.context.Cipher.ExchangeAlgorithmType == ExchangeAlgorithmType.RsaKeyX ||
					this.context.ClientCertificateRequired)
				{
					this.protocol.SendRecord(HandshakeType.CertificateRequest);
				}

				// Send ServerHelloDone message
				this.protocol.SendRecord(HandshakeType.ServerHelloDone);

				// Receive client response, until the Client Finished message
				// is received
				while (this.context.LastHandshakeMsg != HandshakeType.Finished)
				{
					this.protocol.ReceiveRecord (this.innerStream);
				}

				// Send ChangeCipherSpec and ServerFinished messages
				this.protocol.SendChangeCipherSpec();

				// The handshake is finished
				this.context.HandshakeState = HandshakeState.Finished;

				// Clear Key Info
				this.context.ClearKeyInfo();
			}
			catch (TlsException ex)
			{
				this.protocol.SendAlert(ex.Alert);
				this.Close();

				throw new IOException("The authentication or decryption has failed.");
			}
			catch (Exception)
			{
				this.protocol.SendAlert(AlertDescription.InternalError);
				this.Close();

				throw new IOException("The authentication or decryption has failed.");
			}
		}

		#endregion

		#region Event Methods

		internal bool RaiseClientCertificateValidation(
			X509Certificate certificate,
			int[]			certificateErrors)
		{
			if (this.ClientCertValidation != null)
			{
				return this.ClientCertValidation(certificate, certificateErrors);
			}

			return (certificateErrors != null && certificateErrors.Length == 0);
		}

		internal AsymmetricAlgorithm RaisePrivateKeySelection(
			X509Certificate certificate,
			string			targetHost)
		{
			if (this.PrivateKeySelection != null)
			{
				return this.PrivateKeySelection(certificate, targetHost);
			}

			return null;
		}

		#endregion
	}
}


text:
package org.elasticsearch.xpack.datastreams.rest;

import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;
import org.elasticsearch.xpack.core.action.CreateDataStreamAction;

import java.io.IOException;
import java.util.List;

import static org.elasticsearch.rest.RestRequest.Method.PUT;

public class RestCreateDataStreamAction extends BaseRestHandler {

    @Override
    public String getName() {
        return "create_data_stream_action";
    }

    @Override
    public List<Route> routes() {
        return List.of(new Route(PUT, "/_data_stream/{name}"));
    }

    @Override
    protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
        CreateDataStreamAction.Request putDataStreamRequest = new CreateDataStreamAction.Request(request.param("name"));
        return channel -> client.execute(CreateDataStreamAction.INSTANCE, putDataStreamRequest, new RestToXContentListener<>(channel));
    }
}


text:
#ifndef MN_BasicFunctionGradient_H_
#define MN_BasicFunctionGradient_H_

#include "MnMatrix.h"

#include "StackAllocator.h"

//extern StackAllocator gStackAllocator;

class BasicFunctionGradient {

private:

public:

  explicit BasicFunctionGradient(unsigned int n) :
    theGradient(MnAlgebraicVector(n)), theG2ndDerivative(MnAlgebraicVector(n)),
    theGStepSize(MnAlgebraicVector(n)), theValid(false),
    theAnalytical(false) {}

  explicit BasicFunctionGradient(const MnAlgebraicVector& grd) :
    theGradient(grd), theG2ndDerivative(MnAlgebraicVector(grd.size())),
    theGStepSize(MnAlgebraicVector(grd.size())), theValid(true),
    theAnalytical(true) {}

  BasicFunctionGradient(const MnAlgebraicVector& grd, const MnAlgebraicVector& g2, const MnAlgebraicVector& gstep) :
    theGradient(grd), theG2ndDerivative(g2),
    theGStepSize(gstep), theValid(true), theAnalytical(false) {}

  ~BasicFunctionGradient() {}

  BasicFunctionGradient(const BasicFunctionGradient& grad) : theGradient(grad.theGradient), theG2ndDerivative(grad.theG2ndDerivative), theGStepSize(grad.theGStepSize), theValid(grad.theValid) {}

  BasicFunctionGradient& operator=(const BasicFunctionGradient& grad) {
    theGradient = grad.theGradient;
    theG2ndDerivative = grad.theG2ndDerivative;
    theGStepSize = grad.theGStepSize;
    theValid = grad.theValid;
    return *this;
  }

  void* operator new(size_t nbytes) {
    return StackAllocatorHolder::get().allocate(nbytes);
  }

  void operator delete(void* p, size_t /*nbytes */) {
    StackAllocatorHolder::get().deallocate(p);
  }

  const MnAlgebraicVector& grad() const {return theGradient;}
  const MnAlgebraicVector& vec() const {return theGradient;}
  bool isValid() const {return theValid;}

  bool isAnalytical() const {return theAnalytical;}
  const MnAlgebraicVector& g2() const {return theG2ndDerivative;}
  const MnAlgebraicVector& gstep() const {return theGStepSize;}

private:

  MnAlgebraicVector theGradient;
  MnAlgebraicVector theG2ndDerivative;
  MnAlgebraicVector theGStepSize;
  bool theValid;
  bool theAnalytical;
};

#endif //MN_BasicFunctionGradient_H_


text:
import type { EditorState } from 'draft-js';
import type { DraftHandleValue } from 'draft-js/lib/DraftHandleValue';

import handleReturnWithCommand from './handleReturnWithCommand';
import handleReturnListItem from './handleReturnListItem';
import handleReturnToInsertWebCard from './handleReturnToInsertWebCard';
import handleReturnToSplitBlockIfCursorAtStart from './handleReturnToSplitBlockIfCursorAtStart';
import handleReturnBlockquote from './handleReturnBlockquote';

import type { Config } from '../types/Config';
import type { PluginFunctions } from '../types/PluginFunctions';

const createHandleReturn = (config: Config): Function => (
  (event: SyntheticKeyboardEvent<*>, editorState: EditorState, pluginFunctions: PluginFunctions): DraftHandleValue => {
    if (handleReturnWithCommand(event, config)) {
      return 'handled';
    }

    if (handleReturnListItem(editorState, config, pluginFunctions)) {
      return 'handled';
    }

    if (handleReturnToInsertWebCard(editorState, config, pluginFunctions)) {
      return 'handled';
    }

    if (handleReturnToSplitBlockIfCursorAtStart(editorState, config, pluginFunctions)) {
      return 'handled';
    }

    if (handleReturnBlockquote(event, editorState, config, pluginFunctions)) {
      return 'handled';
    }

    return 'not-handled';
  }
);

export default createHandleReturn;


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Bc's Raspberry-Port Marinade</title>
      <categories>
        <cat>Marinades</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>3/4</qty>
          <unit>cups</unit></amt>
        <item>Port wine or apple juice</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>tablespoon</unit></amt>
        <item>Chopped fresh thyme leaves</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Or 1/2 t dried thyme leaves</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Vegetable oil</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>teaspoons</unit></amt>
        <item>Salt</item></ing>
      <ing>
        <amt>
          <qty>1/8</qty>
          <unit>teaspoons</unit></amt>
        <item>Pepper</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit/></amt>
        <item>Cloves garlic, minced</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>cup</unit></amt>
        <item>Fresh or frozen raspberries</item></ing></ingredients>
    <directions>
      <step>  Mix all ingredients except raspberries in shallow nonmetal dish or
  resealable plastic bag. Add up to 2 pounds pork, lamb or turkey, turning to
  coat with marinade. Cover dish or seal bag and refrigerate, turning meat
  occasionally, at least 4 hours but no longer than 24 hours. Remove meat
  from marinade; reserve marinade. Grill meat as desired. While meat is
  grilling, heat marinade and raspberries to boiling in 10-inch skillet over
  medium heat, stirring occasionally. Boil about 10 minutes, stirring
  occasionally, until sauce is reduced to half. Serve sauce with grilled
  meat.

  *Betty Crocker's Great Grilling
  Posted to MM-Recipes Digest V4 #306 by Michael McLaughlin
  <mmclaughlin@micronet.net> on Nov 25, 1997

</step></directions></recipe></recipeml>


text:
/* global Aria:true, aria:true */
var vm = require("vm"), fs = require("fs"), path = require("path");

/* aria and Aria are going to be global */
aria = {};

Aria = {
    rootFolderPath : __dirname + "/../"
};

/* This is the global load method used by the framework, it's common to Rhino */
global.load = function (filePath) {
    filePath = path.normalize(filePath);

    var fileContent = fs.readFileSync(filePath, "utf-8");
    vm.runInThisContext(fileContent);
};

try {
    global.load(__dirname + "/bootstrap.js");

    // For all the other classes we use IO, define our node transport
    Aria.classDefinition({
        $classpath : "aria.node.Transport",
        $implements : ["aria.core.transport.ITransports"],
        $singleton : true,
        $prototype : {
            isReady : true,
            init : Aria.empty,
            request : function (request, callback) {
                fs.readFile(request.url, "utf-8", function (err, data) {
                    if (err) {
                        callback.fn.call(callback.scope, err, callback.args);
                    } else {
                        var responseObject = {
                            status : 200,
                            responseText : data
                        };
                        callback.fn.call(callback.scope, false, callback.args, responseObject);
                    }
                });
            }
        }
    });

    aria.core.IO.updateTransports({
        "sameDomain" : "aria.node.Transport"
    });
} catch (ex) {
    console.error('\n[Error] Aria Templates framework not loaded.', ex);
    process.exit(1);
}


text:
module Spaceship
  module Tunes
    # Represents the information about remaining number of promo codes for an app version
    class AppVersionPromocodes < TunesBase
      # @return
      attr_reader :app_id
      attr_reader :app_name
      attr_reader :version
      attr_reader :platform
      attr_reader :number_of_codes
      attr_reader :maximum_number_of_codes
      attr_reader :contract_file_name

      attr_mapping({
        'id' => :app_id,
        'appName' => :app_name,
        'version' => :version,
        'platform' => :platform,
        'numberOfCodes' => :number_of_codes,
        'maximumNumberOfCodes' => :maximum_number_of_codes,
        'contractFileName' => :contract_file_name
      })

      class << self
        # Create a new object based on a hash.
        # This is used to create a new object based on the server response.
        def factory(attrs)
          obj = self.new(attrs)
          return obj
        end
      end
    end
  end
end


text:
/**
 * @module ol/reproj
 */
import { IMAGE_SMOOTHING_DISABLED } from './source/common.js';
import { assign } from './obj.js';
import { containsCoordinate, createEmpty, extend, forEachCorner, getCenter, getHeight, getTopLeft, getWidth, } from './extent.js';
import { createCanvasContext2D } from './dom.js';
import { getPointResolution, transform } from './proj.js';
import { solveLinearSystem } from './math.js';
var brokenDiagonalRendering_;
/**
 * This draws a small triangle into a canvas by setting the triangle as the clip region
 * and then drawing a (too large) rectangle
 *
 * @param {CanvasRenderingContext2D} ctx The context in which to draw the triangle
 * @param {number} u1 The x-coordinate of the second point. The first point is 0,0.
 * @param {number} v1 The y-coordinate of the second point.
 * @param {number} u2 The x-coordinate of the third point.
 * @param {number} v2 The y-coordinate of the third point.
 */
function drawTestTriangle(ctx, u1, v1, u2, v2) {
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(u1, v1);
    ctx.lineTo(u2, v2);
    ctx.closePath();
    ctx.save();
    ctx.clip();
    ctx.fillRect(0, 0, Math.max(u1, u2) + 1, Math.max(v1, v2));
    ctx.restore();
}
/**
 * Given the data from getImageData, see if the right values appear at the provided offset.
 * Returns true if either the color or transparency is off
 *
 * @param {Uint8ClampedArray} data The data returned from getImageData
 * @param {number} offset The pixel offset from the start of data.
 * @return {boolean} true if the diagonal rendering is broken
 */
function verifyBrokenDiagonalRendering(data, offset) {
    // the values ought to be close to the rgba(210, 0, 0, 0.75)
    return (Math.abs(data[offset * 4] - 210) > 2 ||
        Math.abs(data[offset * 4 + 3] - 0.75 * 255) > 2);
}
/**
 * Determines if the current browser configuration can render triangular clip regions correctly.
 * This value is cached so the function is only expensive the first time called.
 * Firefox on Windows (as of now) does not if HWA is enabled. See https://bugzilla.mozilla.org/show_bug.cgi?id=1606976
 * IE also doesn't. Chrome works, and everything seems to work on OSX and Android. This function caches the
 * result. I suppose that it is conceivably possible that a browser might flip modes while the app is
 * running, but lets hope not.
 *
 * @return {boolean} true if the Diagonal Rendering is broken.
 */
function isBrokenDiagonalRendering() {
    if (brokenDiagonalRendering_ === undefined) {
        var ctx = document.createElement('canvas').getContext('2d');
        ctx.globalCompositeOperation = 'lighter';
        ctx.fillStyle = 'rgba(210, 0, 0, 0.75)';
        drawTestTriangle(ctx, 4, 5, 4, 0);
        drawTestTriangle(ctx, 4, 5, 0, 5);
        var data = ctx.getImageData(0, 0, 3, 3).data;
        brokenDiagonalRendering_ =
            verifyBrokenDiagonalRendering(data, 0) ||
                verifyBrokenDiagonalRendering(data, 4) ||
                verifyBrokenDiagonalRendering(data, 8);
    }
    return brokenDiagonalRendering_;
}
/**
 * Calculates ideal resolution to use from the source in order to achieve
 * pixel mapping as close as possible to 1:1 during reprojection.
 * The resolution is calculated regardless of what resolutions
 * are actually available in the dataset (TileGrid, Image, ...).
 *
 * @param {import("./proj/Projection.js").default} sourceProj Source projection.
 * @param {import("./proj/Projection.js").default} targetProj Target projection.
 * @param {import("./coordinate.js").Coordinate} targetCenter Target center.
 * @param {number} targetResolution Target resolution.
 * @return {number} The best resolution to use. Can be +-Infinity, NaN or 0.
 */
export function calculateSourceResolution(sourceProj, targetProj, targetCenter, targetResolution) {
    var sourceCenter = transform(targetCenter, targetProj, sourceProj);
    // calculate the ideal resolution of the source data
    var sourceResolution = getPointResolution(targetProj, targetResolution, targetCenter);
    var targetMetersPerUnit = targetProj.getMetersPerUnit();
    if (targetMetersPerUnit !== undefined) {
        sourceResolution *= targetMetersPerUnit;
    }
    var sourceMetersPerUnit = sourceProj.getMetersPerUnit();
    if (sourceMetersPerUnit !== undefined) {
        sourceResolution /= sourceMetersPerUnit;
    }
    // Based on the projection properties, the point resolution at the specified
    // coordinates may be slightly different. We need to reverse-compensate this
    // in order to achieve optimal results.
    var sourceExtent = sourceProj.getExtent();
    if (!sourceExtent || containsCoordinate(sourceExtent, sourceCenter)) {
        var compensationFactor = getPointResolution(sourceProj, sourceResolution, sourceCenter) /
            sourceResolution;
        if (isFinite(compensationFactor) && compensationFactor > 0) {
            sourceResolution /= compensationFactor;
        }
    }
    return sourceResolution;
}
/**
 * Calculates ideal resolution to use from the source in order to achieve
 * pixel mapping as close as possible to 1:1 during reprojection.
 * The resolution is calculated regardless of what resolutions
 * are actually available in the dataset (TileGrid, Image, ...).
 *
 * @param {import("./proj/Projection.js").default} sourceProj Source projection.
 * @param {import("./proj/Projection.js").default} targetProj Target projection.
 * @param {import("./extent.js").Extent} targetExtent Target extent
 * @param {number} targetResolution Target resolution.
 * @return {number} The best resolution to use. Can be +-Infinity, NaN or 0.
 */
export function calculateSourceExtentResolution(sourceProj, targetProj, targetExtent, targetResolution) {
    var targetCenter = getCenter(targetExtent);
    var sourceResolution = calculateSourceResolution(sourceProj, targetProj, targetCenter, targetResolution);
    if (!isFinite(sourceResolution) || sourceResolution <= 0) {
        forEachCorner(targetExtent, function (corner) {
            sourceResolution = calculateSourceResolution(sourceProj, targetProj, corner, targetResolution);
            return isFinite(sourceResolution) && sourceResolution > 0;
        });
    }
    return sourceResolution;
}
/**
 * Renders the source data into new canvas based on the triangulation.
 *
 * @param {number} width Width of the canvas.
 * @param {number} height Height of the canvas.
 * @param {number} pixelRatio Pixel ratio.
 * @param {number} sourceResolution Source resolution.
 * @param {import("./extent.js").Extent} sourceExtent Extent of the data source.
 * @param {number} targetResolution Target resolution.
 * @param {import("./extent.js").Extent} targetExtent Target extent.
 * @param {import("./reproj/Triangulation.js").default} triangulation
 * Calculated triangulation.
 * @param {Array<{extent: import("./extent.js").Extent,
 *                 image: (HTMLCanvasElement|HTMLImageElement|HTMLVideoElement)}>} sources
 * Array of sources.
 * @param {number} gutter Gutter of the sources.
 * @param {boolean=} opt_renderEdges Render reprojection edges.
 * @param {object=} opt_contextOptions Properties to set on the canvas context.
 * @return {HTMLCanvasElement} Canvas with reprojected data.
 */
export function render(width, height, pixelRatio, sourceResolution, sourceExtent, targetResolution, targetExtent, triangulation, sources, gutter, opt_renderEdges, opt_contextOptions) {
    var context = createCanvasContext2D(Math.round(pixelRatio * width), Math.round(pixelRatio * height));
    assign(context, opt_contextOptions);
    if (sources.length === 0) {
        return context.canvas;
    }
    context.scale(pixelRatio, pixelRatio);
    function pixelRound(value) {
        return Math.round(value * pixelRatio) / pixelRatio;
    }
    context.globalCompositeOperation = 'lighter';
    var sourceDataExtent = createEmpty();
    sources.forEach(function (src, i, arr) {
        extend(sourceDataExtent, src.extent);
    });
    var canvasWidthInUnits = getWidth(sourceDataExtent);
    var canvasHeightInUnits = getHeight(sourceDataExtent);
    var stitchContext = createCanvasContext2D(Math.round((pixelRatio * canvasWidthInUnits) / sourceResolution), Math.round((pixelRatio * canvasHeightInUnits) / sourceResolution));
    assign(stitchContext, opt_contextOptions);
    var stitchScale = pixelRatio / sourceResolution;
    sources.forEach(function (src, i, arr) {
        var xPos = src.extent[0] - sourceDataExtent[0];
        var yPos = -(src.extent[3] - sourceDataExtent[3]);
        var srcWidth = getWidth(src.extent);
        var srcHeight = getHeight(src.extent);
        // This test should never fail -- but it does. Need to find a fix the upstream condition
        if (src.image.width > 0 && src.image.height > 0) {
            stitchContext.drawImage(src.image, gutter, gutter, src.image.width - 2 * gutter, src.image.height - 2 * gutter, xPos * stitchScale, yPos * stitchScale, srcWidth * stitchScale, srcHeight * stitchScale);
        }
    });
    var targetTopLeft = getTopLeft(targetExtent);
    triangulation.getTriangles().forEach(function (triangle, i, arr) {
        /* Calculate affine transform (src -> dst)
         * Resulting matrix can be used to transform coordinate
         * from `sourceProjection` to destination pixels.
         *
         * To optimize number of context calls and increase numerical stability,
         * we also do the following operations:
         * trans(-topLeftExtentCorner), scale(1 / targetResolution), scale(1, -1)
         * here before solving the linear system so [ui, vi] are pixel coordinates.
         *
         * Src points: xi, yi
         * Dst points: ui, vi
         * Affine coefficients: aij
         *
         * | x0 y0 1  0  0 0 |   |a00|   |u0|
         * | x1 y1 1  0  0 0 |   |a01|   |u1|
         * | x2 y2 1  0  0 0 | x |a02| = |u2|
         * |  0  0 0 x0 y0 1 |   |a10|   |v0|
         * |  0  0 0 x1 y1 1 |   |a11|   |v1|
         * |  0  0 0 x2 y2 1 |   |a12|   |v2|
         */
        var source = triangle.source;
        var target = triangle.target;
        var x0 = source[0][0], y0 = source[0][1];
        var x1 = source[1][0], y1 = source[1][1];
        var x2 = source[2][0], y2 = source[2][1];
        // Make sure that everything is on pixel boundaries
        var u0 = pixelRound((target[0][0] - targetTopLeft[0]) / targetResolution);
        var v0 = pixelRound(-(target[0][1] - targetTopLeft[1]) / targetResolution);
        var u1 = pixelRound((target[1][0] - targetTopLeft[0]) / targetResolution);
        var v1 = pixelRound(-(target[1][1] - targetTopLeft[1]) / targetResolution);
        var u2 = pixelRound((target[2][0] - targetTopLeft[0]) / targetResolution);
        var v2 = pixelRound(-(target[2][1] - targetTopLeft[1]) / targetResolution);
        // Shift all the source points to improve numerical stability
        // of all the subsequent calculations. The [x0, y0] is used here.
        // This is also used to simplify the linear system.
        var sourceNumericalShiftX = x0;
        var sourceNumericalShiftY = y0;
        x0 = 0;
        y0 = 0;
        x1 -= sourceNumericalShiftX;
        y1 -= sourceNumericalShiftY;
        x2 -= sourceNumericalShiftX;
        y2 -= sourceNumericalShiftY;
        var augmentedMatrix = [
            [x1, y1, 0, 0, u1 - u0],
            [x2, y2, 0, 0, u2 - u0],
            [0, 0, x1, y1, v1 - v0],
            [0, 0, x2, y2, v2 - v0],
        ];
        var affineCoefs = solveLinearSystem(augmentedMatrix);
        if (!affineCoefs) {
            return;
        }
        context.save();
        context.beginPath();
        if (isBrokenDiagonalRendering() ||
            opt_contextOptions === IMAGE_SMOOTHING_DISABLED) {
            // Make sure that all lines are horizontal or vertical
            context.moveTo(u1, v1);
            // This is the diagonal line. Do it in 4 steps
            var steps = 4;
            var ud = u0 - u1;
            var vd = v0 - v1;
            for (var step = 0; step < steps; step++) {
                // Go horizontally
                context.lineTo(u1 + pixelRound(((step + 1) * ud) / steps), v1 + pixelRound((step * vd) / (steps - 1)));
                // Go vertically
                if (step != steps - 1) {
                    context.lineTo(u1 + pixelRound(((step + 1) * ud) / steps), v1 + pixelRound(((step + 1) * vd) / (steps - 1)));
                }
            }
            // We are almost at u0r, v0r
            context.lineTo(u2, v2);
        }
        else {
            context.moveTo(u1, v1);
            context.lineTo(u0, v0);
            context.lineTo(u2, v2);
        }
        context.clip();
        context.transform(affineCoefs[0], affineCoefs[2], affineCoefs[1], affineCoefs[3], u0, v0);
        context.translate(sourceDataExtent[0] - sourceNumericalShiftX, sourceDataExtent[3] - sourceNumericalShiftY);
        context.scale(sourceResolution / pixelRatio, -sourceResolution / pixelRatio);
        context.drawImage(stitchContext.canvas, 0, 0);
        context.restore();
    });
    if (opt_renderEdges) {
        context.save();
        context.strokeStyle = 'black';
        context.lineWidth = 1;
        triangulation.getTriangles().forEach(function (triangle, i, arr) {
            var target = triangle.target;
            var u0 = (target[0][0] - targetTopLeft[0]) / targetResolution;
            var v0 = -(target[0][1] - targetTopLeft[1]) / targetResolution;
            var u1 = (target[1][0] - targetTopLeft[0]) / targetResolution;
            var v1 = -(target[1][1] - targetTopLeft[1]) / targetResolution;
            var u2 = (target[2][0] - targetTopLeft[0]) / targetResolution;
            var v2 = -(target[2][1] - targetTopLeft[1]) / targetResolution;
            context.beginPath();
            context.moveTo(u1, v1);
            context.lineTo(u0, v0);
            context.lineTo(u2, v2);
            context.closePath();
            context.stroke();
        });
        context.restore();
    }
    return context.canvas;
}
//# sourceMappingURL=reproj.js.map


text:
package com.amazonaws.services.waf.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Contains the identifier and the name of the IPSet.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class IPSetSummary implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The IPSetId for an IPSet. You can use IPSetId in a GetIPSet request to
     * get detailed information about an IPSet.
     *

     */
    private String iPSetId;
    /**
     *

     * A friendly name or description of the IPSet. You can't change the name of an IPSet after you
     * create it.
     *

     */
    private String name;

    /**
     *

     * The IPSetId for an IPSet. You can use IPSetId in a GetIPSet request to
     * get detailed information about an IPSet.
     *

     *
     * @param iPSetId
     *        The IPSetId for an IPSet. You can use IPSetId in a GetIPSet
     *        request to get detailed information about an IPSet.
     */

    public void setIPSetId(String iPSetId) {
        this.iPSetId = iPSetId;
    }

    /**
     *

     * The IPSetId for an IPSet. You can use IPSetId in a GetIPSet request to
     * get detailed information about an IPSet.
     *

     *
     * @return The IPSetId for an IPSet. You can use IPSetId in a GetIPSet
     *         request to get detailed information about an IPSet.
     */

    public String getIPSetId() {
        return this.iPSetId;
    }

    /**
     *

     * The IPSetId for an IPSet. You can use IPSetId in a GetIPSet request to
     * get detailed information about an IPSet.
     *

     *
     * @param iPSetId
     *        The IPSetId for an IPSet. You can use IPSetId in a GetIPSet
     *        request to get detailed information about an IPSet.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public IPSetSummary withIPSetId(String iPSetId) {
        setIPSetId(iPSetId);
        return this;
    }

    /**
     *

     * A friendly name or description of the IPSet. You can't change the name of an IPSet after you
     * create it.
     *

     *
     * @param name
     *        A friendly name or description of the IPSet. You can't change the name of an IPSet
     *        after you create it.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * A friendly name or description of the IPSet. You can't change the name of an IPSet after you
     * create it.
     *

     *
     * @return A friendly name or description of the IPSet. You can't change the name of an IPSet
     *         after you create it.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * A friendly name or description of the IPSet. You can't change the name of an IPSet after you
     * create it.
     *

     *
     * @param name
     *        A friendly name or description of the IPSet. You can't change the name of an IPSet
     *        after you create it.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public IPSetSummary withName(String name) {
        setName(name);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getIPSetId() != null)
            sb.append("IPSetId: ").append(getIPSetId()).append(",");
        if (getName() != null)
            sb.append("Name: ").append(getName());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof IPSetSummary == false)
            return false;
        IPSetSummary other = (IPSetSummary) obj;
        if (other.getIPSetId() == null ^ this.getIPSetId() == null)
            return false;
        if (other.getIPSetId() != null && other.getIPSetId().equals(this.getIPSetId()) == false)
            return false;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getIPSetId() == null) ? 0 : getIPSetId().hashCode());
        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        return hashCode;
    }

    @Override
    public IPSetSummary clone() {
        try {
            return (IPSetSummary) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.waf.model.waf_regional.transform.IPSetSummaryMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package nl.weeaboo.filesystem;

import nl.weeaboo.common.Checks;

/**
 * File search settings.
 */
public final class FileCollectOptions {

    private FilePath baseFolder = FilePath.empty();
    private String namePrefix = "";

    public boolean recursive;
    public boolean collectFiles;
    public boolean collectFolders;

    /**
     * A recursive, file-only filter.
     */
    public FileCollectOptions() {
        recursive = true;
        collectFiles = true;
    }

    /**
     * A recursive, folder-only filter that only accepts paths starting with the given prefix.
     */
    public static FileCollectOptions subFolders(FilePath basePath) {
        FileCollectOptions opts = new FileCollectOptions();
        opts.setBaseFolder(basePath);
        opts.collectFiles = false;
        opts.collectFolders = true;
        return opts;
    }

    /**
     * @see #files(FilePath, String)
     */
    public static FileCollectOptions files(FilePath basePath) {
        return files(basePath, "");
    }

    /**
     * A recursive, folder-only filter that only accepts paths starting with the given prefix.
     */
    public static FileCollectOptions files(FilePath basePath, String namePrefix) {
        FileCollectOptions opts = new FileCollectOptions();
        opts.setBaseFolder(basePath);
        opts.setNamePrefix(namePrefix);
        opts.collectFiles = true;
        opts.collectFolders = false;
        return opts;
    }

    /**
     * Checks if the supplied path passes the filter.
     */
    public boolean isValid(FilePath file) {
        FilePath parent = file.getParent();
        if (parent == null) {
            parent = FilePath.empty();
        }

        if (file.equals(baseFolder)) {
            return false; // Don't include the base folder
        }

        if (recursive) {
            // This folder is equal to, or a descendant of the base search path
            return file.getName().startsWith(namePrefix) && parent.startsWith(baseFolder);
        } else {
            // This file is a direct child of the base search path
            return file.getName().startsWith(namePrefix) && parent.equals(baseFolder);
        }
    }

    public FilePath getBaseFolder() {
        return baseFolder;
    }

    public void setBaseFolder(FilePath baseFolder) {
        this.baseFolder = Checks.checkNotNull(baseFolder);
    }

    public String getNamePrefix() {
        return namePrefix;
    }

    public void setNamePrefix(String namePrefix) {
        this.namePrefix = Checks.checkNotNull(namePrefix);
    }

}


text:
jQuery.noConflict();
(function($,PLUGIN_ID){
	"use strict";
	/*---------------------------------------------------------------
	 valiable
	---------------------------------------------------------------*/
	var vars={
		limit:500,
		offset:0,
		fromdate:new Date(),
		todate:new Date(),
		drag:{
			capture:false,
			cells:[],
			keep:{
				column:0,
				container:0,
				position:0
			}
		},
		table:null,
		thumbnail:null,
		clients:[],
		columns:[],
		containers:[],
		excludefields:[],
		excludeviews:[],
		styles:[],
		config:{},
		fieldinfos:{},
		viewinfos:{}
	};
	var events={
		list:[
			'app.record.index.show'
		],
		show:[
			'app.record.create.show',
			'app.record.edit.show'
		]
	};
	var functions={
		/* download file */
		download:function(fileKey){
			return new Promise(function(resolve,reject)
			{
				var url=kintone.api.url('/k/v1/file',true)+'?fileKey='+fileKey;
				var xhr=new XMLHttpRequest();
				xhr.open('GET',url);
				xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
				xhr.responseType='blob';
				xhr.onload=function(){
					if (xhr.status===200) resolve(xhr.response);
					else reject(Error('File download error:' + xhr.statusText));
				};
				xhr.onerror=function(){
					reject(Error('There was a network error.'));
				};
				xhr.send();
			});
		},
		/* load client datas */
		loadclients:function(records,callback){
			if (vars.config.clientlookup)
			{
				var fieldinfo=vars.fieldinfos[vars.config.clientlookup];
				var body={
					app:fieldinfo.lookup.relatedApp.app,
					query:''
				};
				body.query+=' order by $id asc limit '+vars.limit.toString()+' offset '+vars.offset.toString();
				kintone.api(kintone.api.url('/k/v1/records',true),'GET',body,function(resp){
					Array.prototype.push.apply(records,resp.records);
					vars.offset+=vars.limit;
					if (resp.records.length==vars.limit) functions.loadclients(records,callback);
					else callback(records);
				},function(error){
					swal('Error!',error.message,'error');
				});
			}
			else callback([]);
		},
		/* place records */
		placerecords:function(records){
			var setvalues=function(row,rowstyle,cellstyle,record,tablecode,rowid){
				var index=vars.table.rows.index(row);
				var baserow=row.addClass(rowstyle);
				var tables=[];
				var cellstyles=function(field,rowinfo){
					var res=$.grep(cellstyle,function(item,index){
						var exists=(item.style.field==field);
						if (exists)
							if (rowinfo.tablecode)
							{
								exists=($.grep(item.record[rowinfo.tablecode].value,function(item,index){
									return item.id==rowinfo.rowid;
								}).length!=0);
							}
						return exists;
					});
					return res;
				};
				$.each(record,function(key,values){
					switch (values.type)
					{
						case 'SUBTABLE':
							for (var i=0;i<values.value.length;i++)
							{
								var rowinfo={
									rowid:values.value[i].id,
									tablecode:key
								};
								if (tables.length<i) tables.push({rowid:rowinfo.rowid,tablecode:rowinfo.tablecode,values:{}});
								$.each(values.value[i].value,function(key,values){
									if (i==0)
									{
										if (!key.match(/^\$/g))
											if ($('#'+key,row))
												functions.setvalue($('div',$('#'+key,row)),vars.fieldinfos[key],values.value,cellstyles(key,rowinfo));
									}
									else tables[i-1].values[key]=values;
								});
							}
							break;
						default:
							if (!key.match(/^\$/g))
								if ($('#'+key,row)) functions.setvalue($('div',$('#'+key,row)),vars.fieldinfos[key],values.value,cellstyles(key,{rowid:rowid,tablecode:tablecode}));
							break;
					}
				});
				if (vars.config.monthlytable && !$('#placeallrecords').prop('checked') && filter[vars.config.monthlytable].value.length==0)
					$('td',row).each(function(index){
						var cellindex=($(this).attr('data-cellindex'))?parseInt($(this).attr('data-cellindex')):index;
						if ($('#tablecode',$('th',vars.table.container).eq(cellindex)))
							if ($('#tablecode',$('th',vars.table.container).eq(cellindex)).val()==vars.config.monthlytable)
							{
								$(this).css({'background-color':'#FA8273'});
								if ($('#fieldcode',$('th',vars.table.container).eq(cellindex)).val()==vars.config.monthlydate)
									$(this).append(
										$('<button type="button">').css({
											'width':'100%'
										}).text('登録')
										.on('click',function(e){
											var index=$('input',$('td',row).first()).val();
											if (index.length!=0) window.location.href=kintone.api.url('/k/', true).replace(/\.json/g,'')+kintone.app.getId()+'/show#record='+index+'&mode=edit&newrow='+vars.fromdate.format('Y-m')+'-01';
										})
									);
							}
					});
				if (tables.length!=0)
				{
					for (var i=0;i<tables.length;i++)
						vars.table.insertrow(baserow,function(row){
							baserow=setvalues(row,rowstyle,cellstyle,tables[i].values,tables[i].tablecode,tables[i].rowid);
						});
					$.each($('.notable',row),function(){$(this).attr('rowspan',tables.length+1);});
					for (var i=index+1;i<index+tables.length+1;i++)
					{
						var cellindex=-1;
						$('td',vars.table.rows.eq(i)).each(function(index){
							cellindex++;
							if (!$(this).hasClass('notable')) $(this).attr('data-cellindex',cellindex);
							else $(this).remove();
						});
					}
				}
				if ('$id' in record) $('input',$('.buttoncell',row)).first().val(record['$id'].value);
				return baserow;
			};
			vars.table.clearrows();
			for (var i=0;i<records.length;i++)
			{
				var record=$.extend(true,{},records[i]);
				/* check consignment contract */
				if (vars.config.clientlookup)
				{
					var client=$.grep(vars.clients,function(item,index){
						return (item[vars.fieldinfos[vars.config.clientlookup].lookup.relatedKeyField].value==record[vars.config.clientlookup].value);
					});
					if (client.length!=0)
					{
						if (client[0][vars.config.clientdate].value)
							if (new Date(client[0][vars.config.clientdate].value)<vars.fromdate) continue;
					}
				}
				(function(fields){
					$.each(record,function(key,values){
						if (fields.indexOf(key)<0 && key!='$id') delete record[key];
					});
				})(vars.viewinfos.fields);
				var filter=record;
				if (vars.config.monthlytable && !$('#placeallrecords').prop('checked'))
				{
					filter[vars.config.monthlytable].value=$.grep(filter[vars.config.monthlytable].value,function(item,index){
						var exists=true;
						if (!item.value[vars.config.monthlydate].value) exists=false;
						if (exists)
						{
							if (new Date(item.value[vars.config.monthlydate].value)<vars.fromdate) exists=false;
							if (new Date(item.value[vars.config.monthlydate].value)>vars.todate) exists=false;
						}
						return exists;
					});
				}
				vars.table.insertrow(null,function(row){
					setvalues(row,((i%2==0)?'odd':'even'),(function(record){
						var res=[];
						for (var i2=0;i2<vars.styles.length;i2++)
						{
							var match=$.conditionsmatch(record,vars.fieldinfos,JSON.parse(vars.styles[i2].conditions));
							if (match) res.push({
								record:match,
								style:vars.styles[i2]
							});
						}
						return res;
					})(records[i]),filter);
				});
			}
			/* mouse events */
			$(vars.table.container).on('mousemove','td,th',function(e){
				if (vars.drag.capture) return;
				var left=e.pageX-$(this).offset().left;
				var hit=true;
				if (left<$(this).outerWidth(false)-5) hit=false;
				if (left>$(this).outerWidth(false)) hit=false;
				if (hit) $(this).addClass('adjust');
				else $(this).removeClass('adjust');
			});
			$(vars.table.container).on('mousedown','td,th',function(e){
				if (!$(this).hasClass('adjust')) return;
				vars.drag.capture=true;
				vars.drag.keep.column=$(this).outerWidth(false);
				vars.drag.keep.container=vars.containers[0].outerWidth(false);
				vars.drag.keep.position=e.pageX;
				/* setup resize column */
				vars.drag.cells=[];
				$.each($('td,th',vars.table.container),function(index){
					if (e.pageX>$(this).offset().left && e.pageX<$(this).offset().left+$(this).outerWidth(false)) vars.drag.cells.push($(this));
				});
				e.stopPropagation();
				e.preventDefault();
			});
			$(window).on('mousemove',function(e){
				if (!vars.drag.capture) return;
				var width=0;
				width=vars.drag.keep.column+e.pageX-vars.drag.keep.position;
				if (width<15) width=15;
				/* resize column */
				$.each(vars.drag.cells,function(index){
					vars.drag.cells[index].css({'width':width.toString()+'px'});
					vars.drag.cells[index].find('div').css({'width':width.toString()+'px'});
				});
				/* resize container */
				$.each(vars.containers,function(index){
					vars.containers[index].css({'width':(vars.drag.keep.container-vars.drag.keep.column+width).toString()+'px'});
				});
				e.stopPropagation();
				e.preventDefault();
			});
			$(window).on('mouseup',function(e){
				if (!vars.drag.capture) return;
				vars.drag.capture=false;
				e.stopPropagation();
				e.preventDefault();
			});
		},
		/* setup column fixed */
		setsticky:function(position){
			if (position)
			{
				var limit=parseInt(position)+1;
				var positions=[];
				var left=0;
				$('th',vars.table.container).each(function(index){
					positions.push(left);
					left+=$(this).width();
				});
				$('th',vars.table.container).each(function(index){
					if (index<limit+1) $(this).css({'left':positions[index].toString()+'px'});
					else $(this).css({'left':'auto'});
				});
				$('tbody tr',vars.table.container).each(function(index){
					$('td',$(this)).each(function(index){
						var cellindex=($(this).attr('data-cellindex'))?parseInt($(this).attr('data-cellindex')):index;
						if (cellindex<limit+1) $(this).css({
							'left':positions[cellindex].toString()+'px',
							'position':'-webkit-sticky',
							'position':'sticky'
						});
						else $(this).css({
							'left':'auto',
							'position':'relative'
						});
					});
				});
			}
			else
			{
				$('th',vars.table.container).each(function(index){
					$(this).css({'left':'auto'});
				});
				$('td',vars.table.container).each(function(index){
					$(this).css({
						'left':'auto',
						'position':'relative'
					});
				});
			}
		},
		/* setup value */
		setvalue:function(cell,fieldinfo,values,styles){
			var value=null;
			var unit=(fieldinfo.unit!=null)?fieldinfo.unit:'';
			var unitPosition=(fieldinfo.unitPosition!=null)?fieldinfo.unitPosition.toUpperCase():'BEFORE';
			if (values!=null)
				switch (fieldinfo.type.toUpperCase())
				{
					case 'CALC':
						if (values.length!=0)
						{
							switch(fieldinfo.format.toUpperCase())
							{
								case 'NUMBER':
									value=values;
									break;
								case 'NUMBER_DIGIT':
									value=parseFloat(values).format();
									break;
								case 'DATETIME':
									value=new Date(values.dateformat());
									value=value.format('Y-m-d H:i');
									break;
								case 'DATE':
									value=new Date((values+'T00:00:00+09:00').dateformat());
									value=value.format('Y-m-d');
									break;
								case 'TIME':
									value=new Date(('1900-01-01T'+values+':00+09:00').dateformat());
									value=value.format('H:i');
									break;
								case 'HOUR_MINUTE':
									value=values;
									break;
								case 'DAY_HOUR_MINUTE':
									value=values;
									break;
							}
							if (unitPosition=='BEFORE') value=unit+value;
							else value=value+unit;
							cell.text(value);
						}
						break;
					case 'CATEGORY':
					case 'CHECK_BOX':
					case 'MULTI_SELECT':
						if (values.length!=0)
						{
							value=values.join('
');
							cell.html(value);
						}
						break;
					case 'CREATOR':
					case 'MODIFIER':
						if (values.code.length!=0) cell.html(''+values.name+'');
						break;
					case 'CREATED_TIME':
					case 'DATETIME':
					case 'UPDATED_TIME':
						if (values.length!=0)
						{
							value=new Date(values.dateformat());
							cell.text(value.format('Y-m-d H:i'));
						}
						break;
					case 'DATE':
						if (values.length!=0)
						{
							value=new Date((values+'T00:00:00+09:00').dateformat());
							cell.text(value.format('Y-m-d'));
						}
						break;
					case 'FILE':
						if (values.length!=0)
						{
							value=[];
							$.each(values,function(index){
								switch(values[index].contentType)
								{
									case 'image/bmp':
									case 'image/gif':
									case 'image/jpeg':
									case 'image/png':
										value.push($('')
											.on('click',function(e){
												vars.thumbnail.find('.listviewer-image').attr('src',$(this).attr('src'));
												vars.thumbnail.show();
											})
										);
										functions.download(values[index].fileKey).then(function(blob){
											var url=window.URL || window.webkitURL;
											var image=url.createObjectURL(blob);
											value[index].attr('src',url.createObjectURL(blob));
										});
										break;
									default:
										value.push($(''+values[index].name+'')
											.on('click',function(e){
												functions.download(values[index].fileKey).then(function(blob){
													if (window.navigator.msSaveBlob) window.navigator.msSaveOrOpenBlob(blob,values[index].name);
													else
													{
														var url=window.URL || window.webkitURL;
														var a=document.createElement('a');
														a.setAttribute('href',url.createObjectURL(blob));
														a.setAttribute('target','_blank');
														a.setAttribute('download',values[index].name);
														a.style.display='none';
														document.body.appendChild(a);
														a.click();
														document.body.removeChild(a);
													}
												});
												return false;
											})
										);
										break;
								}
							});
							$.each(value,function(index){cell.append(value[index]);});
						}
						break;
					case 'LINK':
						if (values.length!=0)
						{
							switch(fieldinfo.protocol.toUpperCase())
							{
								case 'CALL':
									value=''+values+'';
									break;
								case 'MAIL':
									value=''+values+'';
									break;
								case 'WEB':
									value=''+values+'';
									break;
							}
							cell.html(value);
						}
						break;
					case 'MULTI_LINE_TEXT':
						if (values.length!=0) cell.html(values.replace(/\n/g,'
'));
						break;
					case 'NUMBER':
						if (values.length!=0)
						{
							if (fieldinfo.digit) value=parseFloat(values).format();
							else value=values;
							if (unitPosition=='BEFORE') value=unit+value;
							else value=value+unit;
							cell.text(value);
						}
						break;
					case 'GROUP_SELECT':
					case 'ORGANIZATION_SELECT':
						if (values.length!=0)
						{
							value='';
							$.each(values,function(index){
								value+=''+values[index].name+'';
							});
							cell.html(value);
						}
						break;
					case 'RICH_TEXT':
						if (values.length!=0) cell.html(values);
						break;
					case 'STATUS_ASSIGNEE':
					case 'USER_SELECT':
						if (values.length!=0)
						{
							value='';
							$.each(values,function(index){
								value+=''+values[index].name+'';
							});
							cell.html(value);
						}
						break;
					case 'TIME':
						if (values.length!=0)
						{
							value=new Date(('1900-01-01T'+values+':00+09:00').dateformat());
							cell.text(value.format('H:i'));
						}
						break;
					default:
						if (values.length!=0) cell.text(values);
						break;
				}
			for (var i=0;i