text:
// Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
 * @unrestricted
 */
Emulation.SensorsView = class extends UI.VBox {
  constructor() {
    super(true);
    this.registerRequiredCSS('emulation/sensors.css');
    this.contentElement.classList.add('sensors-view');

    this._geolocationSetting = Common.settings.createSetting('emulation.geolocationOverride', '');
    this._geolocation = SDK.EmulationModel.Geolocation.parseSetting(this._geolocationSetting.get());
    this._geolocationOverrideEnabled = false;
    this._createGeolocationSection(this._geolocation);

    this.contentElement.createChild('div').classList.add('panel-section-separator');

    this._deviceOrientationSetting = Common.settings.createSetting('emulation.deviceOrientationOverride', '');
    this._deviceOrientation = SDK.EmulationModel.DeviceOrientation.parseSetting(this._deviceOrientationSetting.get());
    this._deviceOrientationOverrideEnabled = false;
    this._createDeviceOrientationSection();

    this.contentElement.createChild('div').classList.add('panel-section-separator');

    this._appendTouchControl();
  }

  /**
   * @return {!Emulation.SensorsView}
   */
  static instance() {
    if (!Emulation.SensorsView._instanceObject)
      Emulation.SensorsView._instanceObject = new Emulation.SensorsView();
    return Emulation.SensorsView._instanceObject;
  }

  /**
   * @param {!SDK.EmulationModel.Geolocation} geolocation
   */
  _createGeolocationSection(geolocation) {
    const geogroup = this.contentElement.createChild('section', 'sensors-group');
    geogroup.createChild('div', 'sensors-group-title').textContent = Common.UIString('Geolocation');
    const fields = geogroup.createChild('div', 'geo-fields');

    const noOverrideOption = {
      title: Common.UIString('No override'),
      location: Emulation.SensorsView.NonPresetOptions.NoOverride
    };
    const customLocationOption = {
      title: Common.UIString('Custom location...'),
      location: Emulation.SensorsView.NonPresetOptions.Custom
    };
    this._locationSelectElement = this.contentElement.createChild('select', 'chrome-select');
    this._locationSelectElement.appendChild(new Option(noOverrideOption.title, noOverrideOption.location));
    this._locationSelectElement.appendChild(new Option(customLocationOption.title, customLocationOption.location));

    const locationGroups = Emulation.SensorsView.PresetLocations;
    for (let i = 0; i < locationGroups.length; ++i) {
      const group = locationGroups[i].value;
      const groupElement = this._locationSelectElement.createChild('optgroup');
      groupElement.label = locationGroups[i].title;
      for (let j = 0; j < group.length; ++j)
        groupElement.appendChild(new Option(group[j].title, group[j].location));
    }
    this._locationSelectElement.selectedIndex = 0;
    fields.appendChild(this._locationSelectElement);
    this._locationSelectElement.addEventListener('change', this._geolocationSelectChanged.bind(this));

    // Validated input fieldset.
    this._fieldsetElement = fields.createChild('fieldset');
    this._fieldsetElement.disabled = !this._geolocationOverrideEnabled;
    this._fieldsetElement.id = 'geolocation-override-section';

    const latitudeGroup = this._fieldsetElement.createChild('div', 'latlong-group');
    const longitudeGroup = this._fieldsetElement.createChild('div', 'latlong-group');

    this._latitudeInput = UI.createInput('', 'number');
    latitudeGroup.appendChild(this._latitudeInput);
    this._latitudeInput.setAttribute('step', 'any');
    this._latitudeInput.value = 0;
    this._latitudeSetter = UI.bindInput(
        this._latitudeInput, this._applyGeolocationUserInput.bind(this),
        SDK.EmulationModel.Geolocation.latitudeValidator, true, 0.1);
    this._latitudeSetter(String(geolocation.latitude));

    this._longitudeInput = UI.createInput('', 'number');
    longitudeGroup.appendChild(this._longitudeInput);
    this._longitudeInput.setAttribute('step', 'any');
    this._longitudeInput.value = 0;
    this._longitudeSetter = UI.bindInput(
        this._longitudeInput, this._applyGeolocationUserInput.bind(this),
        SDK.EmulationModel.Geolocation.longitudeValidator, true, 0.1);
    this._longitudeSetter(String(geolocation.longitude));

    const cmdOrCtrl = Host.isMac() ? '\u2318' : 'Ctrl';
    const modifierKeyMessage = ls`Adjust with mousewheel or up/down keys. ${cmdOrCtrl}: ±10, Shift: ±1, Alt: ±0.01`;
    this._latitudeInput.title = modifierKeyMessage;
    this._longitudeInput.title = modifierKeyMessage;

    latitudeGroup.createChild('div', 'latlong-title').textContent = Common.UIString('Latitude');
    longitudeGroup.createChild('div', 'latlong-title').textContent = Common.UIString('Longitude');
  }

  _geolocationSelectChanged() {
    this._fieldsetElement.disabled = false;
    const value = this._locationSelectElement.options[this._locationSelectElement.selectedIndex].value;
    if (value === Emulation.SensorsView.NonPresetOptions.NoOverride) {
      this._geolocationOverrideEnabled = false;
      this._fieldsetElement.disabled = true;
    } else if (value === Emulation.SensorsView.NonPresetOptions.Custom) {
      this._geolocationOverrideEnabled = true;
    } else if (value === Emulation.SensorsView.NonPresetOptions.Unavailable) {
      this._geolocationOverrideEnabled = true;
      this._geolocation = new SDK.EmulationModel.Geolocation(0, 0, true);
    } else {
      this._geolocationOverrideEnabled = true;
      const coordinates = JSON.parse(value);
      this._geolocation = new SDK.EmulationModel.Geolocation(coordinates[0], coordinates[1], false);
      this._latitudeSetter(coordinates[0]);
      this._longitudeSetter(coordinates[1]);
    }

    this._applyGeolocation();
    if (value === Emulation.SensorsView.NonPresetOptions.Custom)
      this._latitudeInput.focus();
  }

  _applyGeolocationUserInput() {
    const geolocation = SDK.EmulationModel.Geolocation.parseUserInput(
        this._latitudeInput.value.trim(), this._longitudeInput.value.trim(), '');
    if (!geolocation)
      return;

    this._setSelectElementLabel(this._locationSelectElement, Emulation.SensorsView.NonPresetOptions.Custom);
    this._geolocation = geolocation;
    this._applyGeolocation();
  }

  _applyGeolocation() {
    if (this._geolocationOverrideEnabled)
      this._geolocationSetting.set(this._geolocation.toSetting());
    for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
      emulationModel.emulateGeolocation(this._geolocationOverrideEnabled ? this._geolocation : null);
  }

  _createDeviceOrientationSection() {
    const orientationGroup = this.contentElement.createChild('section', 'sensors-group');
    orientationGroup.createChild('div', 'sensors-group-title').textContent = Common.UIString('Orientation');
    const orientationContent = orientationGroup.createChild('div', 'orientation-content');
    const fields = orientationContent.createChild('div', 'orientation-fields');

    const orientationOffOption = {
      title: Common.UIString('Off'),
      orientation: Emulation.SensorsView.NonPresetOptions.NoOverride
    };
    const customOrientationOption = {
      title: Common.UIString('Custom orientation...'),
      orientation: Emulation.SensorsView.NonPresetOptions.Custom
    };
    this._orientationSelectElement = this.contentElement.createChild('select', 'chrome-select');
    this._orientationSelectElement.appendChild(
        new Option(orientationOffOption.title, orientationOffOption.orientation));
    this._orientationSelectElement.appendChild(
        new Option(customOrientationOption.title, customOrientationOption.orientation));

    const orientationGroups = Emulation.SensorsView.PresetOrientations;
    for (let i = 0; i < orientationGroups.length; ++i) {
      const groupElement = this._orientationSelectElement.createChild('optgroup');
      groupElement.label = orientationGroups[i].title;
      const group = orientationGroups[i].value;
      for (let j = 0; j < group.length; ++j)
        groupElement.appendChild(new Option(group[j].title, group[j].orientation));
    }
    this._orientationSelectElement.selectedIndex = 0;
    fields.appendChild(this._orientationSelectElement);
    this._orientationSelectElement.addEventListener('change', this._orientationSelectChanged.bind(this));

    this._deviceOrientationFieldset = this._createDeviceOrientationOverrideElement(this._deviceOrientation);

    this._stageElement = orientationContent.createChild('div', 'orientation-stage');
    this._stageElement.title = Common.UIString('Shift+drag horizontally to rotate around the y-axis');
    this._orientationLayer = this._stageElement.createChild('div', 'orientation-layer');
    this._boxElement = this._orientationLayer.createChild('section', 'orientation-box orientation-element');

    this._boxElement.createChild('section', 'orientation-front orientation-element');
    this._boxElement.createChild('section', 'orientation-top orientation-element');
    this._boxElement.createChild('section', 'orientation-back orientation-element');
    this._boxElement.createChild('section', 'orientation-left orientation-element');
    this._boxElement.createChild('section', 'orientation-right orientation-element');
    this._boxElement.createChild('section', 'orientation-bottom orientation-element');

    UI.installDragHandle(
        this._stageElement, this._onBoxDragStart.bind(this), this._onBoxDrag.bind(this), null, '-webkit-grabbing',
        '-webkit-grab');

    fields.appendChild(this._deviceOrientationFieldset);
    this._enableOrientationFields(true);
    this._setBoxOrientation(this._deviceOrientation, false);
  }

  /**
   * @param {?boolean} disable
   */
  _enableOrientationFields(disable) {
    if (disable) {
      this._deviceOrientationFieldset.disabled = true;
      this._stageElement.classList.add('disabled');
    } else {
      this._deviceOrientationFieldset.disabled = false;
      this._stageElement.classList.remove('disabled');
    }
  }

  _orientationSelectChanged() {
    const value = this._orientationSelectElement.options[this._orientationSelectElement.selectedIndex].value;
    this._enableOrientationFields(false);

    if (value === Emulation.SensorsView.NonPresetOptions.NoOverride) {
      this._deviceOrientationOverrideEnabled = false;
      this._enableOrientationFields(true);
    } else if (value === Emulation.SensorsView.NonPresetOptions.Custom) {
      this._deviceOrientationOverrideEnabled = true;
      this._alphaElement.focus();
    } else {
      const parsedValue = JSON.parse(value);
      this._deviceOrientationOverrideEnabled = true;
      this._deviceOrientation =
          new SDK.EmulationModel.DeviceOrientation(parsedValue[0], parsedValue[1], parsedValue[2]);
      this._setDeviceOrientation(
          this._deviceOrientation, Emulation.SensorsView.DeviceOrientationModificationSource.SelectPreset);
    }
  }

  _applyDeviceOrientation() {
    if (this._deviceOrientationOverrideEnabled)
      this._deviceOrientationSetting.set(this._deviceOrientation.toSetting());
    for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
      emulationModel.emulateDeviceOrientation(this._deviceOrientationOverrideEnabled ? this._deviceOrientation : null);
  }

  /**
   * @param {!Element} selectElement
   * @param {string} labelValue
   */
  _setSelectElementLabel(selectElement, labelValue) {
    const optionValues = Array.prototype.map.call(selectElement.options, x => x.value);
    selectElement.selectedIndex = optionValues.indexOf(labelValue);
  }

  _applyDeviceOrientationUserInput() {
    this._setDeviceOrientation(
        SDK.EmulationModel.DeviceOrientation.parseUserInput(
            this._alphaElement.value.trim(), this._betaElement.value.trim(), this._gammaElement.value.trim()),
        Emulation.SensorsView.DeviceOrientationModificationSource.UserInput);
    this._setSelectElementLabel(this._orientationSelectElement, Emulation.SensorsView.NonPresetOptions.Custom);
  }

  _resetDeviceOrientation() {
    this._setDeviceOrientation(
        new SDK.EmulationModel.DeviceOrientation(0, 90, 0),
        Emulation.SensorsView.DeviceOrientationModificationSource.ResetButton);
    this._setSelectElementLabel(this._orientationSelectElement, '[0, 90, 0]');
  }

  /**
   * @param {?SDK.EmulationModel.DeviceOrientation} deviceOrientation
   * @param {!Emulation.SensorsView.DeviceOrientationModificationSource} modificationSource
   */
  _setDeviceOrientation(deviceOrientation, modificationSource) {
    if (!deviceOrientation)
      return;

    /**
     * @param {number} angle
     * @return {number}
     */
    function roundAngle(angle) {
      return Math.round(angle * 10000) / 10000;
    }

    if (modificationSource !== Emulation.SensorsView.DeviceOrientationModificationSource.UserInput) {
      this._alphaSetter(roundAngle(deviceOrientation.alpha));
      this._betaSetter(roundAngle(deviceOrientation.beta));
      this._gammaSetter(roundAngle(deviceOrientation.gamma));
    }

    const animate = modificationSource !== Emulation.SensorsView.DeviceOrientationModificationSource.UserDrag;
    this._setBoxOrientation(deviceOrientation, animate);

    this._deviceOrientation = deviceOrientation;
    this._applyDeviceOrientation();
  }

  /**
   * @param {!Element} parentElement
   * @param {!Element} input
   * @param {string} label
   * @return {function(string)}
   */
  _createAxisInput(parentElement, input, label) {
    const div = parentElement.createChild('div', 'orientation-axis-input-container');
    div.appendChild(input);
    div.createTextChild(label);
    input.type = 'number';
    return UI.bindInput(
        input, this._applyDeviceOrientationUserInput.bind(this), SDK.EmulationModel.DeviceOrientation.validator, true);
  }

  /**
   * @param {!SDK.EmulationModel.DeviceOrientation} deviceOrientation
   * @return {!Element}
   */
  _createDeviceOrientationOverrideElement(deviceOrientation) {
    const fieldsetElement = createElement('fieldset');
    fieldsetElement.classList.add('device-orientation-override-section');
    const cellElement = fieldsetElement.createChild('td', 'orientation-inputs-cell');

    this._alphaElement = UI.createInput();
    this._alphaElement.setAttribute('step', 'any');
    this._alphaSetter = this._createAxisInput(cellElement, this._alphaElement, Common.UIString('\u03B1 (alpha)'));
    this._alphaSetter(String(deviceOrientation.alpha));

    this._betaElement = UI.createInput();
    this._betaElement.setAttribute('step', 'any');
    this._betaSetter = this._createAxisInput(cellElement, this._betaElement, Common.UIString('\u03B2 (beta)'));
    this._betaSetter(String(deviceOrientation.beta));

    this._gammaElement = UI.createInput();
    this._gammaElement.setAttribute('step', 'any');
    this._gammaSetter = this._createAxisInput(cellElement, this._gammaElement, Common.UIString('\u03B3 (gamma)'));
    this._gammaSetter(String(deviceOrientation.gamma));

    cellElement.appendChild(UI.createTextButton(
        Common.UIString('Reset'), this._resetDeviceOrientation.bind(this), 'orientation-reset-button'));
    return fieldsetElement;
  }

  /**
   * @param {!SDK.EmulationModel.DeviceOrientation} deviceOrientation
   * @param {boolean} animate
   */
  _setBoxOrientation(deviceOrientation, animate) {
    if (animate)
      this._stageElement.classList.add('is-animating');
    else
      this._stageElement.classList.remove('is-animating');

    // The CSS transform should not depend on matrix3d, which does not interpolate well.
    const matrix = new WebKitCSSMatrix();
    this._boxMatrix = matrix.rotate(-deviceOrientation.beta, deviceOrientation.gamma, -deviceOrientation.alpha);
    const eulerAngles =
        new UI.Geometry.EulerAngles(deviceOrientation.alpha, deviceOrientation.beta, deviceOrientation.gamma);
    this._orientationLayer.style.transform = eulerAngles.toRotate3DString();
  }

  /**
   * @param {!MouseEvent} event
   * @return {boolean}
   */
  _onBoxDrag(event) {
    const mouseMoveVector = this._calculateRadiusVector(event.x, event.y);
    if (!mouseMoveVector)
      return true;

    event.consume(true);
    let axis, angle;
    if (event.shiftKey) {
      axis = new UI.Geometry.Vector(0, 0, -1);
      angle = (this._mouseDownVector.x - mouseMoveVector.x) * Emulation.SensorsView.ShiftDragOrientationSpeed;
    } else {
      axis = UI.Geometry.crossProduct(this._mouseDownVector, mouseMoveVector);
      angle = UI.Geometry.calculateAngle(this._mouseDownVector, mouseMoveVector);
    }

    // The mouse movement vectors occur in the screen space, which is offset by 90 degrees from
    // the actual device orientation.
    let currentMatrix = new WebKitCSSMatrix();
    currentMatrix = currentMatrix.rotate(-90, 0, 0)
                        .rotateAxisAngle(axis.x, axis.y, axis.z, angle)
                        .rotate(90, 0, 0)
                        .multiply(this._originalBoxMatrix);

    const eulerAngles = UI.Geometry.EulerAngles.fromRotationMatrix(currentMatrix);
    const newOrientation =
        new SDK.EmulationModel.DeviceOrientation(-eulerAngles.alpha, -eulerAngles.beta, eulerAngles.gamma);
    this._setDeviceOrientation(newOrientation, Emulation.SensorsView.DeviceOrientationModificationSource.UserDrag);
    this._setSelectElementLabel(this._orientationSelectElement, Emulation.SensorsView.NonPresetOptions.Custom);
    return false;
  }

  /**
   * @param {!MouseEvent} event
   * @return {boolean}
   */
  _onBoxDragStart(event) {
    if (!this._deviceOrientationOverrideEnabled)
      return false;

    this._mouseDownVector = this._calculateRadiusVector(event.x, event.y);
    this._originalBoxMatrix = this._boxMatrix;

    if (!this._mouseDownVector)
      return false;

    event.consume(true);
    return true;
  }

  /**
   * @param {number} x
   * @param {number} y
   * @return {?UI.Geometry.Vector}
   */
  _calculateRadiusVector(x, y) {
    const rect = this._stageElement.getBoundingClientRect();
    const radius = Math.max(rect.width, rect.height) / 2;
    const sphereX = (x - rect.left - rect.width / 2) / radius;
    const sphereY = (y - rect.top - rect.height / 2) / radius;
    const sqrSum = sphereX * sphereX + sphereY * sphereY;
    if (sqrSum > 0.5)
      return new UI.Geometry.Vector(sphereX, sphereY, 0.5 / Math.sqrt(sqrSum));

    return new UI.Geometry.Vector(sphereX, sphereY, Math.sqrt(1 - sqrSum));
  }

  _appendTouchControl() {
    const groupElement = this.contentElement.createChild('div', 'sensors-group');
    const title = groupElement.createChild('div', 'sensors-group-title');
    const fieldsElement = groupElement.createChild('div', 'sensors-group-fields');

    title.textContent = Common.UIString('Touch');
    const select = fieldsElement.createChild('select', 'chrome-select');
    select.appendChild(new Option(Common.UIString('Device-based'), 'auto'));
    select.appendChild(new Option(Common.UIString('Force enabled'), 'enabled'));
    select.addEventListener('change', applyTouch, false);

    const reloadWarning = groupElement.createChild('div', 'reload-warning hidden');
    reloadWarning.textContent = Common.UIString('*Requires reload');

    function applyTouch() {
      for (const emulationModel of SDK.targetManager.models(SDK.EmulationModel))
        emulationModel.overrideEmulateTouch(select.value === 'enabled');
      reloadWarning.classList.remove('hidden');
      const resourceTreeModel = SDK.targetManager.models(SDK.ResourceTreeModel)[0];
      if (resourceTreeModel) {
        resourceTreeModel.once(SDK.ResourceTreeModel.Events.MainFrameNavigated)
            .then(() => reloadWarning.classList.add('hidden'));
      }
    }
  }
};

