text:
package array.n_sum;

import java.util.*;

public class Q15ThreeSum {

    //TAG: Facebook
    //TAG: Microsoft
    //TAG: Amazon
    //TAG: Apple
    //TAG: array
    //TAG: n_sum
    //Difficulty: Medium

    /**
     * 15. 3Sum
     * Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

     Note: The solution set must not contain duplicate triplets.

     For example, given array S = [-1, 0, 1, 2, -1, -4],

     A solution set is:
     [
     [-1, 0, 1],
     [-1, -1, 2]
     ]
     */

    /*
     * Solution:
     * 1. Sort the array in ascending order, need to filter the duplicate number, easier to do this in sorted array
     * 2. set left index i, right index j and middle index m, outer loop of i start from 0 to last third number
     *      1. for each outer loop, start m = i + 1, j = len - 1, to find triplet number equal to 0, each step skip duplicated elements
     * 3. skip duplicated nums[i] and repeat step 2, when find triplet add to list
     *
     * Time: O(nlogn(sort) + n^2) = O(n^2) no matter how middle and right index move, they iterative all numbers right of left index once, it's O(n - 1) + O(n - 2) + ... + O(1) = O(n^2)
     * Space: O(n/3) = O(n) if all numbers could combine a triplet
     *
     */

    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length < 3) return res;
        Arrays.sort(nums);
        int i = 0;
        while (i < nums.length - 2) {
            int m = i + 1, j = nums.length - 1;
            //Define a local nums[i] to compare to skip all duplicated nums[i]
            int temp1 = nums[i];
            //If left index number is larger than 0, due to sorted array, no need to compare next triplets
            if (temp1 > 0) break;
            while (m < j) {
                int temp2 = nums[m], temp3 = nums[j];
                int curSum = temp1 + temp2 + temp3;
                if (curSum < 0) while (m < j && nums[m] == temp2) m++;
                else if (curSum > 0) while (j > m && nums[j] == temp3) j--;
                else {
                    res.add(Arrays.asList(nums[i], nums[m], nums[j]));
                    //If equal to 0, add current triplet and skip duplicated m and j to find next pair of m and j depends on the same i
                    //Be aware of if use nums[m] == nums[m + 1], if use this, at last the m is at the last duplicated m number, which need extra m++ and j-- to skip last duplicated number
                    while (m < j && nums[m] == temp2) m++;
                    while (j > m && nums[j] == temp3) j--;
                }
            }
            while (i < nums.length - 2 && nums[i] == temp1) i++;
        }
        return res;
    }

}


text:
namespace NativeCode.Mobile.Core.Presentation
{
    using NativeCode.Core.Dependencies;

    public abstract class NavigableViewModel : ViewModel
    {
        private readonly IViewModelNavigatorProvider provider;

        protected NavigableViewModel()
        {
            this.provider = DependencyResolver.Current.Resolve<IViewModelNavigatorProvider>();
        }

        protected IViewModelNavigator Navigator
        {
            get { return this.provider.GetCurrentNavigator(); }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/clouddms/v1/clouddms.proto

package com.google.cloud.clouddms.v1;

public interface DeleteMigrationJobRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.clouddms.v1.DeleteMigrationJobRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. Name of the migration job resource to delete.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Required. Name of the migration job resource to delete.
   *

   *
   *
   * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();

  /**
   *
   *
   *

   * A unique id used to identify the request. If the server receives two
   * requests with the same id, then the second request will be ignored.
   * It is recommended to always set this value to a UUID.
   * The id must contain only letters (a-z, A-Z), numbers (0-9), underscores
   * (_), and hyphens (-). The maximum length is 40 characters.
   *

   *
   * string request_id = 2;
   *
   * @return The requestId.
   */
  java.lang.String getRequestId();
  /**
   *
   *
   *

   * A unique id used to identify the request. If the server receives two
   * requests with the same id, then the second request will be ignored.
   * It is recommended to always set this value to a UUID.
   * The id must contain only letters (a-z, A-Z), numbers (0-9), underscores
   * (_), and hyphens (-). The maximum length is 40 characters.
   *

   *
   * string request_id = 2;
   *
   * @return The bytes for requestId.
   */
  com.google.protobuf.ByteString getRequestIdBytes();

  /**
   *
   *
   *

   * The destination CloudSQL connection profile is always deleted with the
   * migration job. In case of force delete, the destination CloudSQL replica
   * database is also deleted.
   *

   *
   * bool force = 3;
   *
   * @return The force.
   */
  boolean getForce();
}


text:
package eu.hurion.vaadin.heroku.it;

import com.vaadin.event.FieldEvents;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.*;

public class SessionTestApplication extends UI {

    public static final String BUTTON_CAPTION = "Click me";
    public static final String BUTTON_ID = "hello-button";
    public static final String NAME_LABEL = "What is your name?";
    public static final String NAME_ID = "name";
    public static final String NAME = "name-session";

    @Override
    protected void init(final VaadinRequest vaadinRequest) {
        setContent(buildContent());
    }

    private Layout buildContent() {
        final FormLayout formLayout = new FormLayout();
        formLayout.setSpacing(true);
        formLayout.setSizeUndefined();

        final TextField nameInput = new TextField();
        nameInput.setCaption(NAME_LABEL);
        nameInput.setId(NAME_ID);
        nameInput.setImmediate(true);
        final VaadinSession session = getUI().getSession();
        final String name = (String) session.getAttribute(NAME);
        if (name != null){
            nameInput.setValue(name);
        }
        nameInput.addTextChangeListener(new FieldEvents.TextChangeListener() {
            @Override
            public void textChange(final FieldEvents.TextChangeEvent event) {
                final String text = event.getText();
                session.setAttribute(NAME, text);
            }
        });
        formLayout.addComponent(nameInput);

        final Button showButton = new Button(BUTTON_CAPTION, new Button.ClickListener() {
            @Override
            public void buttonClick(final Button.ClickEvent clickEvent) {
                final String greeting = "Hello " + nameInput.getValue() + " !";
                Notification.show(greeting);
            }
        });
        showButton.setId(BUTTON_ID);
        formLayout.addComponent(showButton);
        final VerticalLayout vl = new VerticalLayout();
        vl.addComponent(formLayout);
        vl.setComponentAlignment(formLayout, Alignment.MIDDLE_CENTER);
        vl.setSizeFull();
        return vl;
    }

}


text:
import Phaser from 'phaser-ce';

class Rocket extends Phaser.Sprite {
  constructor({ game, x, y, asset }) {
    super(game, x, y, asset);

    this.game = game;
    this.game.physics.enable(this, Phaser.Physics.ARCADE);

    this.anchor.setTo(0.5, 1);

    this.width = this.width * 0.8;
    this.height = this.height * 0.8;

    this.rocketFire = this.game.add.sprite(0, 0, 'rocket-fire');
    this.rocketFire.anchor.setTo(0.5, 0);
    this.rocketFire.visible = false;
    this.addChild(this.rocketFire);

    this.body.collideWorldBounds = true;

    this.isFired = false;
    this.fireTimer = 0;
  }

  update() {
    if (this.isFired) {
      this.body.velocity.y = -500;
      this.body.velocity.x = this.body.velocity.x - 1;
      this.angle = this.angle - 0.1;
    }
  }