/** @enum {string} */
Emulation.SensorsView.DeviceOrientationModificationSource = {
  UserInput: 'userInput',
  UserDrag: 'userDrag',
  ResetButton: 'resetButton',
  SelectPreset: 'selectPreset'
};

/** {string} */
Emulation.SensorsView.NonPresetOptions = {
  'NoOverride': 'noOverride',
  'Custom': 'custom',
  'Unavailable': 'unavailable'
};

/** @type {!Array.<{title: string, value: !Array.<{title: string, location: string}>}>} */
Emulation.SensorsView.PresetLocations = [
  {
    title: 'Presets',
    value: [
      {title: Common.UIString('Berlin'), location: '[52.520007, 13.404954]'},
      {title: Common.UIString('London'), location: '[51.507351, -0.127758]'},
      {title: Common.UIString('Moscow'), location: '[55.755826, 37.617300]'},
      {title: Common.UIString('Mountain View'), location: '[37.386052, -122.083851]'},
      {title: Common.UIString('Mumbai'), location: '[19.075984, 72.877656]'},
      {title: Common.UIString('San Francisco'), location: '[37.774929, -122.419416]'},
      {title: Common.UIString('Shanghai'), location: '[31.230416, 121.473701]'},
      {title: Common.UIString('São Paulo'), location: '[-23.550520, -46.633309]'},
      {title: Common.UIString('Tokyo'), location: '[35.689487, 139.691706]'},
    ]
  },
  {
    title: 'Error',
    value: [
      {title: Common.UIString('Location unavailable'), location: Emulation.SensorsView.NonPresetOptions.Unavailable}
    ]
  }
];

/** @type {!Array.<{title: string, value: !Array.<{title: string, orientation: string}>}>} */
Emulation.SensorsView.PresetOrientations = [{
  title: 'Presets',
  value: [
    {title: Common.UIString('Portrait'), orientation: '[0, 90, 0]'},
    {title: Common.UIString('Portrait upside down'), orientation: '[180, -90, 0]'},
    {title: Common.UIString('Landscape left'), orientation: '[0, 90, -90]'},
    {title: Common.UIString('Landscape right'), orientation: '[0, 90, 90]'},
    {title: Common.UIString('Display up'), orientation: '[0, 0, 0]'},
    {title: Common.UIString('Display down'), orientation: '[0, 180, 0]'}
  ]
}];

/**
 * @implements {UI.ActionDelegate}
 * @unrestricted
 */
Emulation.SensorsView.ShowActionDelegate = class {
  /**
   * @override
   * @param {!UI.Context} context
   * @param {string} actionId
   * @return {boolean}
   */
  handleAction(context, actionId) {
    UI.viewManager.showView('sensors');
    return true;
  }
};

Emulation.SensorsView.ShiftDragOrientationSpeed = 16;


text:
A Continuous Delivery (CD) tool, which we and all stakeholders of the CD pipeline love to use. Licensed under the MIT License

> A free, open-source
> Continuous Delivery tool
> that's powerful enough for the enterprise,
> flexible enough for startups
> and simple to use for hobbyists

## Vision
- [Why a new tool for Continuous Delivery](/pipelinelabs/pipeline/wiki/Vision-Why-a-new-tool-for-Continuous-Delivery)

## User Guide
- [Using Pipeline with a Central Repository](/pipelinelabs/pipeline/wiki/User-Guide-Set-up-with-Central-Repository)
- [Configuring the Pipeline Configuration for your project](/pipelinelabs/pipeline/wiki/User-Guide-Project-Pipeline-Configuration)

## Technical Design
- [Braindump](/pipelinelabs/pipeline/wiki/Technical-Design-Braindump)
- [System Design](/pipelinelabs/pipeline/wiki/Technical-Design-System-design)
- [Command Ideas](/pipelinelabs/pipeline/wiki/Technical-Design-Command-Ideas)
- [DSL Design Ideas](/pipelinelabs/pipeline/wiki/Technical-Design-DSL-Design-Ideas)

redpajama_set_name: RedPajamaGithub


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const fs = require("fs-extra");
const path = require("path");
const semver = require("semver");
const debug = require('debug')('update-check');
const hook = async function ({ config }) {
    const file = path.join(config.cacheDir, 'version');
    // Destructure package.json configuration with defaults
    const { timeoutInDays = 60, message = '<%= config.name %> update available from <%= chalk.greenBright(config.version) %> to <%= chalk.greenBright(latest) %>.', registry = 'https://registry.npmjs.org', authorization = '', } = config.pjson.oclif['warn-if-update-available'] || {};
    const checkVersion = async () => {
        try {
            // do not show warning if updating
            if (process.argv[2] === 'update')
                return;
            const distTags = await fs.readJSON(file);
            if (config.version.includes('-')) {
                // TODO: handle channels
                return;
            }
            if (distTags && distTags.latest && semver.gt(distTags.latest.split('-')[0], config.version.split('-')[0])) {
                const chalk = require('chalk');
                const template = require('lodash.template');
                // Default message if the user doesn't provide one
                this.warn(template(message)(Object.assign({ chalk,
                    config }, distTags)));
            }
        }
        catch (err) {
            if (err.code !== 'ENOENT')
                throw err;
        }
    };
    const refreshNeeded = async () => {
        try {
            const { mtime } = await fs.stat(file);
            const staleAt = new Date(mtime.valueOf() + 1000 * 60 * 60 * 24 * timeoutInDays);
            return staleAt < new Date();
        }
        catch (err) {
            debug(err);
            return true;
        }
    };
    const spawnRefresh = async () => {
        debug('spawning version refresh');
        child_process_1.spawn(process.execPath, [path.join(__dirname, '../../../lib/get-version'), config.name, file, config.version, registry, authorization], {
            detached: !config.windows,
            stdio: 'ignore',
        }).unref();
    };
    await checkVersion();
    if (await refreshNeeded())
        await spawnRefresh();
};
exports.default = hook;


text:
import logging
import os

import numpy as np
import torch

from fairseq import utils
from fairseq.data import (
    AppendTokenDataset,
    data_utils,
    Dictionary,
    IdDataset,
    MonolingualDataset,
    NestedDictionaryDataset,
    NumelDataset,
    PadDataset,
    PrependTokenDataset,
    StripTokenDataset,
    TokenBlockDataset,
    TransformEosDataset,
    TruncatedDictionary,
)
from fairseq.data.shorten_dataset import maybe_shorten_dataset
from fairseq.tasks import FairseqTask, register_task

logger = logging.getLogger(__name__)