  fire() {
    const tween = this.game.add.tween(this).to({
      x: this.x + 5,
    }, 100, Phaser.Easing.Quadratic.InOut, true, 250, 5, true);

    tween.onComplete.add(() => {
      this.rocketFire.visible = true;
      this.isFired = true;
    });
  }
}

export default Rocket;


text:
{-# LANGUAGE FlexibleContexts #-}

module App
    ( runProgram
    ) where

import Control.Monad.Except (runExceptT, throwError)
import Control.Monad.Reader (asks, liftIO, runReaderT)
import qualified Data.Bifunctor as BF
import qualified Data.Bool as B
import qualified Data.Maybe as M
import Types
import Unused.Aliases (termsAndAliases)
import Unused.CLI
       (SearchRunner(..), executeSearch, loadGitContext, renderHeader,
        withRuntime)
import qualified Unused.CLI.Views as V
import Unused.Cache (cached)
import Unused.Grouping (CurrentGrouping(..), groupedResponses)
import Unused.Parser (parseResults)
import Unused.ResponseFilter
       (ignoringPaths, withLikelihoods, withOneOccurrence)
import Unused.ResultsClassifier
       (LanguageConfiguration(..), loadAllConfigurations)
import Unused.TagsSource (loadTagsFromFile, loadTagsFromPipe)
import Unused.TermSearch
       (SearchBackend(..), SearchResults(..), SearchTerm, fromResults)
import Unused.Types (RemovalLikelihood(..), TermMatchSet)

runProgram :: Options -> IO ()
runProgram options =
    withRuntime $ either renderError return =<< runExceptT (runReaderT (runApp run) options)

run :: App ()
run = do
    terms <- termsWithAlternatesFromConfig
    liftIO $ renderHeader terms
    backend <- searchBackend
    results <- withCache . flip (executeSearch backend) terms =<< searchRunner
    printResults =<< retrieveGitContext =<< fmap (`parseResults` results) loadAllConfigs

searchBackend :: AppConfig m => m SearchBackend
searchBackend = asks oSearchBackend

termsWithAlternatesFromConfig :: App [SearchTerm]
termsWithAlternatesFromConfig =
    termsAndAliases <$> (concatMap lcTermAliases <$> loadAllConfigs) <*> calculateTagInput

renderError :: AppError -> IO ()
renderError (TagError e) = V.missingTagsFileError e
renderError (InvalidConfigError e) = V.invalidConfigError e
renderError (CacheError e) = V.fingerprintError e

retrieveGitContext :: TermMatchSet -> App TermMatchSet
retrieveGitContext tms = maybe (return tms) (liftIO . flip loadGitContext tms) =<< numberOfCommits

printResults :: TermMatchSet -> App ()
printResults tms = do
    filters <- optionFilters tms
    grouping <- groupingOptions
    formatter <- resultFormatter
    liftIO $ V.searchResults formatter $ groupedResponses grouping filters

loadAllConfigs :: App [LanguageConfiguration]
loadAllConfigs =
    either throwError return =<< BF.first InvalidConfigError <$> liftIO loadAllConfigurations

calculateTagInput :: App [String]
calculateTagInput =
    either throwError return =<<
    liftIO . fmap (BF.first TagError) . B.bool loadTagsFromFile loadTagsFromPipe =<< readFromStdIn

withCache :: IO SearchResults -> App SearchResults
withCache f = B.bool (liftIO f) (withCache' f) =<< runWithCache
  where
    withCache' :: IO SearchResults -> App SearchResults
    withCache' r =
        either (throwError . CacheError) (return . SearchResults) =<<
        liftIO (cached "term-matches" $ fmap fromResults r)

optionFilters :: AppConfig m => TermMatchSet -> m TermMatchSet
optionFilters tms = foldl (>>=) (pure tms) matchSetFilters
  where
    matchSetFilters = [singleOccurrenceFilter, likelihoodsFilter, ignoredPathsFilter]

singleOccurrenceFilter :: AppConfig m => TermMatchSet -> m TermMatchSet
singleOccurrenceFilter tms = B.bool tms (withOneOccurrence tms) <$> asks oSingleOccurrenceMatches

likelihoodsFilter :: AppConfig m => TermMatchSet -> m TermMatchSet
likelihoodsFilter tms = asks $ withLikelihoods . likelihoods <*> pure tms
  where
    likelihoods options
        | oAllLikelihoods options = [High, Medium, Low]
        | null $ oLikelihoods options = [High]
        | otherwise = oLikelihoods options

ignoredPathsFilter :: AppConfig m => TermMatchSet -> m TermMatchSet
ignoredPathsFilter tms = asks $ ignoringPaths . oIgnoredPaths <*> pure tms

readFromStdIn :: AppConfig m => m Bool
readFromStdIn = asks oFromStdIn

groupingOptions :: AppConfig m => m CurrentGrouping
groupingOptions = asks oGrouping

searchRunner :: AppConfig m => m SearchRunner
searchRunner = asks oSearchRunner

runWithCache :: AppConfig m => m Bool
runWithCache = asks $ not . oWithoutCache

numberOfCommits :: AppConfig m => m (Maybe Int)
numberOfCommits = asks oCommitCount

resultFormatter :: AppConfig m => m V.ResultsFormat
resultFormatter = B.bool V.Column V.List . M.isJust <$> numberOfCommits


text:
package org.jkiss.dbeaver.ext.postgresql.model.data;

import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.ext.postgresql.PostgreConstants;
import org.jkiss.dbeaver.ext.postgresql.PostgreUtils;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreDataSource;
import org.jkiss.dbeaver.ext.postgresql.model.PostgreDataType;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.data.DBDCollection;
import org.jkiss.dbeaver.model.data.DBDDisplayFormat;
import org.jkiss.dbeaver.model.data.DBDValueHandler;
import org.jkiss.dbeaver.model.exec.DBCException;
import org.jkiss.dbeaver.model.exec.DBCSession;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.impl.jdbc.data.JDBCCollection;
import org.jkiss.dbeaver.model.impl.jdbc.data.handlers.JDBCArrayValueHandler;
import org.jkiss.dbeaver.model.sql.SQLUtils;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * PostgreArrayValueHandler
 */
public class PostgreArrayValueHandler extends JDBCArrayValueHandler {
    public static final PostgreArrayValueHandler INSTANCE = new PostgreArrayValueHandler();

    @Override
    protected Object fetchColumnValue(DBCSession session, JDBCResultSet resultSet, DBSTypedObject type, int index) throws DBCException, SQLException {
        return super.fetchColumnValue(session, resultSet, type, index);
    }

    @Override
    public DBDCollection getValueFromObject(@NotNull DBCSession session, @NotNull DBSTypedObject type, Object object, boolean copy) throws DBCException
    {
        if (object != null) {
            String className = object.getClass().getName();
            if (object instanceof String || className.equals(PostgreConstants.PG_OBJECT_CLASS)) {
                final PostgreDataType arrayType = PostgreUtils.findDataType(session, (PostgreDataSource) session.getDataSource(), type);
                if (arrayType == null) {
                    throw new DBCException("Can't resolve data type " + type.getFullTypeName());
                }
                PostgreDataType itemType = arrayType.getElementType(session.getProgressMonitor());
                if (itemType == null) {
                    throw new DBCException("Array type " + arrayType.getFullTypeName() + " doesn't have a component type");
                }
                if (className.equals(PostgreConstants.PG_OBJECT_CLASS)) {
                    final Object value = PostgreUtils.extractPGObjectValue(object);
                    if (value instanceof String) {
                        return convertStringToArray(session, itemType, (String) value);
                    } else {
                        // Can't parse
                        return new JDBCCollection(
                            itemType,
                            DBUtils.findValueHandler(session, itemType),
                            value == null ? null : new Object[]{value});
                    }
                } else if (object instanceof String) {
                    return convertStringToArray(session, itemType, (String) object);
                }
            }
        }
        return super.getValueFromObject(session, type, object, copy);
    }

    private JDBCCollection convertStringToArray(@NotNull DBCSession session, @NotNull PostgreDataType itemType, @NotNull String value) throws DBCException {
        List<String> strings = new ArrayList<>(10);
        StringTokenizer st = new StringTokenizer(value, " ");
        while (st.hasMoreTokens()) {
            strings.add(st.nextToken());
        }
        Object[] contents = new Object[strings.size()];
        for (int i = 0; i < strings.size(); i++) {
            contents[i] = PostgreUtils.convertStringToValue(session, itemType, strings.get(i), false);
        }
        return new JDBCCollection(itemType, DBUtils.findValueHandler(session, itemType), contents);
    }

    @NotNull
    @Override
    public String getValueDisplayString(@NotNull DBSTypedObject column, Object value, @NotNull DBDDisplayFormat format) {
        if (!DBUtils.isNullValue(value) && value instanceof DBDCollection) {
            DBDCollection collection = (DBDCollection) value;

            DBDValueHandler valueHandler = collection.getComponentValueHandler();
            StringBuilder str = new StringBuilder();
            if (format == DBDDisplayFormat.NATIVE) {
                str.append("'");
            }
            str.append("{");
            for (int i = 0; i < collection.getItemCount(); i++) {
                if (i > 0) {
                    str.append(','); //$NON-NLS-1$
                }
                final Object item = collection.getItem(i);
                String itemString;
                if (item instanceof JDBCCollection) {
                    // Multi-dimensional arrays case
                    itemString = getValueDisplayString(column, item, format);
                } else {
                    itemString = valueHandler.getValueDisplayString(collection.getComponentType(), item, DBDDisplayFormat.NATIVE);
                }
                if (format == DBDDisplayFormat.NATIVE) {
                    str.append(SQLUtils.escapeString(collection.getComponentType().getDataSource(), itemString));
                } else {
                    str.append(itemString);
                }
            }
            str.append("}");
            if (format == DBDDisplayFormat.NATIVE) {
                str.append("'");
            }

            return str.toString();
        }
        return super.getValueDisplayString(column, value, format);
    }
}


text:
module.exports = function (app, data) {
	var posts = require('../app/controllers/posts')(data);
	var users = require('../app/controllers/users')(data);

	app.get('/post', posts.get);
	app.post('/post', posts.createNew);

	app.post('/user', users.register);
	app.post('/auth', users.login);
	app.put('/user', users.logout);
	app.get('/user', users.all);
};


text:
import os
from codecs import open

from setuptools import find_packages, setup

from ariane import __version__

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

def read(*paths):
    """Build a file path from *paths and return the contents."""
    with open(os.path.join(*paths), 'r', 'utf-8') as f:
        return f.read()

extras_require = {}

requires = [
    'asgiref==1.0.0',
    'channels==0.17.3',
    'daphne==0.15.0',
    'Django==1.10.5',
    'dj-database-url==0.4.2',
    'django-allauth==0.30.0',
    'django-braces==1.10.0',
    'django-configurations==2.0',
    'django-crispy-forms==1.6.1',
    'django-grappelli==2.9.1',
    'django-model-utils==2.6',
    'envdir==0.7',
    'psycopg2==2.6.2',
    'pytz==2016.10',
    'wit==4.2.0',
    'wikipedia==1.4.0'
]

setup(
    name='ariane',
    version=__version__,
    description='A short description of the project.',
    long_description=read(BASE_DIR, 'README.rst'),
    author='Max Brauer <max@max-brauer.de>',
    author_email='max@max-brauer.de',
    packages=find_packages(),
    include_package_data=True,
    scripts=['manage.py'],
    install_requires=requires,
    license='BSD',
    zip_safe=False,
    classifiers=[
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: Implementation :: CPython',
    ],
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" service="WFS" version="1.0.0" xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <wfs:Insert>
        <feature:my_places xmlns:feature="http://www.oskari.org">
            <feature:geometry>
                <gml:MultiPoint xmlns:gml="http://www.opengis.net/gml" srsName="EPSG:3067">
                    <gml:pointMember>
                        <gml:Point>
                            <gml:coordinates decimal="." cs="," ts=" ">395540,6706198.1514938</gml:coordinates>
                        </gml:Point>
                    </gml:pointMember>
                </gml:MultiPoint>
            </feature:geometry>
            <feature:name>guest insert test</feature:name>
            <feature:place_desc></feature:place_desc>
            <feature:attention_text></feature:attention_text>
            <feature:link></feature:link>
            <feature:image_url></feature:image_url>
            <feature:category_id>1</feature:category_id>
        </feature:my_places>
    </wfs:Insert>
</wfs:Transaction>


text:
namespace Microsoft.Azure.Management.Batch.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// A private container registry.
    /// </summary>
    public partial class ContainerRegistry
    {
        /// <summary>
        /// Initializes a new instance of the ContainerRegistry class.
        /// </summary>
        public ContainerRegistry()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ContainerRegistry class.
        /// </summary>
        /// <param name="userName">The user name to log into the registry
        /// server.</param>
        /// <param name="password">The password to log into the registry
        /// server.</param>
        /// <param name="registryServer">The registry URL.</param>
        public ContainerRegistry(string userName, string password, string registryServer = default(string))
        {
            RegistryServer = registryServer;
            UserName = userName;
            Password = password;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the registry URL.
        /// </summary>
        /// <remarks>
        /// If omitted, the default is "docker.io".
        /// </remarks>
        [JsonProperty(PropertyName = "registryServer")]
        public string RegistryServer { get; set; }

        /// <summary>
        /// Gets or sets the user name to log into the registry server.
        /// </summary>
        [JsonProperty(PropertyName = "username")]
        public string UserName { get; set; }

        /// <summary>
        /// Gets or sets the password to log into the registry server.
        /// </summary>
        [JsonProperty(PropertyName = "password")]
        public string Password { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (UserName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "UserName");
            }
            if (Password == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Password");
            }
        }
    }
}


text:
module Rupy
  def self.Type(name)
    mod, match, klass = name.rpartition(".")
    pymod = Rupy.import(mod)
    pyclass = pymod.pObject.getAttr(klass)
    rclass = Class.new(RubyPyProxy) do
      define_method(:initialize) do |*args|
        args = PyObject.convert(*args)
        pTuple = PyObject.buildArgTuple(*args)
        pReturn = pyclass.callObject(pTuple)
        if PythonError.error?
          raise PythonError.handle_error
        end
        @pObject = pReturn
      end
    end
    return rclass
  end
end


text:
Mi información

<input type="text" class="form-control" id="name" name="name" placeholder="Nombres" value="" ng-model="name" maxlength="35"/>

<input type="text" class="form-control" id="lastname" name="lastname" placeholder="Apellidos" maxlength="35" value="" ng-model="lastname" />

<input type="text" class="form-control" id="email" name="email" placeholder="@ E-mail" maxlength="15" value=""  ng-model="email" readonly="readonly" />

<input type="text" class="form-control" id="cellPhone" name="cellPhone" placeholder="Num. Celular" maxlength="15" value="" ng-model="cellPhone" />

<input type="password" class="form-control" id="password" name="password" placeholder="Contraseña" maxlength="15" value="" ng-model="password" />

<input type="password" class="form-control" id="password2" name="password2" placeholder="Confirmar Contraseña" maxlength="15" value="" />

      <input id="chk_terminos" name="chk_terminos" type="checkbox" value="1" checked="checked" style="visibility:hidden" />
        <button class="btn" ng-click="setAccount('edit')">Guardar</button>
        <button class="btn btn-danger" ng-click="closeSession()">Cerrar Sesión</button>


text:
module.exports = {
  type: 'trade-area',
  label: _t('editor.layers.analysis-form.time'),
  parametersDataFields: 'type,kind,time,isolines,dissolved',

  parse: function (nodeAttrs) {
    return {
      type: 'trade-area',
      kind: nodeAttrs.kind || 'walk',
      isolines: nodeAttrs.isolines || 1,
      time: nodeAttrs.time || 100,
      dissolved: nodeAttrs.dissolved === 'true' || nodeAttrs.dissolved === true
    };
  },

  formatAttrs: function (formAttrs) {
    return formAttrs;
  }
};


text:
- Improved implementation of empty parameters handling provided to the ***xdr-run-script*** command.
- Updated the Docker image to *demisto/python3:3.9.2.17246*.


text:
<link rel="import" href="packages/polymer/polymer.html">
<link rel="import" href="packages/paper_elements/paper_progress.html">

<polymer-element name="slider-bar">
  <template>

{{bubbleText}}

    <paper-progress id="paperProgress" on-mousedown="{{initDrag}}"  value="{{value}}" secondaryProgress="{{secondValue}}" max="{{max}}"></paper-progress>

  </template>

</polymer-element>


text:
package com.hazelcast.cardinality.impl.hyperloglog.impl;

import com.hazelcast.cardinality.impl.CardinalityEstimatorDataSerializerHook;
import com.hazelcast.internal.nio.Bits;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;

import java.io.IOException;
import java.util.Arrays;

/**
 * 1. http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/40671.pdf
 * <p>The implementation is using a fixed p' = 25 which according to [1] provides very high accuracy
 * for the range of cardinalities where the sparse representation is used.
 */
@SuppressWarnings("checkstyle:magicnumber")
public class SparseHyperLogLogEncoder
        implements HyperLogLogEncoder {

    private static final int P_PRIME = 25;
    private static final int P_PRIME_MASK = 0x1ffffff;
    private static final long P_PRIME_FENCE_MASK = 0x4000000000L;

    private static final int DEFAULT_TEMP_CAPACITY = 200;

    private int p;
    private int pMask;
    private int pFenseMask;
    private long pDiffMask;
    private VariableLengthDiffArray register;

    private int[] temp;
    private int mPrime;
    private int tempIdx;

    public SparseHyperLogLogEncoder() {
    }

    SparseHyperLogLogEncoder(final int p) {
        init(p, new VariableLengthDiffArray());
    }

    public void init(int p, VariableLengthDiffArray register) {
        this.p = p;
        this.pMask = ((1 << p) - 1);
        this.pFenseMask = 1 << (64 - p) - 1;
        this.pDiffMask = P_PRIME_MASK ^ pMask;

        this.mPrime = 1 << P_PRIME;
        this.temp = new int[DEFAULT_TEMP_CAPACITY];
        this.register = register;
    }

    @Override
    public boolean add(long hash) {
        int encoded = encodeHash(hash);
        temp[tempIdx++] = encoded;
        boolean isTempAtCapacity = tempIdx == DEFAULT_TEMP_CAPACITY;
        if (isTempAtCapacity) {
            mergeAndResetTmp();
        }

        return true;
    }

    @Override
    public long estimate() {
        mergeAndResetTmp();
        return linearCounting(mPrime, mPrime - register.total);
    }

    @Override
    public HyperLogLogEncoder merge(HyperLogLogEncoder encoder) {
        HyperLogLogEncoder dense = asDense();
        return dense.merge(encoder);
    }

    @Override
    public int getFactoryId() {
        return CardinalityEstimatorDataSerializerHook.F_ID;
    }

    @Override
    public int getClassId() {
        return CardinalityEstimatorDataSerializerHook.HLL_SPARSE_ENC;
    }

    @Override
    public void writeData(ObjectDataOutput out) throws IOException {
        mergeAndResetTmp();
        out.writeInt(p);
        out.writeInt(register.total);
        out.writeInt(register.mark);
        out.writeInt(register.prev);
        out.writeByteArray(register.elements);
    }

    @Override
    public void readData(ObjectDataInput in) throws IOException {
        int p = in.readInt();
        int total = in.readInt();
        int mark = in.readInt();
        int prev = in.readInt();
        byte[] bytes = in.readByteArray();
        init(p, new VariableLengthDiffArray(bytes, total, mark, prev));
    }

    @Override
    public HyperLogLogEncoding getEncodingType() {
        return HyperLogLogEncoding.SPARSE;
    }

    @Override
    public int getMemoryFootprint() {
        return register.mark + (DEFAULT_TEMP_CAPACITY * Bits.INT_SIZE_IN_BYTES);
    }

    HyperLogLogEncoder asDense() {
        mergeAndResetTmp();

        byte[] dense = new byte[1 << this.p];
        for (int hash : register.explode()) {
            int index = decodeHashPIndex(hash);
            dense[index] = (byte) Math.max(dense[index], decodeHashRunOfZeros(hash));
        }

        return new DenseHyperLogLogEncoder(p, dense);
    }

    private int encodeHash(long hash) {
        if ((hash & pDiffMask) == 0) {
            int newHash = (int) (hash & P_PRIME_MASK) << (32 - P_PRIME);
            return newHash | (Long.numberOfTrailingZeros((hash >>> P_PRIME) | P_PRIME_FENCE_MASK) + 1) << 1 | 0x1;
        }

        return (int) (hash & P_PRIME_MASK) << 1;
    }

    private int decodeHashPPrimeIndex(int hash) {
        if (!hasRunOfZerosEncoded(hash)) {
            return ((hash >> 1) & P_PRIME_MASK) & mPrime - 1;
        }

        return (hash >> (32 - P_PRIME) & P_PRIME_MASK) & mPrime - 1;
    }

    private int decodeHashPIndex(long hash) {
        if (!hasRunOfZerosEncoded(hash)) {
            // |-25bits-||-1bit-
            return (int) ((hash >>> 1)) & pMask;
        }

        // |-25bits-||-6bits-||-1bit-|
        // (p - p') || p(w') || 1
        return (int) (hash >>> 7) & pMask;
    }

    private byte decodeHashRunOfZeros(int hash) {
        int stripedZeroFlag = hash >>> 1;

        if (!hasRunOfZerosEncoded(hash)) {
            // |-25bits-||-1bit-
            // (p - p') || 0
            return (byte) (Long.numberOfTrailingZeros(stripedZeroFlag >>> p | pFenseMask) + 1);
        }

        // |-25bits-||-6bits-||-1bit-|
        // (p - p') || p(w') || 1
        int pW = stripedZeroFlag & ((1 << 6) - 1);
        return (byte) (pW + (P_PRIME - p));
    }

    private boolean hasRunOfZerosEncoded(long hash) {
        // is format (p - p') || p(w') || 1
        return ((hash & 0x1) == 1);
    }

    private long linearCounting(final int total, final int empty) {
        return (long) (total * Math.log(total / (double) empty));
    }

    private void mergeAndResetTmp() {
        if (tempIdx == 0) {
            return;
        }

        // merge existing register with temp
        int[] old = register.explode();
        int[] all = Arrays.copyOf(old, old.length + tempIdx);

        System.arraycopy(temp, 0, all, old.length, tempIdx);
        Arrays.sort(all);

        // clear register, re-inserting will be in different order, due to new values
        register.clear();

        int previousHash = all[0];
        for (int i = 1; i < all.length; i++) {
            int hash = all[i];
            boolean conflictingIndex = decodeHashPPrimeIndex(hash) == decodeHashPPrimeIndex(previousHash);

            if (!conflictingIndex) {
                register.add(previousHash);
            }

            previousHash = hash;
        }

        register.add(previousHash);
        Arrays.fill(temp, 0);
        tempIdx = 0;
    }

    /**
     * Variable length difference encoding for sorted integer lists.
     *
     * Single byte, (7 bits) used to store the value if less or equal to 127,
     * or more bytes for larger numbers, having the MSB bit set to 1 to signify
     * the next_flag. Also, numbers are stored as a diff from the previous one
     * to make the Variable Length algo more efficient. Therefore, the input must
     * be sorted first.
     */
    private static class VariableLengthDiffArray {
        //aka 32
        private static final int INITIAL_CAPACITY = 1 << 5;

        private byte[] elements = new byte[INITIAL_CAPACITY];

        private int prev;
        private int total;
        private int mark;

        VariableLengthDiffArray() {
        }

        VariableLengthDiffArray(final byte[] elements, final int total, final int mark, final int prev) {
            this.elements = elements;
            this.total = total;
            this.mark = mark;
            this.prev = prev;
        }

        void add(int value) {
            append(value - prev);
            prev = value;
        }

        void clear() {
            Arrays.fill(elements, (byte) 0);
            mark = 0;
            total = 0;
            prev = 0;
        }

        int[] explode() {
            int[] exploded = new int[total];
            int counter = 0;

            int last = 0;
            for (int i = 0; i < mark; i++) {
                int noOfBytes = 0;
                byte element;

                do {
                    element = elements[i++];
                    exploded[counter] |= (element & 0x7F) << (7 * noOfBytes++);
                } while (needsMoreBytes(element));

                exploded[counter] += last;
                last = exploded[counter];

                // fix positions
                i--;
                counter++;
            }

            return exploded;
        }

        private void append(int diff) {
            while (diff > 0x7F) {
                ensureCapacity();
                elements[mark++] = (byte) ((diff & 0x7F) | 0x80);
                diff >>>= 7;
            }

            ensureCapacity();
            elements[mark++] = (byte) (diff & 0x7F);
            total++;
        }

        private void ensureCapacity() {
            if (elements.length == mark) {
                int newCapacity = elements.length << 1;
                elements = Arrays.copyOf(elements, newCapacity);
            }
        }

        private boolean needsMoreBytes(byte val) {
            return (val & 0x80) != 0;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<string name="cancel">"Avbryt"</string>
<string name="http_post_warning">"Önskad sida använder information som du har angett. Om du återgår till sidan kan eventuella åtgärder på sidan upprepas. Vill du fortsätta?"</string>
<string name="http_post_warning_resend">"Fortsätt"</string>
<string name="firstrun_signed_in_title">"Du är nu inloggad i Chrome."</string>
<string name="firstrun_signed_in_description">"Bland annat öppna flikar, bokmärken och historik synkroniseras med ditt Google-konto."</string>
<string name="sad_tab_title">"Oj, ett fel har uppstått!"</string>
<string name="sad_tab_message">"Ett fel uppstod när webbsidan skulle visas. Fortsätt genom att läsa in sidan på nytt eller besök en annan sida."</string>
<string name="sad_tab_help_message">"Om du ser detta ofta provar du $1."</string>
<string name="sad_tab_help_link">"förslag"</string>
<string name="sad_tab_reload_label">"Hämta igen"</string>
<string name="options_startup_pages_placeholder">"Ange webbadress ..."</string>
</resources>


text:
export default function() {
  return {
    manipulateOptions(opts, parserOpts) {
      parserOpts.plugins.push("nullishCoalescingOperator");
    },
  };
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using OneDriveWeb.Models;

namespace OneDriveWeb.Controllers {
  public class OneDriveNewApiController : Controller {
    [Authorize]
    public async Task<ActionResult> Index(int? pageIndex, int? pageSize) {

      var repository = new OneDriveNewApiRepository();

      // setup paging defaults if not provided
      pageIndex = pageIndex ?? 0;
      pageSize = pageSize ?? 10;

      // setup paging for the IU
      ViewBag.PageIndex = (int)pageIndex;
      ViewBag.PageSize = (int)pageSize;

      var myFiles = await repository.GetMyFiles((int)pageIndex, (int)pageSize);

      return View(myFiles);
    }

    [Authorize]
    public async Task<ActionResult> Delete(string id, string etag) {
      var repository = new OneDriveNewApiRepository();

      if (id != null) {
        await repository.DeleteFile(id, etag);
      }

      return Redirect("/");
    }

  }
}


text:
var profile = require("./profile");
profile.get("chalkers");


text: ALTER TABLE person ALTER COLUMN id RENAME TO id;


text:
<?php

namespace TelegramBot\Api\Test\Types;

use TelegramBot\Api\Types\CallbackQuery;
use TelegramBot\Api\Types\Message;
use TelegramBot\Api\Types\User;

class CallbackQueryTest extends \PHPUnit_Framework_TestCase
{
    protected $callbackQueryFixture = [
        'id' => 1,
        'from' => [
            'first_name' => 'Ilya',
            'last_name' => 'Gusev',
            'id' => 123456,
            'username' => 'iGusev',
        ],
        'inline_message_id' => 1234,
        'chat_instance' => 123,
        'data' => 'callback_data',
        'game_short_name' => 'game_name'
    ];

    public function testFromResponse()
    {
        $item = CallbackQuery::fromResponse($this->callbackQueryFixture);

        $user = User::fromResponse($this->callbackQueryFixture['from']);

        $this->assertInstanceOf('\TelegramBot\Api\Types\CallbackQuery', $item);
        $this->assertEquals($this->callbackQueryFixture['id'], $item->getId());
        $this->assertEquals($user, $item->getFrom());
        $this->assertEquals($this->callbackQueryFixture['inline_message_id'], $item->getInlineMessageId());
        $this->assertEquals($this->callbackQueryFixture['chat_instance'], $item->getChatInstance());
        $this->assertEquals($this->callbackQueryFixture['data'], $item->getData());
        $this->assertEquals($this->callbackQueryFixture['game_short_name'], $item->getGameShortName());
    }

    /**
     * @expectedException \TelegramBot\Api\InvalidArgumentException
     */
    public function testFromResponseExceptionEmptyId() {
        unset($this->callbackQueryFixture['id']);
        CallbackQuery::fromResponse($this->callbackQueryFixture);
    }

    /**
     * @expectedException \TelegramBot\Api\InvalidArgumentException
     */
    public function testFromResponseExceptionEmptyFrom() {
        unset($this->callbackQueryFixture['from']);
        CallbackQuery::fromResponse($this->callbackQueryFixture);
    }

    public function testSetId()
    {
        $item = new CallbackQuery();
        $item->setId($this->callbackQueryFixture['id']);
        $this->assertAttributeEquals($this->callbackQueryFixture['id'], 'id', $item);
    }

    public function testGetId()
    {
        $item = new CallbackQuery();
        $item->setId($this->callbackQueryFixture['id']);
        $this->assertEquals($this->callbackQueryFixture['id'], $item->getId());
    }

    public function testSetFrom()
    {
        $item = new CallbackQuery();
        $user = User::fromResponse($this->callbackQueryFixture['from']);
        $item->setFrom($user);
        $this->assertAttributeEquals($user, 'from', $item);
    }

    public function testGetFrom() {
        $item = new CallbackQuery();
        $user = User::fromResponse($this->callbackQueryFixture['from']);
        $item->setFrom($user);
        $this->assertEquals($user, $item->getFrom());
    }

    public function testSetInlineMessageId()
    {
        $item = new CallbackQuery();
        $item->setInlineMessageId($this->callbackQueryFixture['inline_message_id']);
        $this->assertAttributeEquals($this->callbackQueryFixture['inline_message_id'], 'inlineMessageId', $item);
    }

    public function testGetInlineMessageId() {
        $item = new CallbackQuery();
        $item->setInlineMessageId('testInlineMessageId');
        $this->assertEquals('testInlineMessageId', $item->getInlineMessageId());
    }

    public function testSetChatInstance()
    {
        $item = new CallbackQuery();
        $item->setChatInstance($this->callbackQueryFixture['chat_instance']);
        $this->assertAttributeEquals($this->callbackQueryFixture['chat_instance'], 'chatInstance', $item);
    }

    public function testGetChatInstance() {
        $item = new CallbackQuery();
        $item->setChatInstance('testChatInstance');
        $this->assertEquals('testChatInstance', $item->getChatInstance());
    }

    public function testSetData()
    {
        $item = new CallbackQuery();
        $item->setData($this->callbackQueryFixture['data']);
        $this->assertAttributeEquals($this->callbackQueryFixture['data'], 'data', $item);
    }

    public function testGetData() {
        $item = new CallbackQuery();
        $item->setData('testData');
        $this->assertEquals('testData', $item->getData());
    }

    public function testSetGameShortName()
    {
        $item = new CallbackQuery();
        $item->setGameShortName($this->callbackQueryFixture['game_short_name']);
        $this->assertAttributeEquals($this->callbackQueryFixture['game_short_name'], 'gameShortName', $item);
    }

    public function testGetGameShortName() {
        $item = new CallbackQuery();
        $item->setGameShortName('testGameShortName');
        $this->assertEquals('testGameShortName', $item->getGameShortName());
    }

}


text:
<!DOCTYPE html>

    <title>PicoGL.js Example: Occlusion Culling</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="../site/css/picogl-example.css">

        PicoGL.js Example: Occlusion Culling

            Source code

    <canvas id="gl-canvas"></canvas>

        Spheres:

        Culled spheres:

        Enable occlusion culling: <input id="occlusion-toggle" type="checkbox" checked>

        Top-down HUD: <input id="hud-toggle" type="checkbox" checked>


text:
package pl.snowdog.dzialajlokalnie.events;

/**
 * Created by bartek on 16.07.15.
 */
public class SetTitleAndPhotoEvent {

    String title;
    String photoUrl;

    public SetTitleAndPhotoEvent(String title, String photoUrl) {
        this.title = title;
        this.photoUrl = photoUrl;
    }

    @Override
    public String toString() {
        return "SetTitleAndPhotoEvent{" +
                "title='" + title + '\'' +
                ", photoUrl='" + photoUrl + '\'' +
                '}';
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPhotoUrl() {
        return photoUrl;
    }

    public void setPhotoUrl(String photoUrl) {
        this.photoUrl = photoUrl;
    }
}


text:
package water.util.fp;

import java.io.Serializable;

/**
 * An abstraction for the entities that don't have any data,
 * so they are equal if they are of the same class.
 *
 * Comparison is done by comparing canonical class names. This ensures that
 * classes loaded by different classloaders still are comparable.
 */
public abstract class JustCode implements Serializable {
  @Override public int hashCode() {
    return getClass().getName().hashCode();
  }

  @Override public boolean equals(Object other) {
    return other != null && getClass().getName().equals(other.getClass().getName());
  }
}


text:
package ieugen.trainings.di.guice;

import com.google.inject.AbstractModule;
import ieugen.trainings.di.notebook.api.Battery;
import ieugen.trainings.di.notebook.api.Computer;
import ieugen.trainings.di.notebook.api.Display;
import ieugen.trainings.di.notebook.api.Keyboard;
import ieugen.trainings.di.notebook.impl.DefaultBattery;
import ieugen.trainings.di.notebook.impl.LedKeyboard;
import ieugen.trainings.di.notebook.impl.NoteBook;
import ieugen.trainings.di.notebook.impl.RetinaDisplay;

public class ModernNoteBookModule extends AbstractModule {

    @Override
    protected void configure() {

        bind(Keyboard.class).to(LedKeyboard.class);
        bind(Display.class).to(RetinaDisplay.class);
        bind(Battery.class).to(DefaultBattery.class);
        bind(Computer.class).to(NoteBook.class);
    }
}


text:
<readable><title>2659183350_730951f740</title><content>
A boy in a red and white shirt kicks a large baseball while surrounded by people .
A boy kicks a giant baseball while a group of children watch .
A boy kicks a really large baseball
A kid kicking a large ball while surrounded by other kids .
Children are outside playing with an oversized baseball .
</content></readable>


text:
FROM openjdk13:alpine-jre

LABEL maintainer="Douglas Apolinário <douglas@konkerlabs.com>"

ENV KONKER_BASE /var/lib/konker
RUN mkdir -p "$KONKER_BASE"

WORKDIR $KONKER_BASE

COPY docker-resources/docker-entrypoint.sh /
RUN chmod 777 /docker-entrypoint.sh

COPY target/cassandra-etl.jar /var/lib/konker/
COPY docker-resources/dist/application.conf /var/lib/konker/
COPY docker-resources/dist/logback.xml /var/lib/konker/

#start
EXPOSE 80
ENTRYPOINT ["/docker-entrypoint.sh"]


text:
using UnityEngine;
using System.Collections;

public class Help : MonoBehaviour {

	bool showHelp;
	public static bool adjustSize;
	string instructions = "No instructions";
	Rect helpRect = new Rect(Screen.width - 80, 0, 80, 25);
	Rect adjustRect = new Rect(Screen.width - 80, 25, 80, 25);

	void OnGUI(){
		GUI.depth = 0;

		if(showHelp){
			if(GUI.Button(helpRect, "Hide Help")){
				showHelp = !showHelp;
			}

			if(Application.loadedLevelName == "Main Menu"){
				instructions = "Choose singleplayer or multi-player.";
			}
			if(Application.loadedLevelName == "SinglePlayer"){
				instructions = "Choose a level to play.";
			}
			if(Application.loadedLevelName == "Lobby"){
				instructions = "Press \"Host a game\" to start your own game, " +
								"\npress \"Refresh Hsots\" to list any other people hosting a game." +
								"\nWhen connected to a server press level buttons to load a level.";
			}
			if(Application.loadedLevelName == "Level 1-1"){
				instructions = "WASD to move, push the blocks into areas to fill or " +
								"\nempty and push into each other to transfer values." +
								"\n\nWhen the container is filled with 4, push onto Dock.";
			}
			if(Application.loadedLevelName == "Level 2-1" || Application.loadedLevelName == "Level 2-2"){
				instructions = "Click on text to fill, empty and move the volumes " +
								"\nbetween the containers." +
								"\n\nGet 4 liters in the 5 liter jug.";
			}
			if(Application.loadedLevelName == "Level 2-2" || Application.loadedLevelName == "Level 2-2"){
				instructions = "Click on text to fill, empty and move the volumes " +
								"\nbetween the containers."  +
								"\n\nGet 2 liters in two of the jugs.";
			}
			if(Application.loadedLevelName == "Level 2-3" || Application.loadedLevelName == "Level 2-2"){
				instructions = "Click on text to fill, empty and move the volumes " +
								"\nbetween the containers.";
			}
			GUI.Box(new Rect(0, 0, Screen.width, Screen.height), instructions);
		}
		else{
			if(GUI.Button(helpRect, "Show Help")){
				showHelp = !showHelp;
			}
		}
	}
}


text:
package org.springframework.boot.gradle.tasks.bundling;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.gradle.api.Project;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import org.springframework.boot.buildpack.platform.build.BuildRequest;
import org.springframework.boot.buildpack.platform.build.BuildpackReference;
import org.springframework.boot.buildpack.platform.build.PullPolicy;
import org.springframework.boot.buildpack.platform.docker.type.Binding;
import org.springframework.boot.buildpack.platform.docker.type.ImageReference;
import org.springframework.boot.gradle.junit.GradleProjectBuilder;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link BootBuildImage}.
 *
 * @author Andy Wilkinson
 * @author Scott Frederick
 * @author Andrey Shlykov
 * @author Jeroen Meijer
 * @author Rafael Ceccone
 */
class BootBuildImageTests {

	Project project;

	private BootBuildImage buildImage;

	@BeforeEach
	void setUp(@TempDir File temp) {
		File projectDir = new File(temp, "project");
		projectDir.mkdirs();
		this.project = GradleProjectBuilder.builder().withProjectDir(projectDir).withName("build-image-test").build();
		this.project.setDescription("Test project for BootBuildImage");
		this.buildImage = this.project.getTasks().create("buildImage", BootBuildImage.class);
	}

	@Test
	void whenProjectVersionIsUnspecifiedThenItIsIgnoredWhenDerivingImageName() {
		assertThat(this.buildImage.getImageName().get()).isEqualTo("docker.io/library/build-image-test");
		BuildRequest request = this.buildImage.createRequest();
		assertThat(request.getName().getDomain()).isEqualTo("docker.io");
		assertThat(request.getName().getName()).isEqualTo("library/build-image-test");
		assertThat(request.getName().getTag()).isEqualTo("latest");
		assertThat(request.getName().getDigest()).isNull();
	}

	@Test
	void whenProjectVersionIsSpecifiedThenItIsUsedInTagOfImageName() {
		this.project.setVersion("1.2.3");
		assertThat(this.buildImage.getImageName().get()).isEqualTo("docker.io/library/build-image-test:1.2.3");
		BuildRequest request = this.buildImage.createRequest();
		assertThat(request.getName().getDomain()).isEqualTo("docker.io");
		assertThat(request.getName().getName()).isEqualTo("library/build-image-test");
		assertThat(request.getName().getTag()).isEqualTo("1.2.3");
		assertThat(request.getName().getDigest()).isNull();
	}

	@Test
	void whenImageNameIsSpecifiedThenItIsUsedInRequest() {
		this.project.setVersion("1.2.3");
		this.buildImage.getImageName().set("example.com/test/build-image:1.0");
		assertThat(this.buildImage.getImageName().get()).isEqualTo("example.com/test/build-image:1.0");
		BuildRequest request = this.buildImage.createRequest();
		assertThat(request.getName().getDomain()).isEqualTo("example.com");
		assertThat(request.getName().getName()).isEqualTo("test/build-image");
		assertThat(request.getName().getTag()).isEqualTo("1.0");
		assertThat(request.getName().getDigest()).isNull();
	}

	@Test
	void springBootVersionDefaultValueIsUsed() {
		BuildRequest request = this.buildImage.createRequest();
		assertThat(request.getCreator().getName()).isEqualTo("Spring Boot");
		assertThat(request.getCreator().getVersion()).isEqualTo("");
	}

	@Test
	void whenIndividualEntriesAreAddedToTheEnvironmentThenTheyAreIncludedInTheRequest() {
		this.buildImage.getEnvironment().put("ALPHA", "a");
		this.buildImage.getEnvironment().put("BRAVO", "b");
		assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b")
				.hasSize(2);
	}

	@Test
	void whenEntriesAreAddedToTheEnvironmentThenTheyAreIncludedInTheRequest() {
		Map<String, String> environment = new HashMap<>();
		environment.put("ALPHA", "a");
		environment.put("BRAVO", "b");
		this.buildImage.getEnvironment().putAll(environment);
		assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b")
				.hasSize(2);
	}

	@Test
	void whenTheEnvironmentIsSetItIsIncludedInTheRequest() {
		Map<String, String> environment = new HashMap<>();
		environment.put("ALPHA", "a");
		environment.put("BRAVO", "b");
		this.buildImage.getEnvironment().set(environment);
		assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b")
				.hasSize(2);
	}

	@Test
	void whenTheEnvironmentIsSetItReplacesAnyExistingEntriesAndIsIncludedInTheRequest() {
		Map<String, String> environment = new HashMap<>();
		environment.put("ALPHA", "a");
		environment.put("BRAVO", "b");
		this.buildImage.getEnvironment().put("C", "Charlie");
		this.buildImage.getEnvironment().set(environment);
		assertThat(this.buildImage.createRequest().getEnv()).containsEntry("ALPHA", "a").containsEntry("BRAVO", "b")
				.hasSize(2);
	}

	@Test
	void whenUsingDefaultConfigurationThenRequestHasVerboseLoggingDisabled() {
		assertThat(this.buildImage.createRequest().isVerboseLogging()).isFalse();
	}

	@Test
	void whenVerboseLoggingIsEnabledThenRequestHasVerboseLoggingEnabled() {
		this.buildImage.getVerboseLogging().set(true);
		assertThat(this.buildImage.createRequest().isVerboseLogging()).isTrue();
	}

	@Test
	void whenUsingDefaultConfigurationThenRequestHasCleanCacheDisabled() {
		assertThat(this.buildImage.createRequest().isCleanCache()).isFalse();
	}

	@Test
	void whenCleanCacheIsEnabledThenRequestHasCleanCacheEnabled() {
		this.buildImage.getCleanCache().set(true);
		assertThat(this.buildImage.createRequest().isCleanCache()).isTrue();
	}

	@Test
	void whenUsingDefaultConfigurationThenRequestHasPublishDisabled() {
		assertThat(this.buildImage.createRequest().isPublish()).isFalse();
	}

	@Test
	void whenNoBuilderIsConfiguredThenRequestHasDefaultBuilder() {
		assertThat(this.buildImage.createRequest().getBuilder().getName()).isEqualTo("paketobuildpacks/builder");
	}

	@Test
	void whenBuilderIsConfiguredThenRequestUsesSpecifiedBuilder() {
		this.buildImage.getBuilder().set("example.com/test/builder:1.2");
		assertThat(this.buildImage.createRequest().getBuilder().getName()).isEqualTo("test/builder");
	}

	@Test
	void whenNoRunImageIsConfiguredThenRequestUsesDefaultRunImage() {
		assertThat(this.buildImage.createRequest().getRunImage()).isNull();
	}

	@Test
	void whenRunImageIsConfiguredThenRequestUsesSpecifiedRunImage() {
		this.buildImage.getRunImage().set("example.com/test/run:1.0");
		assertThat(this.buildImage.createRequest().getRunImage().getName()).isEqualTo("test/run");
	}

	@Test
	void whenUsingDefaultConfigurationThenRequestHasAlwaysPullPolicy() {
		assertThat(this.buildImage.createRequest().getPullPolicy()).isEqualTo(PullPolicy.ALWAYS);
	}

	@Test
	void whenPullPolicyIsConfiguredThenRequestHasPullPolicy() {
		this.buildImage.getPullPolicy().set(PullPolicy.NEVER);
		assertThat(this.buildImage.createRequest().getPullPolicy()).isEqualTo(PullPolicy.NEVER);
	}

	@Test
	void whenNoBuildpacksAreConfiguredThenRequestUsesDefaultBuildpacks() {
		assertThat(this.buildImage.createRequest().getBuildpacks()).isEmpty();
	}

	@Test
	void whenBuildpacksAreConfiguredThenRequestHasBuildpacks() {
		this.buildImage.getBuildpacks().set(Arrays.asList("example/buildpack1", "example/buildpack2"));
		assertThat(this.buildImage.createRequest().getBuildpacks()).containsExactly(
				BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2"));
	}

	@Test
	void whenEntriesAreAddedToBuildpacksThenRequestHasBuildpacks() {
		this.buildImage.getBuildpacks().addAll(Arrays.asList("example/buildpack1", "example/buildpack2"));
		assertThat(this.buildImage.createRequest().getBuildpacks()).containsExactly(
				BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2"));
	}

	@Test
	void whenIndividualEntriesAreAddedToBuildpacksThenRequestHasBuildpacks() {
		this.buildImage.getBuildpacks().add("example/buildpack1");
		this.buildImage.getBuildpacks().add("example/buildpack2");
		assertThat(this.buildImage.createRequest().getBuildpacks()).containsExactly(
				BuildpackReference.of("example/buildpack1"), BuildpackReference.of("example/buildpack2"));
	}

	@Test
	void whenNoBindingsAreConfiguredThenRequestHasNoBindings() {
		assertThat(this.buildImage.createRequest().getBindings()).isEmpty();
	}

	@Test
	void whenBindingsAreConfiguredThenRequestHasBindings() {
		this.buildImage.getBindings().set(Arrays.asList("host-src:container-dest:ro", "volume-name:container-dest:rw"));
		assertThat(this.buildImage.createRequest().getBindings())
				.containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw"));
	}

	@Test
	void whenEntriesAreAddedToBindingsThenRequestHasBindings() {
		this.buildImage.getBindings()
				.addAll(Arrays.asList("host-src:container-dest:ro", "volume-name:container-dest:rw"));
		assertThat(this.buildImage.createRequest().getBindings())
				.containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw"));
	}

	@Test
	void whenIndividualEntriesAreAddedToBindingsThenRequestHasBindings() {
		this.buildImage.getBindings().add("host-src:container-dest:ro");
		this.buildImage.getBindings().add("volume-name:container-dest:rw");
		assertThat(this.buildImage.createRequest().getBindings())
				.containsExactly(Binding.of("host-src:container-dest:ro"), Binding.of("volume-name:container-dest:rw"));
	}

	@Test
	void whenNetworkIsConfiguredThenRequestHasNetwork() {
		this.buildImage.getNetwork().set("test");
		assertThat(this.buildImage.createRequest().getNetwork()).isEqualTo("test");
	}

	@Test
	void whenNoTagsAreConfiguredThenRequestHasNoTags() {
		assertThat(this.buildImage.createRequest().getTags()).isEmpty();
	}

	@Test
	void whenTagsAreConfiguredThenRequestHasTags() {
		this.buildImage.getTags()
				.set(Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest"));
		assertThat(this.buildImage.createRequest().getTags()).containsExactly(ImageReference.of("my-app:latest"),
				ImageReference.of("example.com/my-app:0.0.1-SNAPSHOT"), ImageReference.of("example.com/my-app:latest"));
	}

	@Test
	void whenEntriesAreAddedToTagsThenRequestHasTags() {
		this.buildImage.getTags().addAll(
				Arrays.asList("my-app:latest", "example.com/my-app:0.0.1-SNAPSHOT", "example.com/my-app:latest"));
		assertThat(this.buildImage.createRequest().getTags()).containsExactly(ImageReference.of("my-app:latest"),
				ImageReference.of("example.com/my-app:0.0.1-SNAPSHOT"), ImageReference.of("example.com/my-app:latest"));
	}

	@Test
	void whenIndividualEntriesAreAddedToTagsThenRequestHasTags() {
		this.buildImage.getTags().add("my-app:latest");
		this.buildImage.getTags().add("example.com/my-app:0.0.1-SNAPSHOT");
		this.buildImage.getTags().add("example.com/my-app:latest");
		assertThat(this.buildImage.createRequest().getTags()).containsExactly(ImageReference.of("my-app:latest"),
				ImageReference.of("example.com/my-app:0.0.1-SNAPSHOT"), ImageReference.of("example.com/my-app:latest"));
	}

}


text:
import {
  Component,
  ViewEncapsulation,
  ViewChild,
  ElementRef,
  Input,
  NgZone } from '@angular/core';
import { InteractivityChecker } from './interactivity-checker';
import { coerceBooleanProperty } from '../coercion/boolean-property';

/**
 * Directive for trapping focus within a region.
 *
 * NOTE: This directive currently uses a very simple (naive) approach to focus trapping.
 * It assumes that the tab order is the same as DOM order, which is not necessarily true.
 * Things like tabIndex > 0, flex `order`, and shadow roots can cause the two to misalign.
 * This will be replaced with a more intelligent solution before the library is considered stable.
 *
 * The HTMLElement.tabIndex property represents the tab order of the current element.
 * If both set to "0", they will be traversed in the order they appear.
 *
 * If hit "tab" and reach the last div below, move back up to the first tabbable element.
 * If hit "shift-tag" and reach the first div below, move down to the last tabbable element.
 */
@Component({
  moduleId: module.id,
  selector: 'focus-trap',
  templateUrl: 'focus-trap.html',
  encapsulation: ViewEncapsulation.None
})
export class FocusTrap
{
  @ViewChild('trappedContent') trappedContent: ElementRef;

  /** Whether the focus trap is active. */
  @Input()
  get disabled(): boolean { return this.f_b_disabled; }
  set disabled(val: boolean) { this.f_b_disabled  = coerceBooleanProperty(val); }
  private f_b_disabled: boolean = false;

  constructor(
    private f_checker: InteractivityChecker,
    private f_ngZone: NgZone
  ) { } // constructor()

  /**
   * Waits for the microtask queue to empty, then focuses the first
   * tabbable element within the focus trap region.
   */
  focusFirstTabbableElementWhenReady()
  {
    this.f_ngZone.onMicrotaskEmpty.first().subscribe( () => {
      this.focusFirstTabbableElement();
    });

  } // focusFirstTabbableElementWhenReady()

  /**
   * Waits for the microtask queue to empty, then focuses the last
   * tabbable element within the focus trap region.
   */
  focusLastTabbableElementWhenReady()
  {
    this.f_ngZone.onMicrotaskEmpty.first().subscribe( () => {
      this.focusLastTabbableElement();
    });

  } // focusLastTabbableElementWhenReady()

  /**
   * Focuses the first tabbable element within the focus trap region
   */
  focusFirstTabbableElement()
  {
    // let redirectToElement = this._getFirstTabbableElement(this.trappedContent.nativeElement);
    let rootElement: HTMLElement = this.trappedContent.nativeElement;
    let redirectToElement =
      rootElement.querySelector('[md-focus-start]') as HTMLElement ||
      this._getFirstTabbableElement(rootElement);

    if (redirectToElement) // if not null
    {
      redirectToElement.focus();
    }
  } // focusFirstTabbableElement()

  /**
   * Get the first tabbable element from a DOM subtree (inclusive)
   */
  private _getFirstTabbableElement(a_root: HTMLElement): HTMLElement
  {
    if (this.f_checker.isFocusable(a_root) && this.f_checker.isTabbable(a_root))
    {
      return a_root;
    }

    // iterate in DOM order.
    // go through each of the a_root's children and return the first one
    // that is tabbable.
    let n_childCount = a_root.children.length;
    for (let i = 0; i < n_childCount; i++)
    {
      let tabbableChild = this._getFirstTabbableElement(a_root.children[i] as HTMLElement);
      if (tabbableChild)
      {
        return tabbableChild;
      }
    } // for

    return null;

  } // _getFirstTabbableElement()

  /**
   * Focuses the last tabbable element within the focus trap region
   */
  focusLastTabbableElement()
  {
    // let redirectToElement = this._getLastTabbableElement(this.trappedContent.nativeElement);
    let rootElement: HTMLElement = this.trappedContent.nativeElement;
    let focusTargets = rootElement.querySelectorAll('[md-focus-end]');
    let redirectToElement: HTMLElement = null;

    if (focusTargets.length)
    {
      redirectToElement = focusTargets[focusTargets.length - 1] as HTMLElement;
    }
    else
    {
      redirectToElement = this._getLastTabbableElement(rootElement);
    }

    if (redirectToElement)
    {
      redirectToElement.focus();
    }

  } // focusLastTabbableElement()

  /**
   * Get the last tabbable element from a DOM subtree (inclusive).
   * First check if a_root isTabbable.
   * If not, move on to his children.
   */
  private _getLastTabbableElement(a_root: HTMLElement): HTMLElement
  {
    if (this.f_checker.isFocusable(a_root) && this.f_checker.isTabbable(a_root))
    {
      return a_root;
    }

    // iterate in reverse DOM order
    for (let i = a_root.children.length - 1; i >= 0; i--)
    {
      let tabbableChild = this._getLastTabbableElement(a_root.children[i] as HTMLElement);
      if (tabbableChild)
      {
        return tabbableChild;
      }
    } // for

    return null;

  } // _getLastTabbableElement()

} // class FocusTrap


text:
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <installed facet="php.core.component" version="1"/>
  <installed facet="php.composer.component" version="1"/>
</faceted-project>


text:
package com.tokenautocomplete;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.widget.MultiAutoCompleteTextView;

import java.util.ArrayList;

/**
 * Tokenizer with configurable array of characters to tokenize on.
 *
 * Created on 2/3/15.
 * @author mgod
 */
public class CharacterTokenizer implements MultiAutoCompleteTextView.Tokenizer {
    ArrayList<Character> splitChar;

    CharacterTokenizer(char[] splitChar){
        super();
        this.splitChar = new ArrayList<>(splitChar.length);
        for(char c : splitChar) this.splitChar.add(c);
    }

    public int findTokenStart(CharSequence text, int cursor) {
        int i = cursor;

        while (i > 0 && !splitChar.contains(text.charAt(i - 1))) {
            i--;
        }
        while (i < cursor && text.charAt(i) == ' ') {
            i++;
        }

        return i;
    }

    public int findTokenEnd(CharSequence text, int cursor) {
        int i = cursor;
        int len = text.length();

        while (i < len) {
            if (splitChar.contains(text.charAt(i))) {
                return i;
            } else {
                i++;
            }
        }

        return len;
    }

    public CharSequence terminateToken(CharSequence text) {
        int i = text.length();

        while (i > 0 && text.charAt(i - 1) == ' ') {
            i--;
        }

        if (i > 0 && splitChar.contains(text.charAt(i - 1))) {
            return text;
        } else {
            // Try not to use a space as a token character
            String token = (splitChar.size()>1 && splitChar.get(0)==' ' ? splitChar.get(1) : splitChar.get(0))+" ";
            if (text instanceof Spanned) {
                SpannableString sp = new SpannableString(text + token);
                TextUtils.copySpansFrom((Spanned) text, 0, text.length(),
                        Object.class, sp, 0);
                return sp;
            } else {
                return text + token;
            }
        }
    }
}


text:
from urllib import parse

from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import strutils

from tacker._i18n import _
from tacker.vnfm.monitor_drivers.token import Token
from tacker import wsgi
# check alarm url with db --> move to plugin

LOG = logging.getLogger(__name__)

OPTS = [
    cfg.StrOpt('username', default='admin',
        help=_('User name for alarm monitoring')),
    cfg.StrOpt('password', default='devstack',
        help=_('Password for alarm monitoring')),
    cfg.StrOpt('project_name', default='admin',
        help=_('Project name for alarm monitoring')),
    cfg.StrOpt('user_domain_name', default='Default',
        help=_('User domain name for alarm monitoring')),
    cfg.StrOpt('project_domain_name', default='Default',
        help=_('Project domain name for alarm monitoring')),
]

cfg.CONF.register_opts(OPTS, 'alarm_auth')

def config_opts():
    return [('alarm_auth', OPTS)]

class AlarmReceiver(wsgi.Middleware):
    def process_request(self, req):
        LOG.debug('Process request: %s', strutils.mask_password(req))
        if req.method != 'POST':
            return
        url = req.url
        if not self.handle_url(url):
            return
        prefix, info, params = self.handle_url(req.url)
        resource = 'trigger' if info[4] != 'maintenance' else 'maintenance'
        redirect = resource + 's'
        auth = cfg.CONF.keystone_authtoken
        alarm_auth = cfg.CONF.alarm_auth
        token = Token(username=alarm_auth.username,
                      password=alarm_auth.password,
                      project_name=alarm_auth.project_name,
                      auth_url=auth.auth_url + '/v3',
                      user_domain_name=alarm_auth.user_domain_name,
                      project_domain_name=alarm_auth.project_domain_name)

        token_identity = token.create_token()
        req.headers['X_AUTH_TOKEN'] = token_identity
        # Change the body request
        if req.body:
            body_dict = dict()
            body_dict[resource] = {}
            body_dict[resource].setdefault('params', {})
            # Update params in the body request
            body_info = jsonutils.loads(req.body)
            body_dict[resource]['params']['credential'] = info[6]
            if resource == 'maintenance':
                body_info.update({
                    'body': self._handle_maintenance_body(body_info)})
                del body_info['reason_data']
            else:
                # Update policy and action
                body_dict[resource]['policy_name'] = info[4]
                body_dict[resource]['action_name'] = info[5]
            body_dict[resource]['params']['data'] = body_info
            req.body = jsonutils.dump_as_bytes(body_dict)
            LOG.debug('Body alarm: %s', req.body)
        # Need to change url because of mandatory
        req.environ['PATH_INFO'] = prefix + redirect
        req.environ['QUERY_STRING'] = ''
        LOG.debug('alarm url in receiver: %s', req.url)

    def handle_url(self, url):
        # alarm_url = 'http://host:port/v1.0/vnfs/vnf-uuid/mon-policy-name/action-name/8ef785' # noqa
        parts = parse.urlparse(url)
        p = parts.path.split('/')
        if len(p) != 7:
            return None

        if any((p[0] != '', p[2] != 'vnfs')):
            return None
        # decode action name: respawn%25log
        p[5] = parse.unquote(p[5])
        qs = parse.parse_qs(parts.query)
        params = dict((k, v[0]) for k, v in qs.items())
        prefix_url = '/%(collec)s/%(vnf_uuid)s/' % {'collec': p[2],
                                                    'vnf_uuid': p[3]}
        return prefix_url, p, params

    def _handle_maintenance_body(self, body_info):
        body = {}
        traits_list = body_info['reason_data']['event']['traits']
        if type(traits_list) is not list:
            return
        for key, t_type, val in traits_list:
            if t_type == 1 and val and (val[0] == '[' or val[0] == '{'):
                body[key] = eval(val)
            else:
                body[key] = val
        return body


text:
The project offers a JavaScript library to build an optimized
[Dockerfile](https://docs.docker.com/reference/builder/).

## Scope of the problem

We wanted to create a testable and a reproducible collection of docker images.
Dockerfile syntax offers a simple inheritance pattern, where a new image can begin
putting layers on top of the old image. We also wanted to create a continuous
delivery setup, where every built image would be tested and released.

Over the time we have realized that some fundamental docker design decisions
stop us from creating a truly flexible system:

* Dockerfiles are static, they can not be tuned dynamically to user's needs
* Image hierarchies do not support mixins and it is not easy to relocate the
hierarchy onto a different base image
* Image hierarchy has to be planned to account for all possible descendants -
if a descendant needs to change existing behavior it will create additional layers
* Many intermediate images were not directly usable, but generated significant clutter

Apparently, these are not docker issues. Rather, we perceived the tool wrongly.
After all, it was evident that the problem domain needs to be dealt with outside
of docker.

## Goals

* Generate a single optimized Dockerfile to build the final image from a published
base
* Minimize the number of layers by combining commands together (e.g. set multiple
  environment variables together)
* Do not create extra layers for conflicting commands (e.g. there may be only
  one working directory)
* Encapsulate best practices behind the API (e.g. sort list of installed packages
  alphabetically)
* Limited support for dependencies (e.g. add custom repository before installing
  the package)
* Simple customization
* Common context - all files to be added into the image are combined in a local
  context first and then copied in a single layer

These goals somewhat restrict certain fancy features. For instance, it would be
no longer possible to switch a user in one layer, run some commands and then switch
to another again.

## Workflow

User writes a script, where they consequently call functions to add commands to
a Dockerfile. Dockerfile along with context are returned in a `.tar` archive to
the user. User may review the result or pipe it directly into the build command.

Reusable parts of the Dockerfile can be separated into their own modules.

## Context management

User may add their own files to the container's filesystem. This is easy to optimize
by pre-making the context locally. This once again robs a user of some fanciness.

To manage a context we may have to commission a temporary folder or do it in
memory. We can use [tar-stream](https://www.npmjs.com/package/tar-stream) to keep
the context in memory.

`COPY` and `ADD` are commands, which modify the context. They do not accept multiple
source files/folders. They accept a single pathname or readable stream object.
`ADD` and `COPY` are different in how they handle archives. `ADD` will unpack the
contents under the destination path and `COPY` will copy it over. `ADD` with URL
source is not supported as it is discouraged by best practices guide.

## Dependencies

The commitment to support dependencies for proper ordering of Dockerfile commands
is a serious challenge. The tool must understand what is command's side-effect.

Arranging dependencies in order inside a single module is not so hard. Commands
can be chained by calling `next()` or `before()`. This will affect to commands
arrangement in the resulting Dockerfile.

## Command

A Dockerfile command is characterized with a following qualities:

* Combines - commands with the same keywords may be combined to one
* Overrides - a command with the same keyword will replace this command

A command, which does not combine nor it allows overriding, is a standalone
command. It may not be optimized and has to be added to the Dockerfile verbatim.
Combining commands requires some logic implemented and in the interim a command
may be standalone.

Standalone commands:

* `ADD`
* `COPY`

Combining commands:

* `RUN`
* `LABEL`
* `EXPOSE`
* `ENV`
* `VOLUME`

Overriding commands:

* `FROM`
* `MAINTAINER`
* `ENTRYPOINT`
* `USER`
* `WORKDIR`
* `CMD`

User has to be conscious about command overriding, i.e. to add a possibly overriding
command they must do it with `override()` function.

## Combinations

The engine will try to do its best to combine everything that can be combined.
Commands under the same keyword shall respect dependencies.

Example input (dependencies are commented):

```Dockerfile
RUN touch /etc/settings
RUN stat /etc/settings # the file must exist already
```

The output would be:

```Dockerfile
RUN touch /etc/settings && \
    stat /etc/settings
```

Dependencies with a different keyword will split combinations.

Example input:

```Dockerfile
RUN mkdir -p -m 0700 /etc/default
ADD settings /etc/default/ # Folder has to be created before a file is pushed
RUN stat /etc/default/settings
RUN touch /etc/other-settings
```

Results in:

```Dockerfile
RUN touch /etc/other-settings && \
    mkdir -p -m 0700 /etc/default
ADD settings /etc/default/
RUN stat /etc/default/settings
```


text:
#ifndef __SceneManagerEnumerator_H__
#define __SceneManagerEnumerator_H__

#include "OgrePrerequisites.h"

#include "OgreSceneManager.h"
#include "OgreSingleton.h"
#include "OgreHeaderPrefix.h"

namespace Ogre {

    /** \addtogroup Core
    *  @{
    */
    /** \addtogroup Scene
    *  @{
    */
    /// Factory for default scene manager
    class _OgreExport DefaultSceneManagerFactory : public SceneManagerFactory
    {
    protected:
        void initMetaData(void) const override;
    public:
        DefaultSceneManagerFactory() {}
        ~DefaultSceneManagerFactory() {}
        /// Factory type name
        static const String FACTORY_TYPE_NAME;
        SceneManager* createInstance(const String& instanceName) override;
    };

    /// Default scene manager
    class _OgreExport DefaultSceneManager : public SceneManager
    {
    public:
        DefaultSceneManager(const String& name);
        ~DefaultSceneManager();
        const String& getTypeName(void) const override;
    };

    /** Enumerates the SceneManager classes available to applications.

            As described in the SceneManager class, SceneManagers are responsible
            for organising the scene and issuing rendering commands to the
            RenderSystem. Certain scene types can benefit from different
            rendering approaches, and it is intended that subclasses will
            be created to special case this.
        @par
            In order to give applications easy access to these implementations,
            this class has a number of methods to create or retrieve a SceneManager
            which is appropriate to the scene type.
        @par
            SceneManagers are created by SceneManagerFactory instances. New factories
            for new types of SceneManager can be registered with this class to make
            them available to clients.
        @par
            Note that you can still plug in your own custom SceneManager without
            using a factory, should you choose, it's just not as flexible that way.
            Just instantiate your own SceneManager manually and use it directly.
    */
    class _OgreExport SceneManagerEnumerator : public Singleton<SceneManagerEnumerator>, public SceneMgtAlloc
    {
    public:
        /// Scene manager instances, indexed by instance name
        typedef std::map<String, SceneManager*> Instances;
        /// List of available scene manager types as meta data
        typedef std::vector<const SceneManagerMetaData*> MetaDataList;
    private:
        /// Scene manager factories
        typedef std::list<SceneManagerFactory*> Factories;
        Factories mFactories;
        Instances mInstances;
        /// Stored separately to allow iteration
        MetaDataList mMetaDataList;
        /// Factory for default scene manager
        DefaultSceneManagerFactory mDefaultFactory;
        /// Count of creations for auto-naming
        unsigned long mInstanceCreateCount;
        /// Currently assigned render system
        RenderSystem* mCurrentRenderSystem;

    public:
        SceneManagerEnumerator();
        ~SceneManagerEnumerator();

        /** Register a new SceneManagerFactory.

            Plugins should call this to register as new SceneManager providers.
        */
        void addFactory(SceneManagerFactory* fact);

        /** Remove a SceneManagerFactory.
        */
        void removeFactory(SceneManagerFactory* fact);

        /** Get more information about a given type of SceneManager.

            The metadata returned tells you a few things about a given type
            of SceneManager, which can be created using a factory that has been
            registered already.
        @param typeName The type name of the SceneManager you want to enquire on.
            If you don't know the typeName already, you can iterate over the
            metadata for all types using getMetaDataIterator.
        */
        const SceneManagerMetaData* getMetaData(const String& typeName) const;

        /** get all types of SceneManager available for construction

            providing some information about each one.
        */
        const MetaDataList& getMetaData() const { return mMetaDataList; }

        typedef ConstVectorIterator<MetaDataList> MetaDataIterator;
        /** Iterate over all types of SceneManager available for construction,
            providing some information about each one.
            @deprecated use getMetaData()
        */
        OGRE_DEPRECATED MetaDataIterator getMetaDataIterator(void) const;

        /** Create a SceneManager instance of a given type.

            You can use this method to create a SceneManager instance of a
            given specific type. You may know this type already, or you may
            have discovered it by looking at the results from getMetaDataIterator.
        @note
            This method throws an exception if the named type is not found.
        @param typeName String identifying a unique SceneManager type
        @param instanceName Optional name to given the new instance that is
            created. If you leave this blank, an auto name will be assigned.
        */
        SceneManager* createSceneManager(const String& typeName,
            const String& instanceName = BLANKSTRING);

        /// @deprecated typeMask is obsolete
        OGRE_DEPRECATED SceneManager* createSceneManager(uint16 typeMask,
            const String& instanceName = BLANKSTRING)
        { return createSceneManager(DefaultSceneManagerFactory::FACTORY_TYPE_NAME, instanceName); }

        /** Destroy an instance of a SceneManager. */
        void destroySceneManager(SceneManager* sm);

        /** Get an existing SceneManager instance that has already been created,
            identified by the instance name.
        @param instanceName The name of the instance to retrieve.
        */
        SceneManager* getSceneManager(const String& instanceName) const;

        /** Identify if a SceneManager instance already exists.
        @param instanceName The name of the instance to retrieve.
        */
        bool hasSceneManager(const String& instanceName) const;

        typedef MapIterator<Instances> SceneManagerIterator;
        /** Get an iterator over all the existing SceneManager instances.
        @deprecated use getSceneManagers() instead */
        OGRE_DEPRECATED SceneManagerIterator getSceneManagerIterator(void);

        /// Get all the existing SceneManager instances.
        const Instances& getSceneManagers() const;

        /** Notifies all SceneManagers of the destination rendering system.
        */
        void setRenderSystem(RenderSystem* rs);

        /// Utility method to control shutdown of the managers
        void shutdownAll(void);
        /// @copydoc Singleton::getSingleton()
        static SceneManagerEnumerator& getSingleton(void);
        /// @copydoc Singleton::getSingleton()
        static SceneManagerEnumerator* getSingletonPtr(void);

    };

    /** @} */
    /** @} */

}

#include "OgreHeaderSuffix.h"

#endif


text:
package org.webrtc;

public interface CameraEnumerator {
  public String[] getDeviceNames();
  public boolean isFrontFacing(String deviceName);
  public boolean isBackFacing(String deviceName);

  public CameraVideoCapturer createCapturer(String deviceName,
      CameraVideoCapturer.CameraEventsHandler eventsHandler);
}


text:
#region License Terms

// ================================================================================
// RosSharp
//
// Software License Agreement (BSD License)
//
// Copyright (C) 2012 zoetrope
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ================================================================================

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;

namespace RosSharp.Parameter
{
    /// <summary>
    ///   XML-RPC Client for ParameterServer API
    /// </summary>
    public sealed class ParameterServerClient
    {
        private ParameterServerProxy _proxy;

        public ParameterServerClient(Uri uri)
        {
            _proxy = new ParameterServerProxy();
            _proxy.Url = uri.ToString();
            _proxy.Timeout = Ros.XmlRpcTimeout;
        }

        /// <summary>
        ///   Delete parameter
        /// </summary>
        /// <param name="callerId"> ROS caller ID </param>
        /// <param name="key"> Parameter name. </param>
        /// <returns> ignore </returns>
        public Task DeleteParamAsync(string callerId, string key)
        {
            return Task<object[]>.Factory.FromAsync(_proxy.BeginDeleteParam, _proxy.EndDeleteParam, callerId, key, null)
                .ContinueWith(task => { if ((StatusCode) task.Result[0] != StatusCode.Success) throw new InvalidOperationException((string) task.Result[1]); });
        }

        /// <summary>
        ///   Set parameter.
        /// </summary>
        /// <param name="callerId"> ROS caller ID </param>
        /// <param name="key"> Parameter name. </param>
        /// <param name="value"> Parameter value. </param>
        /// <returns> ignore </returns>
        public Task SetParamAsync(string callerId, string key, object value)
        {
            return Task<object[]>.Factory.FromAsync(_proxy.BeginSetParam, _proxy.EndSetParam, callerId, key, value, null)
                .ContinueWith(task => { if ((StatusCode) task.Result[0] != StatusCode.Success) throw new InvalidOperationException((string) task.Result[1]); });
        }

        /// <summary>
        ///   Retrieve parameter value from server.
        /// </summary>
        /// <param name="callerId"> ROS caller ID </param>
        /// <param name="key"> Parameter name. If key is a namespace, getParam() will return a parameter tree. </param>
        /// <returns> parameterValue </returns>
        public Task<object> GetParamAsync(string callerId, string key)
        {
            return Task<object[]>.Factory.FromAsync(_proxy.BeginGetParam, _proxy.EndGetParam, callerId, key, null)
                .ContinueWith(task =>
                {
                    if ((StatusCode) task.Result[0] != StatusCode.Success) throw new InvalidOperationException((string) task.Result[1]);
                    return task.Result[2];
                });
        }

        /// <summary>
        ///   Search for parameter key on the Parameter Server.
        /// </summary>
        /// <param name="callerId"> ROS caller ID </param>
        /// <param name="key"> Parameter name to search for. </param>
        /// <returns> foundKey </returns>
        public Task<string> SearchParamAsync(string callerId, string key)
        {
            return Task<object[]>.Factory.FromAsync(_proxy.BeginSearchParam, _proxy.EndSearchParam, callerId, key, null)
                .ContinueWith(task =>
                {
                    if ((StatusCode) task.Result[0] != StatusCode.Success) throw new InvalidOperationException((string) task.Result[1]);
                    return (string) task.Result[2];
                });
        }

        /// <summary>
        ///   Retrieve parameter value from server and subscribe to updates to that param. See paramUpdate() in the Node API.
        /// </summary>
        /// <param name="callerId"> ROS caller ID. </param>
        /// <param name="callerApi"> Node API URI of subscriber for paramUpdate callbacks. </param>
        /// <param name="key"> Parameter name </param>
        /// <returns> parameterValue </returns>
        public Task<object> SubscribeParamAsync(string callerId, Uri callerApi, string key)
        {
            return Task<object[]>.Factory.FromAsync(_proxy.BeginSubscribeParam, _proxy.EndSubscribeParam, callerId, callerApi.ToString(), key, null)
                .ContinueWith(task =>
                {
                    if ((StatusCode) task.Result[0] != StatusCode.Success) throw new InvalidOperationException((string) task.Result[1]);
                    return task.Result[2];
                });
        }

        /// <summary>
        ///   Retrieve parameter value from server and subscribe to updates to that param. See paramUpdate() in the Node API.
        /// </summary>
        /// <param name="callerId"> ROS caller ID. </param>
        /// <param name="callerApi"> Node API URI of subscriber. </param>
        /// <param name="key"> Parameter name. </param>
        /// <returns> number of unsubscribed </returns>
        public Task<int> UnsubscribeParamAsync(string callerId, Uri callerApi, string key)
        {
            return Task<object[]>.Factory.FromAsync(_proxy.BeginUnsubscribeParam, _proxy.EndUnsubscribeParam, callerId, callerApi.ToString(), key, null)
                .ContinueWith(task =>
                {
                    if ((StatusCode) task.Result[0] != StatusCode.Success) throw new InvalidOperationException((string) task.Result[1]);
                    return (int) task.Result[2];
                });
        }

        /// <summary>
        ///   Check if parameter is stored on server.
        /// </summary>
        /// <param name="callerId"> ROS caller ID. </param>
        /// <param name="key"> Parameter name. </param>
        /// <returns> hasParam </returns>
        public Task<bool> HasParamAsync(string callerId, string key)
        {
            return Task<object[]>.Factory.FromAsync(_proxy.BeginHasParam, _proxy.EndHasParam, callerId, key, null)
                .ContinueWith(task =>
                {
                    if ((StatusCode) task.Result[0] != StatusCode.Success) throw new InvalidOperationException((string) task.Result[1]);
                    return (bool) task.Result[2];
                });
        }

        /// <summary>
        ///   Get list of all parameter names stored on this server.
        /// </summary>
        /// <param name="callerId"> ROS caller ID. </param>
        /// <returns> parameter name list </returns>
        public Task<List<string>> GetParamNamesAsync(string callerId)
        {
            return Task<object[]>.Factory.FromAsync(_proxy.BeginGetParamNames, _proxy.EndGetParamNames, callerId, null)
                .ContinueWith(task =>
                {
                    if ((StatusCode) task.Result[0] != StatusCode.Success) throw new InvalidOperationException((string) task.Result[1]);
                    return ((string[]) task.Result[2]).ToList();
                });
        }
    }
}