@register_task("language_modeling")
class LanguageModelingTask(FairseqTask):
    """
    Train a language model.

    Args:
        dictionary (~fairseq.data.Dictionary): the dictionary for the input of
            the language model
        output_dictionary (~fairseq.data.Dictionary): the dictionary for the
            output of the language model. In most cases it will be the same as
            *dictionary*, but could possibly be a more limited version of the
            dictionary (if ``--output-dictionary-size`` is used).
        targets (List[str]): list of the target types that the language model
            should predict.  Can be one of "self", "future", and "past".
            Defaults to "future".

    .. note::

        The language modeling task is compatible with :mod:`fairseq-train`,
        :mod:`fairseq-generate`, :mod:`fairseq-interactive` and
        :mod:`fairseq-eval-lm`.

    The language modeling task provides the following additional command-line
    arguments:

    .. argparse::
        :ref: fairseq.tasks.language_modeling_parser
        :prog:
    """

    @staticmethod
    def add_args(parser):
        """Add task-specific arguments to the parser."""
        # fmt: off
        parser.add_argument('data', help='path to data directory')
        parser.add_argument('--sample-break-mode', default='none',
                            choices=['none', 'complete', 'complete_doc', 'eos'],
                            help='If omitted or "none", fills each sample with tokens-per-sample '
                                 'tokens. If set to "complete", splits samples only at the end '
                                 'of sentence, but may include multiple sentences per sample. '
                                 '"complete_doc" is similar but respects doc boundaries. '
                                 'If set to "eos", includes only one sentence per sample.')
        parser.add_argument('--tokens-per-sample', default=1024, type=int,
                            help='max number of tokens per sample for LM dataset')
        parser.add_argument('--output-dictionary-size', default=-1, type=int,
                            help='limit the size of output dictionary')
        parser.add_argument('--self-target', action='store_true',
                            help='include self target')
        parser.add_argument('--future-target', action='store_true',
                            help='include future target')
        parser.add_argument('--past-target', action='store_true',
                            help='include past target')
        parser.add_argument('--add-bos-token', action='store_true',
                            help='prepend beginning of sentence token (<s>)')
        parser.add_argument('--max-target-positions', type=int, metavar='N',
                            help='max number of tokens in the target sequence')
        parser.add_argument('--shorten-method', default='none',
                            choices=['none', 'truncate', 'random_crop'],
                            help='if not none, shorten sequences that exceed --tokens-per-sample')
        parser.add_argument('--shorten-data-split-list', default='',
                            help='comma-separated list of dataset splits to apply shortening to, '
                                 'e.g., "train,valid" (default: all dataset splits)')
        # fmt: on

    def __init__(self, args, dictionary, output_dictionary=None, targets=None):
        super().__init__(args)
        self.dictionary = dictionary
        self.output_dictionary = output_dictionary or dictionary

        if targets is None:
            targets = ["future"]
        self.targets = targets

    @classmethod
    def setup_dictionary(cls, args, **kwargs):
        dictionary = None
        output_dictionary = None
        if args.data:
            paths = utils.split_paths(args.data)
            assert len(paths) > 0
            dictionary = Dictionary.load(os.path.join(paths[0], "dict.txt"))
            logger.info("dictionary: {} types".format(len(dictionary)))
            output_dictionary = dictionary
            if args.output_dictionary_size >= 0:
                output_dictionary = TruncatedDictionary(
                    dictionary, args.output_dictionary_size
                )
        return (dictionary, output_dictionary)

    @classmethod
    def setup_task(cls, args, **kwargs):
        """Setup the task (e.g., load dictionaries).

        Args:
            args (argparse.Namespace): parsed command-line arguments
        """
        dictionary, output_dictionary = cls.setup_dictionary(args, **kwargs)

        # upgrade old checkpoints
        if hasattr(args, "exclude_self_target"):
            args.self_target = not args.exclude_self_target

        targets = []
        if getattr(args, "self_target", False):
            targets.append("self")
        if getattr(args, "future_target", False):
            targets.append("future")
        if getattr(args, "past_target", False):
            targets.append("past")
        if len(targets) == 0:
            # standard language modeling
            targets = ["future"]

        return cls(args, dictionary, output_dictionary, targets=targets)

    def build_model(self, args):
        model = super().build_model(args)

        for target in self.targets:
            if target not in model.supported_targets:
                raise ValueError(
                    "Unsupported language modeling target: {}".format(target)
                )

        return model

    def load_dataset(self, split, epoch=1, combine=False, **kwargs):
        """Load a given dataset split.

        Args:
            split (str): name of the split (e.g., train, valid, test)
        """
        paths = utils.split_paths(self.args.data)
        assert len(paths) > 0

        data_path = paths[(epoch - 1) % len(paths)]
        split_path = os.path.join(data_path, split)

        dataset = data_utils.load_indexed_dataset(
            split_path, self.dictionary, self.args.dataset_impl, combine=combine
        )
        if dataset is None:
            raise FileNotFoundError(
                "Dataset not found: {} ({})".format(split, split_path)
            )

        dataset = maybe_shorten_dataset(
            dataset,
            split,
            self.args.shorten_data_split_list,
            self.args.shorten_method,
            self.args.tokens_per_sample,
            self.args.seed,
        )

        dataset = TokenBlockDataset(
            dataset,
            dataset.sizes,
            self.args.tokens_per_sample,
            pad=self.dictionary.pad(),
            eos=self.dictionary.eos(),
            break_mode=self.args.sample_break_mode,
            include_targets=True,
        )

        add_eos_for_other_targets = (
            self.args.sample_break_mode is not None
            and self.args.sample_break_mode != "none"
        )

        self.datasets[split] = self._initialize_dataset(
            dataset=dataset,
            sizes=dataset.sizes,
            src_vocab=self.dictionary,
            tgt_vocab=self.output_dictionary,
            add_eos_for_other_targets=add_eos_for_other_targets,
            shuffle=True,
            targets=self.targets,
            add_bos_token=self.args.add_bos_token,
        )

    def _initialize_dataset(self, **kwargs):
        return MonolingualDataset(**kwargs)

    def build_dataset_for_inference(self, src_tokens, src_lengths, **kwargs):
        """
        Generate batches for inference. We prepend an eos token to src_tokens
        (or bos if `--add-bos-token` is set) and we append a <pad> to target.
        This is convenient both for generation with a prefix and LM scoring.
        """
        dataset = StripTokenDataset(
            TokenBlockDataset(
                src_tokens,
                src_lengths,
                block_size=None,  # ignored for "eos" break mode
                pad=self.source_dictionary.pad(),
                eos=self.source_dictionary.eos(),
                break_mode="eos",
            ),
            # remove eos from (end of) target sequence
            self.source_dictionary.eos(),
        )
        src_dataset = PrependTokenDataset(
            dataset,
            token=(
                self.source_dictionary.bos()
                if getattr(self.args, "add_bos_token", False)
                else self.source_dictionary.eos()
            ),
        )
        tgt_dataset = AppendTokenDataset(
            dataset,
            token=self.source_dictionary.pad()
        )
        return NestedDictionaryDataset(
            {
                "id": IdDataset(),
                "net_input": {
                    "src_tokens": PadDataset(src_dataset, pad_idx=self.source_dictionary.pad(), left_pad=False),
                    "src_lengths": NumelDataset(src_dataset, reduce=False),
                },
                "target": PadDataset(tgt_dataset, pad_idx=self.source_dictionary.pad(), left_pad=False),
            },
            sizes=[np.array(src_lengths)],
        )

    def inference_step(self, generator, models, sample, prefix_tokens=None):
        with torch.no_grad():
            # Generation will always be conditioned on bos_token
            if getattr(self.args, "add_bos_token", False):
                bos_token = self.source_dictionary.bos()
            else:
                bos_token = self.source_dictionary.eos()

            # SequenceGenerator doesn't use src_tokens directly, we need to
            # pass the `prefix_tokens` argument instead
            if prefix_tokens is None and sample["net_input"]["src_tokens"].nelement():
                prefix_tokens = sample["net_input"]["src_tokens"]
                if prefix_tokens[:, 0].eq(bos_token).all():
                    prefix_tokens = prefix_tokens[:, 1:]

            return generator.generate(
                models, sample, prefix_tokens=prefix_tokens, bos_token=bos_token,
            )

    @property
    def source_dictionary(self):
        """Return the :class:`~fairseq.data.Dictionary` for the language
        model."""
        return self.dictionary

    @property
    def target_dictionary(self):
        """Return the :class:`~fairseq.data.Dictionary` for the language
        model."""
        return self.output_dictionary


text:
function initTemplates() {
    var templateFields = $("#templateFields");
    templateFields.hide();
    $("#startButton").hide();
    var selectList = $("#templates");
    for (var i = 0; i < templates.length; i++) {
        selectList.append('<option value="' + i + '">' + templates[i].title
                + '</option>');
    }
    selectList
            .change(function(e) {
                templateFields.show();
                $('#signersContainer').text('(None)');
                $('#ccsContainer').text('(None)');
                $('#customFieldsContainer').text('(None)');
                var template = templates[$("option:selected", this).attr(
                        "value")];
                if (template) {
                    if (template.signer_roles.length > 0) {
                        $('#signersContainer').empty();
                    }
                    for (var i = 0; i < template.signer_roles.length; i++) {
                        var signerRole = template.signer_roles[i];
                        var newOptionStr = ''
                                + (signerRole.order != null ? signerRole.order
                                        : '')
                                + signerRole.name
                                + ': <input type="text" name="signerRole_email_'
                                + signerRole.name
                                + '" placeholder="Email address"/> '
                                + '<input type="text" name="signerRole_name_'
                                + signerRole.name
                                + '" placeholder="Name"/>
';
                        var newSignerFields = $(newOptionStr);
                        $('#signersContainer').append(newSignerFields);
                    }
                    if (template.cc_roles.length > 0) {
                        $('#ccsContainer').text('(None)');
                    }
                    for (var i = 0; i < template.cc_roles.length; i++) {
                        var ccRole = template.cc_roles[i].name;
                        var newCCFieldStr = ''
                                + ccRole
                                + ': <input type="text" name="ccRole_'
                                + ccRole
                                + '" placeholder="Email address"/>
'
                        var newCCFields = $(newCCFieldStr);
                        $('#ccsContainer').append(newCCFields);
                    }
                    if (template.custom_fields.length > 0) {
                        $('#customFieldsContainer').text('(None)');
                    }
                    for (var i = 0; i < template.custom_fields.length; i++) {
                        var cf = template.custom_fields[i];
                        var newCFFieldStr = ''
                                + cf.name
                                + ': <input type="text" name="cf_'
                                + cf.name + '" placeholder="' + cf.type
                                + '"/>
';
                        var newCFField = $(newCFFieldStr);
                        $('#customFieldsContainer').append(newCFField);
                    }
                    $('#templateId').val(template.template_id);
                    $('#startButton').show();
                } else {
                    $('#templateFields').hide();
                    $('#startButton').hide();
                }
            });
};


text:
var Alexa = require('alexa-sdk')
var foodapi = require('./foodapi.js')

var firebase = require("firebase")
firebase.initializeApp({
  serviceAccount: "firebase-creds.json",
  databaseURL: "https://can-i-eat-alexa-skill.firebaseio.com/"
})
const db = firebase.database()

const userId = 'one'

var APP_ID = undefined; //OPTIONAL: replace with "amzn1.echo-sdk-ams.app.[your-unique-value-here]"
var SKILL_NAME = 'Can I Eat'

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context)
    alexa.appId = APP_ID
    alexa.registerHandlers(handlers)
    alexa.execute()
}

var handlers = {
    'LaunchRequest': function () {
    },
    'WhatAllergens': function () { // Is a food ok for me?
        const food = this.event.request.intent.slots.Food.value
        // this.emit(':tell', `You asked about ${food}`)
        foodapi.makeSession(() => {
          foodapi.search(food, (upc) => {
            foodapi.getAllergens(upc, (allergens) => {
              const bad = allergens.red
              const badAllergenList = naturalJoin(bad)
              const minor = allergens.yellow
              const minorAllergenList = naturalJoin(minor)

              if (bad.length >= 1 && minor.length >= 1) {
                this.emit(':tell', `${food} contains ${badAllergenList} and traces of ${minorAllergenList}`)
              }
              else if (bad.length >= 1 ) {
                this.emit(':tell', `${food} contains ${badAllergenList}`)
              }
              else if (minor.length >= 1) {
                this.emit(':tell', `${food} contains traces of ${minorAllergenList}`)
              }
              else {
                this.emit(':tell', `${food} is free of allergens`)
              }
            })
          })
        })
    },
    'AllergensList': function () { // List the user's allergens
        const ref = db.ref(`allergies/${userId}`)
        ref.once("value", (snapshot) => {
            const allergies = snapshot.val()
            this.emit(':tell', `You have allergies to: ${naturalJoin(allergies)}`)
        })
    },
    'AMAZON.HelpIntent': function () {
        var speechOutput = "You can say tell me a space fact, or, you can say exit... What can I help you with?"
        var reprompt = "What can I help you with?"
        this.emit(':ask', speechOutput, reprompt)
    },
    'AMAZON.CancelIntent': function () {
        this.emit(':tell', 'Goodbye!')
    },
    'AMAZON.StopIntent': function () {
        this.emit(':tell', 'Goodbye!')
    }
}

// Function to join a list of strings. You can customise the penultimate separator.
function naturalJoin(arr, penSep) {
    if (!penSep) {penSep = ' and '}
    const str = arr.slice(0, -1).join(', ') + penSep + arr.slice(-1)
    return str
}


text:
import { JSONPBackend } from './backends/jsonp_backend';
import { CookieXSRFStrategy, XHRBackend } from './backends/xhr_backend';
import { RequestOptions } from './base_request_options';
import { Http, Jsonp } from './http';
export declare function _createDefaultCookieXSRFStrategy(): CookieXSRFStrategy;
export declare function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions): Http;
export declare function jsonpFactory(jsonpBackend: JSONPBackend, requestOptions: RequestOptions): Jsonp;
/**
 * The module that includes http's providers
 *
 * @experimental
 */
export declare class HttpModule {
}
/**
 * The module that includes jsonp's providers
 *
 * @experimental
 */
export declare class JsonpModule {
}


text:
#pragma warning disable 1591

namespace sapHowmuch.Base
{
	public static class sapHowmuchConstants
	{
		public const string SapUiAppName = "SAP Business One.exe";
		public const string SapUiDebugConnectionString = "0030002C0030002C00530041005000420044005F00440061007400650076002C0050004C006F006D0056004900490056";
		public const string SapTempAddonIdentifier = "5645523035496D706C656D656E746174696F6E3A5330343134333233313438D97E42D4155C03AF691C13952E1B7EA4BA9FE8CC";
		public const string SettingTableName = "SHM_SETTING";
		public const string SettingTableDescription = "sapHowmuch Addon setting table";
		public const string SettingFieldName = "SettingValue";
		public const string SettingFieldDescription = "Setting Value";

		#region menu attribute constants

		public const string MenuFormTypeAttr = "FormType";
		public const string MenuUniqueIdAttr = "UniqueID";
		public const string MenuFatherUIDAttr = "FatherUID";
		public const string MenuPositionAttr = "Position";
		public const string MenuTitleAttr = "String";
		public const string MenuTypeAttr = "Type";
		public const string MenuThreadedActionAttr = "ThreadedAction";
		public const string MenuImageAttr = "Image";

		#endregion menu attribute constants

		#region Change Tracker constants

		public const string CT_UdtName = "SHM_CHANGETRACKER";
		public const string CT_UdfKey = "SHM_CT_Key";
		public const string CT_UdfObj = "SHM_CT_Obj";

		#endregion Change Tracker constants
	}
}


text:
#include <cwf/cppwebapplication.h>
#include <model/usermodel.h>

class BmiController : public CWF::Controller
{
public:
    void doGet(CWF::Request &request, CWF::Response &response) const override
    {
        request.getRequestDispatcher("/pages/bmi.html").forward(request, response);
    }

    void doPost(CWF::Request &request, CWF::Response &response) const override
    {
        UserModel model;
        request.fillQObject(&model);
        request.addAttribute("model", &model);
        request.getRequestDispatcher("/pages/bmiresults.view").forward(request, response);
    }
};

int main(int argc, char *argv[])
{
    CWF::CppWebApplication server(argc, argv, "/home/herik/CPPWebFramework/examples/FillObjectBMI/server/");
    server.addController<BmiController>("/bmi");
    return server.start();
}


text:
package de.knoobie.vaadin.addons.bootstrap.formgroup.single;

import com.vaadin.ui.PasswordField;

/**
 * Creates a FormGroup with a field of type {@link com.vaadin.ui.PasswordField} and
 * a value of type {@link java.lang.String}.
 *
 * @author Knoobie
 * @see de.knoobie.vaadin.addons.bootstrap.formgroup.FormGroup
 * @since 0.1
 */
public class PasswordFieldGroup extends AbstractSingleValueFormGroup<PasswordFieldGroup, String, PasswordField> {

    /**
     * Constructs an empty PasswordField with no caption.
     *
     * @since 0.1
     */
    // Copied from Vaadin Framework
    public PasswordFieldGroup() {
        this(new PasswordField());
    }

    /**
     * Constructs an empty PasswordField with given caption.
     *
     * @param caption the caption String for the field.
     * @since 0.1
     */
    // Copied from Vaadin Framework
    public PasswordFieldGroup(String caption) {
        this(new PasswordField(caption));
    }

    /**
     * Constructs a new PasswordField with the given caption and
     * initial text contents.
     *
     * @param caption the caption String for the field.
     * @param value   the initial text content of the field, not {@code null}
     * @since 0.1
     */
    // Copied from Vaadin Framework
    public PasswordFieldGroup(String caption, String value) {
        this(new PasswordField(caption, value));
    }

    /**
     * Uses the given PasswordField as base for the component.
     *
     * @param field the PasswordField used in the component, not {@code null}
     * @since 0.1
     */
    public PasswordFieldGroup(PasswordField field) {
        super(field);
    }

    // Javadoc see FormGroup
    @Override
    protected PasswordFieldGroup getThis() {
        return this;
    }
}


text:
define({
  "_widgetLabel": "Übersichtskarte"
});


text:
[![Join the chat at https://gitter.im/JasperFx/Marten](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/JasperFx/Marten?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Windows Build Status](https://img.shields.io/teamcity/http/build.fubu-project.org/s/marten_master.svg?label=TeamCity&style=flat)](http://build.fubu-project.org/project.html?projectId=Marten&tab=projectOverview&guest=1)
[![Nuget Package](https://img.shields.io/nuget/v/Marten.svg?style=flat)](https://www.nuget.org/packages/Marten/)

Hey, we're just getting started, but there'll be stuff here soon. Check the issue list as quasi-roadmap and feel free to jump into the Gitter room linked above.
See this blog post http://jeremydmiller.com/2015/10/21/postgresql-as-a-document-db-for-net-development/ for more information

## Working with the Code

Like I said, it's way, way early and this should get smoother later. For now, you'll need to have access to a Postgresql **9.5** server and a database. After cloning the code, put a file named `connection.txt` at `src/Marten.Testing` that just needs to contain the connection string to the Postgresql database you want to use as a testbed. See the [Npgsql documentation](http://www.npgsql.org/doc/connection-string-parameters.html) for more information about postgresql connection strings.

You will also need to enable the PLV8 extension inside of Postgresql for running Javascript stored procedures for the nascent projection support. See
[this link](http://www.postgresonline.com/journal/archives/360-PLV8-binaries-for-PostgreSQL-9.5-windows-both-32-bit-and-64-bit.html) for pre-built binaries for PLV8 running on Windows. Just drop the folder structure from that download into your main Postgresql installation folder (`c:\program files\postgresql\9.5` on my box). Once the binaries are copied in, run the command `CREATE EXTENSION PLV8;` in your Postgresql database.
If you have any trouble with PLV8, please feel free to ask for help in the Gitter room.

Once you have the codebase and the connection.txt file, either:

* Run the rake script
* From a command line at the root of the codebase, run `paket restore` to fetch all the nuget dependencies

From there, open Visual Studio.Net or whatever editor you prefer and go to town.

## Tooling

We're using [xUnit](http://xunit.github.io/) and [Shouldly](https://github.com/shouldly/shouldly) for unit testing and [paket](https://fsprojects.github.io/Paket/) for improved Nuget workflow. We're temporarily using rake for build automation, but it's not mandatory for development.

## Mocha Specs

To run the mocha tests on the little bit of custom Javascript for Marten, you will also need some version of Node.js that at least supports arrow function
syntax (I'm using Node.js 4.*). Use `rake mocha` or `npm install` once, then `npm run test`. There is also `npm run tdd` to run the mocha specifications
in a watched mode with growl turned on.

## Storyteller Specs

We're also using [Storyteller](http://storyteller.github.io) for some of the very data intensive automated tests. To open the Storyteller editor, use the command `rake open_st` from the command line or `rake storyeller` to run the Storyteller specs. If you don't want to use rake, you can launch the
Storyteller editor *after compiling the solution* by the command `packages\storyteller\tools\st.exe open src/Marten.Testing`.

## Documentation

The documentation website for Marten is authored with [Storyteller's documentation generation feature](http://storyteller.github.io/documentation/docs/). The actual content is the markdown files in the `/documentation` directory directly under the project root. To quickly run the documentation website locally with auto-refresh (it's not perfect since it does rely on .Net's FileSystemWatcher), either use the rake task `rake docs` or there is a new batch script named `run-docs.cmd`.

If you wish to insert code samples to a documentation page from the tests,
you'll need to wrap the code you wish to insert with
`// SAMPLE: name-of-sample` and `// ENDSAMPLE`.
Then to insert that code to the documentation, add `<[sample:name-of-sample]>`.

The content is kept in the main Marten GitHub repository, but the published documentation is done by running the `publish-docs.cmd` command and pushing the generated static HTML to the gh-pages branch of Marten.


text:
<?php

namespace Touki\FTP\Tests;

use Touki\FTP\FTPFactory;
use Touki\FTP\FTPWrapper;
use Touki\FTP\DeleterVoter;
use Touki\FTP\CreatorVoter;
use Touki\FTP\DownloaderVoter;
use Touki\FTP\UploaderVoter;
use Touki\FTP\Manager\FTPFilesystemManager;
use Touki\FTP\WindowsFilesystemFactory;

/**
 * FTP Factory Test Case
 *
 * @author Touki <g.vincendon@vithemis.com>
 */
class FTPFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $mock = $this->getMock('Touki\FTP\ConnectionInterface');
        $mock
            ->expects($this->any())
            ->method('isConnected')
            ->will($this->returnValue(true))
        ;

        $this->connection = $mock;
        $this->factory    = new FTPFactory;
    }

    public function testNoConfigurationGiven()
    {
        $ftp = $this->factory->build($this->connection);

        $this->assertInstanceOf('Touki\FTP\FTP', $ftp);
        $this->assertInstanceOf('Touki\FTP\FTPWrapper', $this->factory->getWrapper());
        $this->assertSame($this->connection, $this->factory->getWrapper()->getConnection());
        $this->assertInstanceOf('Touki\FTP\Manager\FTPFilesystemManager', $this->factory->getManager());
        $this->assertInstanceOf('Touki\FTP\CreatorVoter', $this->factory->getCreatorVoter());
        $this->assertInstanceOf('Touki\FTP\DeleterVoter', $this->factory->getDeleterVoter());
        $this->assertInstanceOf('Touki\FTP\DownloaderVoter', $this->factory->getDownloaderVoter());
        $this->assertInstanceOf('Touki\FTP\UploaderVoter', $this->factory->getUploaderVoter());
    }

    public function testFTPWrapperGiven()
    {
        $wrapper = new FTPWrapper($this->connection);
        $this->factory->setWrapper($wrapper);

        $ftp = $this->factory->build($this->connection);

        $this->assertInstanceOf('Touki\FTP\FTP', $ftp);
        $this->assertSame($wrapper, $this->factory->getWrapper());
        $this->assertInstanceOf('Touki\FTP\Manager\FTPFilesystemManager', $this->factory->getManager());
        $this->assertInstanceOf('Touki\FTP\CreatorVoter', $this->factory->getCreatorVoter());
        $this->assertInstanceOf('Touki\FTP\DeleterVoter', $this->factory->getDeleterVoter());
        $this->assertInstanceOf('Touki\FTP\DownloaderVoter', $this->factory->getDownloaderVoter());
        $this->assertInstanceOf('Touki\FTP\UploaderVoter', $this->factory->getUploaderVoter());
    }

    public function testManagerGiven()
    {
        $manager = new FTPFilesystemManager(new FTPWrapper($this->connection), new WindowsFilesystemFactory);
        $this->factory->setManager($manager);

        $ftp = $this->factory->build($this->connection);

        $this->assertInstanceOf('Touki\FTP\FTP', $ftp);
        $this->assertInstanceOf('Touki\FTP\FTPWrapper', $this->factory->getWrapper());
        $this->assertSame($this->connection, $this->factory->getWrapper()->getConnection());
        $this->assertSame($manager, $this->factory->getManager());
        $this->assertInstanceOf('Touki\FTP\CreatorVoter', $this->factory->getCreatorVoter());
        $this->assertInstanceOf('Touki\FTP\DeleterVoter', $this->factory->getDeleterVoter());
        $this->assertInstanceOf('Touki\FTP\DownloaderVoter', $this->factory->getDownloaderVoter());
        $this->assertInstanceOf('Touki\FTP\UploaderVoter', $this->factory->getUploaderVoter());
    }

    public function testCreatorVoterGiven()
    {
        $crVoter = new CreatorVoter;
        $this->factory->setCreatorVoter($crVoter);
        $ftp = $this->factory->build($this->connection);

        $this->assertInstanceOf('Touki\FTP\FTP', $ftp);
        $this->assertInstanceOf('Touki\FTP\FTPWrapper', $this->factory->getWrapper());
        $this->assertSame($this->connection, $this->factory->getWrapper()->getConnection());
        $this->assertInstanceOf('Touki\FTP\Manager\FTPFilesystemManager', $this->factory->getManager());
        $this->assertSame($crVoter, $this->factory->getCreatorVoter());
        $this->assertInstanceOf('Touki\FTP\DeleterVoter', $this->factory->getDeleterVoter());
        $this->assertInstanceOf('Touki\FTP\DownloaderVoter', $this->factory->getDownloaderVoter());
        $this->assertInstanceOf('Touki\FTP\UploaderVoter', $this->factory->getUploaderVoter());
    }

    public function testDeleterVoterGiven()
    {
        $deVoter = new DeleterVoter;
        $this->factory->setDeleterVoter($deVoter);
        $ftp = $this->factory->build($this->connection);

        $this->assertInstanceOf('Touki\FTP\FTP', $ftp);
        $this->assertInstanceOf('Touki\FTP\FTPWrapper', $this->factory->getWrapper());
        $this->assertSame($this->connection, $this->factory->getWrapper()->getConnection());
        $this->assertInstanceOf('Touki\FTP\Manager\FTPFilesystemManager', $this->factory->getManager());
        $this->assertInstanceOf('Touki\FTP\CreatorVoter', $this->factory->getCreatorVoter());
        $this->assertSame($deVoter, $this->factory->getDeleterVoter());
        $this->assertInstanceOf('Touki\FTP\DownloaderVoter', $this->factory->getDownloaderVoter());
        $this->assertInstanceOf('Touki\FTP\UploaderVoter', $this->factory->getUploaderVoter());
    }

    public function testDownloaderVoterGiven()
    {
        $dlVoter = new DownloaderVoter;
        $this->factory->setDownloaderVoter($dlVoter);
        $ftp = $this->factory->build($this->connection);

        $this->assertInstanceOf('Touki\FTP\FTP', $ftp);
        $this->assertInstanceOf('Touki\FTP\FTPWrapper', $this->factory->getWrapper());
        $this->assertSame($this->connection, $this->factory->getWrapper()->getConnection());
        $this->assertInstanceOf('Touki\FTP\Manager\FTPFilesystemManager', $this->factory->getManager());
        $this->assertInstanceOf('Touki\FTP\CreatorVoter', $this->factory->getCreatorVoter());
        $this->assertInstanceOf('Touki\FTP\DeleterVoter', $this->factory->getDeleterVoter());
        $this->assertSame($dlVoter, $this->factory->getDownloaderVoter());
        $this->assertInstanceOf('Touki\FTP\UploaderVoter', $this->factory->getUploaderVoter());
    }

    public function testUploaderVoterGiven()
    {
        $ulVoter = new UploaderVoter;
        $this->factory->setUploaderVoter($ulVoter);
        $ftp = $this->factory->build($this->connection);

        $this->assertInstanceOf('Touki\FTP\FTP', $ftp);
        $this->assertInstanceOf('Touki\FTP\FTPWrapper', $this->factory->getWrapper());
        $this->assertSame($this->connection, $this->factory->getWrapper()->getConnection());
        $this->assertInstanceOf('Touki\FTP\Manager\FTPFilesystemManager', $this->factory->getManager());
        $this->assertInstanceOf('Touki\FTP\CreatorVoter', $this->factory->getCreatorVoter());
        $this->assertInstanceOf('Touki\FTP\DeleterVoter', $this->factory->getDeleterVoter());
        $this->assertInstanceOf('Touki\FTP\DownloaderVoter', $this->factory->getDownloaderVoter());
        $this->assertSame($ulVoter, $this->factory->getUploaderVoter());
    }

    public function testFilesystemFactoryGiven()
    {
        $fsFactory = new WindowsFilesystemFactory;
        $this->factory->setFilesystemFactory($fsFactory);
        $ftp = $this->factory->build($this->connection);

        $this->assertInstanceOf('Touki\FTP\FTP', $ftp);
        $this->assertInstanceOf('Touki\FTP\FTPWrapper', $this->factory->getWrapper());
        $this->assertSame($this->connection, $this->factory->getWrapper()->getConnection());
        $this->assertInstanceOf('Touki\FTP\Manager\FTPFilesystemManager', $this->factory->getManager());
        $this->assertInstanceOf('Touki\FTP\CreatorVoter', $this->factory->getCreatorVoter());
        $this->assertInstanceOf('Touki\FTP\DeleterVoter', $this->factory->getDeleterVoter());
        $this->assertInstanceOf('Touki\FTP\DownloaderVoter', $this->factory->getDownloaderVoter());
        $this->assertInstanceOf('Touki\FTP\UploaderVoter', $this->factory->getUploaderVoter());
    }
}


text:
import {
	useMutableCallback,
	useLocalStorage,
	useDebouncedValue,
} from '@rocket.chat/fuselage-hooks';
import React, { useCallback, useMemo, useState } from 'react';

import { roomTypes } from '../../../../../app/utils/client';
import { usePermission } from '../../../../contexts/AuthorizationContext';
import { useSetModal } from '../../../../contexts/ModalContext';
import { useRecordList } from '../../../../hooks/lists/useRecordList';
import { AsyncStatePhase } from '../../../../lib/asyncState';
import CreateChannelWithData from '../../../../sidebar/header/CreateChannelWithData';
import RoomInfo from '../../../room/contextualBar/Info';
import { useTabBarClose } from '../../../room/providers/ToolboxProvider';
import AddExistingModal from './AddExistingModal';
import BaseTeamsChannels from './BaseTeamsChannels';
import { useTeamsChannelList } from './hooks/useTeamsChannelList';

const useReactModal = (Component, props) => {
	const setModal = useSetModal();

	return useMutableCallback((e) => {
		e.preventDefault();

		const handleClose = () => {
			setModal(null);
		};

		setModal(() => <Component onClose={handleClose} {...props} />);
	});
};

const TeamsChannels = ({ teamId, rid }) => {
	const [state, setState] = useState({});
	const onClickClose = useTabBarClose();

	const [type, setType] = useLocalStorage('channels-list-type', 'all');
	const [text, setText] = useState('');

	const debouncedText = useDebouncedValue(text, 800);

	const { teamsChannelList, loadMoreItems, reload } = useTeamsChannelList(
		useMemo(() => ({ teamId, text: debouncedText, type }), [teamId, debouncedText, type]),
	);

	const { phase, items, itemCount: total } = useRecordList(teamsChannelList);

	const handleTextChange = useCallback((event) => {
		setText(event.currentTarget.value);
	}, []);

	const canAddExistingTeam = usePermission('add-team-channel', rid);
	const addExisting = useReactModal(AddExistingModal, { teamId, reload });
	const createNew = useReactModal(CreateChannelWithData, { teamId, reload });

	const goToRoom = useCallback((room) => roomTypes.openRouteLink(room.t, room), []);
	const handleBack = useCallback(() => setState({}), [setState]);
	const viewRoom = useMutableCallback((room) => {
		goToRoom(room);
	});

	if (state.tab === 'RoomInfo') {
		return (
			<RoomInfo
				rid={state.rid}
				onClickClose={onClickClose}
				onClickBack={handleBack}
				onEnterRoom={goToRoom}
				resetState={setState}
			/>
		);
	}

	return (
		<BaseTeamsChannels
			loading={phase === AsyncStatePhase.LOADING}
			type={type}
			text={text}
			setType={setType}
			setText={handleTextChange}
			channels={items}
			total={total}
			onClickClose={onClickClose}
			onClickAddExisting={canAddExistingTeam && addExisting}
			onClickCreateNew={canAddExistingTeam && createNew}
			onClickView={viewRoom}
			loadMoreItems={loadMoreItems}
			reload={reload}
		/>
	);
};

export default TeamsChannels;


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<dom-module id="simple-sequencer">
  <template>
    <style>
      :host {
        display: block;
      }
    </style>

    <div class="matrix-list">
      <element-header label="Sequencer" removable="{{removable}}"></element-header>

      <sequencer-matrix
        class="matrix"
        number-of-steps="16"
        number-of-rows="12"
        clip-manager="{{clipManager}}"
        clip-label="Sequencer Roll">
      </sequencer-matrix>

      <sequencer-matrix
        class="matrix"
        number-of-steps="16"
        number-of-rows="12"
        clip-manager="{{clipManager}}"
        clip-label="Sequencer Roll">
      </sequencer-matrix>

    </div>

  </template>

  <script>
    (function() {
      'use strict';

      class SimpleSequencer {

        beforeRegister() {
          this.is = 'simple-sequencer';

          this.properties = {
            instrumentSet: {
              type: Object
            },
            removable: {
              type: Object
            }
          };

          this.listeners = {};

        }

        ready() {}
        attached() {
          this.isReset = true;
          this.schedulable = buildSchedulable.call(this);
          app.scheduler.register(this.schedulable);

          let matrixNodeList = this.getElementsByClassName('matrix');
          this.matrixList = Array.prototype.slice.call(matrixNodeList);
          this.activeIndex;

          this.clipManager = buildClipManager(this.matrixList, (activeIndex) => {
            this.activeIndex = activeIndex;
            this.isReset = true;
          });

          setTimeout(() => {
            this.matrixList[0].setAsActive();
          }, 0);
        }

        detached() {
          app.scheduler.deregister(this.schedulable);
        }
        attributeChanged() {}
      }
      Polymer(SimpleSequencer);

      function buildSchedulable () {
        return {
          processTick: (beatNumber, time) => {
            let columnData = this.matrixList[this.activeIndex].getColumnValueList(beatNumber);
            columnData.forEach( (matrixElement, index) => {
              let note = index - 6;
              if (matrixElement) {
                this.instrumentSet.forEach((instrument) => {
                  instrument.play(note, time);
                });
              }
            });
          },
          render: (beatNumber, lastBeatNumber) => {
            this.matrixList[this.activeIndex].render(beatNumber, lastBeatNumber, this.isReset);

            if (this.isReset) {
              this.isReset = false;
            }
          },
          start: () => {
            this.isReset = true;
          },
          stop: () => {
            this.matrixList[this.activeIndex].stop();
          }
        }
      }

      function buildClipManager (matrixList, setActiveIndex) {
        return {
          queueActive: (matrixElement) => {
            let activeIndex = matrixList.indexOf(matrixElement);
            setActiveIndex(activeIndex);
            matrixList.forEach( (matrix, index) => {
              if (index !== activeIndex) {
                matrix.setAsInactive();
                matrix.stop();
              }
            });
          },
          onMatrixChange: (matrixElement, row, column, value) => {}
        };
      }

    })();
  </script>

</dom-module>


text:
layout:		property
title:		"notional_amount"
schemas:	[derivative, derivative_cash_flow, loan, security]
---

# notional_amount

---

The notional amount is the face value of an instrument and indicates how much of a particular security an investor has. This is to be contrasted to the market value, which indicates how much that security could be sold for in the market.

### Regulatory Context

[EU Regulation][EUR] with regard to regulatory technical standards on indirect clearing arrangements, the clearing obligation, the public register, access to a trading venue, non-financial counterparties, and risk mitigation techniques for OTC derivatives contracts not cleared by a CCP:

"To further mitigate risks, portfolio reconciliation enables each counterparty to undertake a comprehensive review of a portfolio of transactions as seen by its counterparty in order to promptly identify any misunderstandings of key transaction terms. Such terms should include the valuation of each transaction and may also include other relevant details such as the effective date, the scheduled maturity date, any payment or settlement dates, **the notional value of the contract** and currency of the transaction, the underlying instrument, the position of the counterparties, the business day convention and any relevant fixed or floating rates of the OTC derivative contract."

[EUR]: http://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX%3A32013R0149


text:
'''
Created on 26 May 2015

@author: will
'''
import time
import logging
import calendar

class TimeoutCalculator(object):
    '''
    classdocs
    '''

    def __init__(self, timeout):
        self.timeout = timeout
        '''
        Constructor
        '''

    def start(self):
        self.startTime = calendar.timegm(time.gmtime())

    def reset(self):
        self.start()

    def amITimedOut(self):
        endTime = (self.startTime + self.timeout)
        presentTime = calendar.timegm(time.gmtime())
        logging.debug("End time calculated as:" + str(endTime))
        if presentTime > endTime:
            logging.info("Timeout Calculator: Timed out")
            return True
        else:
            logging.info("Timeout Calculator: Not Timed out")
            return False


text:
<?php

/**
 * ##MODULE_NAME## module configuration.
 *
 * @package    ##PROJECT_NAME##
 * @subpackage ##MODULE_NAME##
 * @author     ##AUTHOR_NAME##
 * @version    SVN: $Id: configuration.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ##MODULE_NAME##GeneratorConfiguration extends Base##UC_MODULE_NAME##GeneratorConfiguration
{
  public function getPagerMaxPerPage()
  {
    $user = sfContext::getInstance()->getUser();
    return $user->getAttribute('max_per_page', 50);
  }

  public function getFormActions()
  {
    return array(  '_delete' => NULL,  '_list' => NULL,  '_save' => NULL,  '_save_and_add' => NULL,  '_save_and_list' => NULL,);
  }

  public function getNewActions()
  {
    return array();
  }

  public function getEditActions()
  {
    return array(  '_delete' => NULL,  '_list' => NULL,  '_save' => NULL,  '_save_and_add' => NULL,  '_save_and_list' => NULL,);
  }

}


text:
import React from "react";
class Header extends React.Component {
    render() {
        return (

Front-end Test

        )
    }
}

export default Header;


text:
 /* ==================================================================================
-- CONFIGURATION PROTOTYPE
-- =============================================================================== */
define(["jquery"], function($) {

	var Configuration = function() {
		var self = this;

		self.swipeDistance	= 4;			// DIVIDE WIDTH BY TO DETERMINE CAPTURE MOVE
		self.slideSpeed		= 1.0;			// MULTIPLIER FOR FASTER OR SLOWER
		self.audioEnabled	= false;		// SIMPLY, IS IT ENABLED
		self.slightBounce	= false;		// ENABLE/DISABLE BOUNCE AT END OF CARD MOVEMENT

		// USED TO TRACK MODAL OPEN/CLOSED TO ENABLE/DISABLE NAVIGATION HANDLING
		self.Modal			= false;
	};

	return Configuration;
});


text:
As the very long repo title indicates, this is a boilerplate repository that
includes the following:

- ES6-to-ES5 transpilation using [Babel](https://github.com/babel/babel)
- Uni-directional data-flow architecture using [Reflux](https://github.com/spoike/refluxjs)

## Getting started

1. Clone this project
2. Install dependencies:

    ```shell
    $ npm install
    ```

3. Start the webpack watcher (it builds the `index.ios.js` file expected by React Native)
4. Open `ReactNativeEs6Reflux.xcodeproj` in XCode and run the project - it should look like this:

    <img alt="iOS Simulator running this boilerplate" src="http://i.imgur.com/OKELxXP.png" height="50%" width="50%">

## Javascript file structure

```
  - src/
    stores/ -  Reflux stores
      color_store.js - Example store implementation
    components/ - React components
      app.jsx - Top-level app component

    action.js - Reflux action definitions
    styles.js - StyleSheet definition(s)
    main.js   - Application bootstrap with react-native, transpiler entry-point
```

## Included in the example:

- A simple top-level `App` component with example styles (in `src/styles.js`)
- An example interaction using `TouchableOpacity`, and an example Reflux action (defined in `src/actions.js`)
- An example `AppMessageStore` Reflux store, which handles setting the random message when the React logo is tapped.

## Author

This boilerplate was created by [Filipe Dobreira](https://github.com/filp). It includes auto-generated code (through `react-native init`), and code by [Roman Liutikov](https://github.com/roman01la) (namely the webpack configuration).


text:
require 'pattern_deployer'

class Container < ActiveRecord::Base

  include NodesHelper
  include PatternDeployer::Errors

  belongs_to :topology, :autosave => true, :inverse_of => :containers
  belongs_to :owner, :class_name => "User", :foreign_key => "user_id", :inverse_of => :containers
  has_many :nodes, :dependent => :destroy, :as => :parent

  attr_accessible :container_id, :num_of_copies, :owner, :id, :topology

  validates :container_id, :presence => true
  validates :num_of_copies, :numericality => { :only_integer => true, :greater_than => 0 }
  validates_presence_of :topology, :owner
  validate :container_id_unique_within_topology
  validate :container_mutable

  after_initialize :set_default_values
  before_destroy :container_destroyable

  def update_container_attributes(container_element)
    self.container_id = container_element["id"]
    self.num_of_copies = container_element["num_of_copies"] || 1
    container_element.each_element do |element|
      if element.name == "node"
        node = create_node_scaffold(element, self, self.owner)
        node.update_node_attributes(element)
      else
        msg = "Only element of name 'node' can be child element of container. Invalid element: #{element}."
        fail PatternValidationError, msg
      end
    end

    self.save!
  end

  def update_container_connections(container_element)
    container_element.each_element do |element|
      if element.name == "node"
        node = self.nodes.find_by_node_id!(element["id"])
        node.update_node_connections(element)
      end
    end
  end

  def rename(name)
    self.container_id = name
    self.save!
  end

  def get_topology
    self.topology || Topology.find(topology_id)
  end

  protected

  def set_default_values
    self.num_of_copies ||= 1
  end

  def container_id_unique_within_topology
    if Container.where("topology_id = ? AND container_id = ? AND id <> ?", self.topology_id, self.container_id, self.id).first
      errors.add(:container_id, "have already been taken")
    end
  end

  def container_mutable
    if get_topology.locked?
      errors.add(:container_id, "cannot be modified. Please make sure its topology is not deployed or deploying")
    end
  end

  def container_destroyable
    if get_topology.locked?
      msg = "Container #{container_id} cannot be destroyed. Please make sure its topology is not deployed or deploying."
      fail InvalidOperationError, msg
    end
  end

end


text:
FROM java:openjdk-8u72-jdk

MAINTAINER itzg

ENV CASSANDRA_VERSION 2.2.7

RUN wget -qO /tmp/apache-cassandra.tgz http://mirrors.ibiblio.org/apache/cassandra/$CASSANDRA_VERSION/apache-cassandra-$CASSANDRA_VERSION-bin.tar.gz
RUN tar -C /opt -zxf /tmp/apache-cassandra.tgz && \
  rm /tmp/apache-cassandra.tgz

RUN mv /opt/apache-cassandra-$CASSANDRA_VERSION /opt/cassandra
ENV CASSANDRA_HOME /opt/cassandra
ENV CASSANDRA_CONF /conf
ENV CASSANDRA_DATA /data
WORKDIR $CASSANDRA_HOME

RUN ln -s $CASSANDRA_HOME/bin/* /usr/local/bin
VOLUME ["/data","/conf"]

EXPOSE 9042 9160 7000 7001

ADD cassandra.in.sh $CASSANDRA_HOME/cassandra.in.sh
RUN mv $CASSANDRA_HOME/bin/cassandra.in.sh $CASSANDRA_HOME/bin/orig.cassandra.in.sh

CMD ["/opt/cassandra/bin/cassandra", "-f"]


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-capable" content="yes" />
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-title" content="Storm Remote">

	<link rel="apple-touch-icon" href="/app/assets/icons/ios.png">

	<title>Cuevana Storm Remote</title>
	<link rel="stylesheet" href="/app/assets/remote/css/remote.css">

CONNECTION_LOST

CONNECTION_LOST_MSG

			RECONNECT

SEARCH

				<input type="text" id="q" placeholder-translate="SEARCH_PLACEHOLDER" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">

			OK

SUBTITLES

			OK

				Remote

				EXIT_VIDEO