text:
/**
 * Created by madcat on 10/28/15.
 *
 * The Turing Enumerable module.
 *
 * This is bound to DOM objects:
 *
 *     global('p').each(function() {
 *       // `this` contains a DOM element
 *     });
 *
 */
define('xo.enumerable', ['xo.core'], function(xo){

    function EnumerableModule(global) {
        global.enumerable = {
            /**
             * Throw to break out of iterators
             * */
            Break : {},

            /**
             * Iterators using a function over a set of items. Example :
             *
             *  xo.enumerable.each([1,2,3], function(n){
             *   console.debug(n);
             *  });
             *
             * @param {Object} enumerable A set of items that responds to `length`
             * @param {Function} callback The function to run
             * @param {Object} [context] An optional parameter to determine `this` in the callback
             * @returns {Object} The passed in enumerable object
             *
             */
            each : function(enumerable, callback, context){
                var hasOwnProperty = Object.prototype.hasOwnProperty;

                try {
                    if(Array.prototype.forEach && enumerable.forEach === Array.prototype.forEach) {
                        enumerable.forEach(callback, context);
                    } else if (global.isNumer(enumerable.length)) {
                        for(var i = 0; i < enumerable.length; i++) {
                            callback.call(enumerable, enumerable[i], i, enumerable);
                        }
                    } else {
                        for( var key in enumerable) {
                            if(hasOwnProperty.call(enumerable, key)) {
                                callback.call(context, enumerable[key], key, enumerable);
                            }
                        }
                    }
                } catch (e) {
                    if(e != global.enumerable.Break)
                        throw e;
                }
                return enumerable;
            },

            /***
             * Changes a set of item using a function. Example:
             *
             * xo.enumerable.map([1, 2, 3], function(n) {
             *  return n + 1;
             * }); // => [2,3,4]
             *
             * @param enumerable A set of items that responds to `length`
             * @param callback The function to run over each item
             * @param context An optional parameter to determine `this` in the callback
             * @returns {Array} The changed items
             */
            map : function(enumerable, callback, context) {
                if(Array.prototype.map && enumerable.map === Array.prototype.map)
                    return enumerable.map(callback, context);
                var results = [];

                global.enumerable.each(enumerable, function(value, index, list){
                   results.push(callback.call(context, value, index, list));
                });

                return results;
            },

            /**
             * Removes items based on a callback :
             *
             *  var a = [1, 2, 3, 4, 5, 6];
             *  xo.enumerable.filter(a, function(n){
             *      return n % 2 === 0;
             *  });
             *
             *  => [2, 4, 6];
             *
             * @param enumerable A set of items that responds to `length`
             * @param callback The function to run over each item
             * @param context An optional parameter to determine `this` in the callback
             * @returns {Array} The filtered items
             */
            filter : function(enumerable, callback, context) {
                if(Array.prototype.filter && enumerable.filter === Array.prototype.filter)
                    return enumerable.filter(callback, context);

                var results = [],
                    pushIndex = !global.isArray(enumerable);

                global.enumerable.each(enumerable, function(value, index, list){
                    if(callback.call(context, value, index, list)){
                        if(pushIndex) {
                            results.push([index, value]);
                        } else {
                            results.push(value);
                        }
                    }
                });
                return results;
            },

            /**
             * The opposite of filter :
             *
             *  var a = [1, 2, 3, 4, 5, 6, 7, 8];
             *  xo.enumerable.reject(a, function(n){
             *      return n % 2 === 0;
             *  });
             *
             *  => [1, 3, 5, 7]
             *
             *
             * @param enumerable A set of items that responds to `length`
             * @param callback The function to run over each item
             * @param context An optional parameter to determine `this` in the callback
             * @returns {*|Array} The rejected items
             */
            reject : function(enumerable, callback, context) {
                return this.filter(enumerable, function(){
                    return !callback.apply(context, arguments);
                }, context);
            },

            /**
             * Find a single item :
             *
             *  var a = [1, 2, 3, 4, 5, 6, 7, 8];
             *  xo.enumerable.detect(a, function(n){
             *      return n === 3;
             *  });
             *
             *  => 3
             *
             *
             * @param enumerable A set of items that responds to `length`
             * @param callback The function to run over each item
             * @param context An optional parameter to determine `this` in the callback
             * @returns {Object} The item (if found)
             */
            detect : function(enumerable, callback, context) {
                var result;
                global.enumerable.each(enumerable, function(value, index, list){
                    if(callback.call(context, value, index, list)) {
                        result = value;
                        throw global.enumerable.Break;
                    }
                });

                return result;
            },

            /**
             * Runs a function over each item, collecting the results:
             *
             *  var a = [1, 2, 3, 4, 5, 6, 7, 8];
             *  xo.enumerable.reduce(a, 0, function(memo, n) {
             *      return memo + n;
             *  });
             *
             *  => 36
             *
             * @param enumerable
             * @param memo
             * @param callback
             * @param context
             * @returns {*}
             */
            reduce : function(enumerable, memo, callback, context) {
                if(Array.prototype.reduce && enumerable.reduce === Array.prototype.reduce)
                    return enumerable.reduce(global.bind(callback, context),memo);

                global.enumerable.each(enumerable, function(value, index, list){
                    memo = callback.call(context, memo, value, index, list);
                });

                return memo;
            },

            /**
             * Flattens multidimensional arrays:
             *
             *   var a = [[2, 4], [[6], 8]];
             *   xo.enumerable.flatten(a);
             *
             *   => [2, 4, 6, 8]
             *
             * @param {Object} enumerable A set of items that responds to `length`
             * @returns {Object} The flat array
             */
            flatten : function(array) {
                return global.enumerable.reduce(array, [], function(memo, value){
                    if(global.isArray(value))
                        return memo.concat(global.enumerable.flatten(value));

                    memo.push(value);
                    return memo;
                });
            },

            /**
             * Return the last item from a list
             *
             *  xo.enumerable.tail([1, 2, 3, 4, 5, 6], 3);
             *  => [4, 5, 6]
             *
             * @param {Object} enumerable A set of items that responds to `length`
             * @param {Number} start The index of the item to 'cut' the array
             * @returns {Array.<T>} A list of items
             */
            tail : function(enumerable, start) {
                start = typeof start === 'undefined' ? 1 : start;

                return Array.prototype.slice.apply(enumerable, [start]);
            },

            /**
             * Invokes `method` on a list of item:
             *  xo.enumerable.invoke(['hello','world'], 'substring', 0, 3);
             *  => ['hel', 'wor']
             *
             * @param enumerable
             * @param {Function} method The method to invoke on each item
             * @returns {Object} The changed list
             */
            invoke : function(enumerable, method) {
                var args = global.enumerable.tail(arguments, 2);

                return global.enumerable.map(enumerable, function(value) {
                    return (method ? value[method] : value).apply(value, args);
                });
            },

            /**
             * Pluck a property from each item of a list
             *
             *  xo.enumerable.pluck(['hello', 'world'], 'length');
             *  => [5, 5]
             *
             * @param enumerable A set of items that responds to `length`
             * @param {String} key The property to pluck
             * @returns {*|Array} The plucked properties
             */
            pluck : function(enumerable, key) {
                return global.enumerable.map(enumerable, function(value){
                    return value[key];
                });
            },

            /**
             * Determines if a list matches some items based on a callback:
             *
             *      xo.enumerable.some([1, 2, 3], function(value) {
             *        return value === 3;
             *      });
             *
             *      => true
             *
             * @param {Object} enumerable A set of items that responds to `length`
             * @param {Function} callback A function to run against each item
             * @param {Object} [context] An optional parameter to determine `this` in the callback
             * @returns {Boolean} True if an item was matched
             */
            some : function(enumerable, callback, context) {
                callback = callback || global.enumerable.identity;

                if(Array.prototype.some && enumerable.some === Array.prototype.some)
                    return enumerable.some(callback, context);

                var result = false;
                global.enumerable.each(enumerable, function(value, index, list){
                    if(result = callback.call(context, value, index, list)){
                        throw global.enumerable.Break;
                    }
                });

                return result;
            },

            /**
             * Checks if all items match the callback:
             *
             *      xo.enumerable.all([1, 2, 3], function(value) {
             *        return value < 4;
             *      })
             *
             *      => true
             *
             * @param {Object} enumerable A set of items that responds to `length`
             * @param {Function} callback A function to run against each item
             * @param {Object} [context] An optional parameter to determine `this` in the callback
             * @returns {Boolean} True if all items match
             */
            all : function(enumerable, callback, context) {
                callback = callback || global.enumerable.identity;
                if(Array.prototype.all && enumerable.prototype.all === Array.prototype.all)
                    return enumerable.all(callback, context);

                var result = true;
                global.enumerable.each(enumerable, function(value, index, list){
                    if(!(result = callback.call(context, value, index, list))) {
                        throw global.enumerable.Break;
                    }
                });

                return result;
            },

            /**
             * Checks if one item matches a value:
             *
             *      xo.enumerable.include([1, 2, 3], 3);
             *
             *      => true
             *
             * @param {Object} enumerable A set of items that responds to `length`
             * @param {Object} target A value to find
             * @returns {Boolean} True if an item was found
             */
            include : function(enumerable, target) {
                if(Array.prototype.indexOf && enumerable.indexOf === Array.prototype.indexOf)
                    return enumerable.indexOf(target) != -1;

                var found = false;
                global.enumerable.each(enumerable, function(value, key) {
                    if(found = value === target){
                        throw global.enumerable.Break;
                    }
                });

                return found;
            },

            /**
             * Chain enumerable calls:
             *
             *      xo.enumerable.chain([1, 2, 3, 4])
             *        .filter(function(n) { return n % 2 == 0; })
             *        .map(function(n) { return n * 10; })
             *        .values();
             *
             *      => [20, 40]
             *
             * @param {Object} enumerable A set of items that responds to `length`
             * @returns {Object} The chained enumerable API
             */
            chain: function(enumerable) {
                return new global.enumerable.Chainer(enumerable);
            },

            identity : function(value) {
                return value;
            }
        }; // end enumerable object

        /**
         *  Aliases
         */

        global.enumerable.select = global.enumerable.filter;
        global.enumerable.collect = global.enumerable.map;
        global.enumerable.inject = global.enumerable.reduce;
        global.enumerable.rest = global.enumerable.tail;
        global.enumerable.any = global.enumerable.some;
        global.enumerable.every = global.enumerable.all;

        global.chainableMethods = ['map', 'collect', 'detect', 'filter', 'reduce', 'each',
                                    'tail', 'rest', 'reject', 'plunk', 'any', 'some', 'all'];

        /**
         *  Chainer class
         */
        global.enumerable.Chainer = function(values){
            this.results = values;
        };

        global.enumerable.Chainer.prototype.values = function(){
            return this.results;
        };

        // Map selected methods by wrapping them in a closure that returns this each time
        global.enumerable.each(global.chainableMethods, function(methodName) {
            var method = global.enumerable[methodName];
            global.enumerable.Chainer.prototype[methodName] = function() {
                var args = Array.prototype.slice.call(arguments);
                args.unshift(this.results);

                this.results = method.apply(this, args);

                return this;
            };
        });

        global.init(function(arg){
            if(arg.hasOwnProperty.length && typeof arg !== 'string') {
                return global.enumerable.chain(arg);
            }
        });
    } // end EnumerableModule

    if(typeof module !== 'undefined') {
        module.exports = function(t){
            return EnumerableModule(t);
        }
    } else {
        EnumerableModule(xo);
    }
});


text:
package com.hss01248.net.interfaces;

import com.hss01248.net.config.ConfigInfo;

import java.util.Map;

import okhttp3.CookieJar;

/**
 * Created by huangshuisheng on 2017/9/28.
 */

public interface ValidateStrategy {

    void addToken(String token, Map<String,String> headers, Map<String,String> params, CookieJar cookieJar);

    void reLogin(ConfigInfo info);
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

      <meta charset="utf-8">
      <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      <link type="text/css" rel="stylesheet" href="css/materialize.css"
        media="screen,projection"/>
      <link rel="stylesheet" href="css/experio.css">
      <title>xperio/restablecer</title>

      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

                <input id="correo" type="text" class="validate">
                Ingresa tu correo

              Solicitar

REESTABLECER CONTRASEÑA

                <input id="password2" type="password" class="validate">
                Nueva Contraseña

                <input id="password3" type="password" class="validate">
                Confirma Contraseña

              Reestablecer


text:
USE [Koski_SA]
GO

DROP PROCEDURE IF EXISTS [sa].[p_lataa_ammatillisen_koulutuksen_sopimusjaksot_siivottu]
GO

/****** Object:  StoredProcedure [sa].[p_lataa_ammatillisen_koulutuksen_sopimusjaksot_siivottu]    Script Date: 14.12.2020 16:42:26 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [sa].[p_lataa_ammatillisen_koulutuksen_sopimusjaksot_siivottu] AS

DROP TABLE IF EXISTS Koski_SA.sa.sa_ammatillisen_koulutuksen_sopimusjaksot_siivottu_valitaulu
DROP TABLE IF EXISTS Koski_SA.sa.sa_ammatillisen_koulutuksen_sopimusjaksot_siivottu

SELECT DISTINCT id = ROW_NUMBER() over (order by opiskeluoikeus_oid, sopimusmuoto, alku, loppu, ytunnus, sijainti)
	,opiskeluoikeus_oid
	,sopimusmuoto
	,alku
	,loppu
	,ytunnus
	,sijainti
INTO Koski_SA.sa.sa_ammatillisen_koulutuksen_sopimusjaksot_siivottu_valitaulu

FROM(
SELECT DISTINCT *
	   ,rnk_ytunnus =
	    RANK() OVER (PARTITION BY opiskeluoikeus_oid, sopimusmuoto, alku, loppu, ytunnus ORDER BY sijainti DESC)
	   ,rnk_poimintatapa =
		RANK() OVER (PARTITION BY opiskeluoikeus_oid, sopimusmuoto, alku, loppu ORDER BY ytunnus DESC)
	FROM (
	SELECT DISTINCT [opiskeluoikeus_oid]
		  ,sopimusmuoto =
				CASE
					WHEN sopimusmuoto = 'Koulutuksen järjestäminen oppisopimuskoulutuksena' THEN 'Oppisopimus'
					ELSE sopimusmuoto
					END
		  ,[alku]
		  ,[loppu]
		  ,[sijainti]
		  ,[ytunnus]
	  FROM [Koski_SA].[sa].[sa_koski_ammatillisen_koulutuksen_sopimusjaksot]
	  WHERE sopimusmuoto NOT IN ('Oppilaitosmuotoinen koulutus', 'Koulutuksen järjestäminen oppilaitosmuotoisena')) q) q2
WHERE NOT(ytunnus IS NULL AND rnk_poimintatapa != 1)
	AND NOT(rnk_ytunnus != 1 AND sijainti IS NULL)

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT DISTINCT
	id,
	opiskeluoikeus_oid,
	alku = sj_alku,
	loppu = sj_loppu,
	sopimusmuoto,
	ytunnus,
	sijainti,
	paivat,
	paivat_tarkastettu = SUM(paivat_tarkastettu)
INTO [Koski_SA].[sa].[sa_ammatillisen_koulutuksen_sopimusjaksot_siivottu]
FROM(
SELECT
	id,
	opiskeluoikeus_oid,
	sj_alku,
	sj_loppu,
	sopimusmuoto,
	ytunnus,
	sijainti,
	paivat = DATEDIFF(D, sj_alku, sj_loppu),
	paivat_tarkastettu = DATEDIFF(D, sop_alku, sop_loppu)
FROM(
SELECT sj.[opiskeluoikeus_oid]
      ,[sopimusmuoto]
	  ,id
      ,sj_alku = sj.[alku]
      ,sj_loppu = sj.[loppu]
	  ,ooa_alku = ooa.alku
	  ,ooa_loppu = ooa.loppu
	  ,sop_alku =
		CASE
			WHEN ooa.alku > sj.alku THEN ooa.alku
			WHEN ooa.alku <= sj.alku THEN sj.alku
			ELSE NULL END
	  ,sop_loppu =
		CASE
			WHEN ooa.loppu > sj.loppu THEN sj.loppu
			WHEN ooa.loppu <= sj.loppu THEN ooa.loppu
			ELSE NULL END
      ,[ytunnus]
      ,[sijainti]
  FROM [Koski_SA].[sa].[sa_ammatillisen_koulutuksen_sopimusjaksot_siivottu_valitaulu] sj
  LEFT JOIN Koski_SA.sa.sa_koski_opiskeluoikeus oo ON oo.opiskeluoikeus_oid = sj.opiskeluoikeus_oid
  LEFT JOIN Koski_SA.sa.sa_koski_opiskeluoikeus_aikajakso ooa
	ON sj.opiskeluoikeus_oid = ooa.opiskeluoikeus_oid
		AND ooa.alku <= sj.loppu
		AND ooa.loppu >= sj.alku
	WHERE ooa.tila IN ('lasna', 'loma', 'valmistunut')) q) q2
GROUP BY
	id,
	opiskeluoikeus_oid,
	sj_alku,
	sj_loppu,
	sopimusmuoto,
	ytunnus,
	sijainti,
	paivat

DROP TABLE IF EXISTS Koski_SA.sa.sa_ammatillisen_koulutuksen_sopimusjaksot_siivottu_valitaulu

GO

USE ANTERO


text:
package com.monitor.dao;

import java.sql.ResultSet;
import java.util.ArrayList;

public interface UnitType_functionDAO {

	//查询数据库中unitType表,并将表中所有数据表记录返回
	public abstract String[] findUnitType();

	//通过参数单元类型unitTypeName和int unitTypeID,访问数据库表返回符合条件的记录
	public abstract String[] searchUnitType(String unitTypeID, String unitTypeName);

	//通过参数单元类型ID号unitTypeID,修改数据库中符合条件的记录相应字段改为newUnitTypeName
	public abstract boolean changeUnitType(String unitTypeID, String newUnitTypeName);

	//通过参数单元类型ID号unitTypeID,删除数据库中符合条件的记录
	public abstract boolean delUnitType(String unitTypeID);

	//通过参数单元类型名称unitTypeNameS,向数据库unitType表中增加一条记录
	public abstract boolean addUnitType(String unitTypeNameS);
}


text:
package v7_test

import (
	"errors"
	"time"

	"code.cloudfoundry.org/cli/actor/actionerror"
	"code.cloudfoundry.org/cli/actor/v7action"
	"code.cloudfoundry.org/cli/api/cloudcontroller/ccv3/constant"
	"code.cloudfoundry.org/cli/command/commandfakes"
	"code.cloudfoundry.org/cli/command/translatableerror"
	. "code.cloudfoundry.org/cli/command/v7"
	"code.cloudfoundry.org/cli/command/v7/v7fakes"
	"code.cloudfoundry.org/cli/integration/helpers"
	"code.cloudfoundry.org/cli/resources"
	"code.cloudfoundry.org/cli/types"
	"code.cloudfoundry.org/cli/util/configv3"
	"code.cloudfoundry.org/cli/util/ui"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
)

var _ = Describe("scale Command", func() {
	var (
		cmd             ScaleCommand
		input           *Buffer
		output          *Buffer
		testUI          *ui.UI
		fakeConfig      *commandfakes.FakeConfig
		fakeSharedActor *commandfakes.FakeSharedActor
		fakeActor       *v7fakes.FakeActor
		app             resources.Application
		binaryName      string
		executeErr      error
	)

	BeforeEach(func() {
		input = NewBuffer()
		output = NewBuffer()
		testUI = ui.NewTestUI(input, output, NewBuffer())
		fakeConfig = new(commandfakes.FakeConfig)
		fakeSharedActor = new(commandfakes.FakeSharedActor)
		fakeActor = new(v7fakes.FakeActor)
		app = resources.Application{Name: "some-app", GUID: "some-app-guid"}

		cmd = ScaleCommand{
			BaseCommand: BaseCommand{
				UI:          testUI,
				Config:      fakeConfig,
				SharedActor: fakeSharedActor,
				Actor:       fakeActor,
			},
		}

		binaryName = "faceman"
		fakeConfig.BinaryNameReturns(binaryName)

		cmd.RequiredArgs.AppName = app.Name
		cmd.ProcessType = constant.ProcessTypeWeb
	})

	JustBeforeEach(func() {
		executeErr = cmd.Execute(nil)
	})

	When("checking target fails", func() {
		BeforeEach(func() {
			fakeSharedActor.CheckTargetReturns(actionerror.NotLoggedInError{BinaryName: binaryName})
		})

		It("returns an error", func() {
			Expect(executeErr).To(MatchError(actionerror.NotLoggedInError{BinaryName: binaryName}))

			Expect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))
			checkTargetedOrg, checkTargetedSpace := fakeSharedActor.CheckTargetArgsForCall(0)
			Expect(checkTargetedOrg).To(BeTrue())
			Expect(checkTargetedSpace).To(BeTrue())
		})
	})

	When("the user is logged in, and org and space are targeted", func() {
		BeforeEach(func() {
			fakeConfig.HasTargetedOrganizationReturns(true)
			fakeConfig.TargetedOrganizationReturns(configv3.Organization{Name: "some-org"})
			fakeConfig.HasTargetedSpaceReturns(true)
			fakeConfig.TargetedSpaceReturns(configv3.Space{
				GUID: "some-space-guid",
				Name: "some-space"})
			fakeActor.GetCurrentUserReturns(
				configv3.User{Name: "some-user"},
				nil)
		})

		When("getting the current user returns an error", func() {
			var expectedErr error

			BeforeEach(func() {
				expectedErr = errors.New("getting current user error")
				fakeActor.GetCurrentUserReturns(
					configv3.User{},
					expectedErr)
			})

			It("returns the error", func() {
				Expect(executeErr).To(MatchError(expectedErr))
			})
		})

		When("the application does not exist", func() {
			BeforeEach(func() {
				fakeActor.GetApplicationByNameAndSpaceReturns(
					resources.Application{},
					v7action.Warnings{"get-app-warning"},
					actionerror.ApplicationNotFoundError{Name: app.Name})
			})

			It("returns an ApplicationNotFoundError and all warnings", func() {
				Expect(executeErr).To(Equal(actionerror.ApplicationNotFoundError{Name: app.Name}))

				Expect(testUI.Out).ToNot(Say("Showing | Scaling"))
				Expect(testUI.Err).To(Say("get-app-warning"))

				Expect(fakeActor.GetApplicationByNameAndSpaceCallCount()).To(Equal(1))
				appNameArg, spaceGUIDArg := fakeActor.GetApplicationByNameAndSpaceArgsForCall(0)
				Expect(appNameArg).To(Equal(app.Name))
				Expect(spaceGUIDArg).To(Equal("some-space-guid"))
			})
		})

		When("an error occurs getting the application", func() {
			var expectedErr error

			BeforeEach(func() {
				expectedErr = errors.New("get app error")
				fakeActor.GetApplicationByNameAndSpaceReturns(
					resources.Application{},
					v7action.Warnings{"get-app-warning"},
					expectedErr)
			})

			It("returns the error and displays all warnings", func() {
				Expect(executeErr).To(Equal(expectedErr))
				Expect(testUI.Err).To(Say("get-app-warning"))
			})
		})

		When("the application exists", func() {
			var appSummary v7action.DetailedApplicationSummary

			BeforeEach(func() {
				appSummary = v7action.DetailedApplicationSummary{
					ApplicationSummary: v7action.ApplicationSummary{
						ProcessSummaries: v7action.ProcessSummaries{
							{
								Process: resources.Process{
									Type:              constant.ProcessTypeWeb,
									MemoryInMB:        types.NullUint64{Value: 32, IsSet: true},
									DiskInMB:          types.NullUint64{Value: 1024, IsSet: true},
									LogRateLimitInBPS: types.NullInt{Value: 1024 * 10, IsSet: true},
								},
								InstanceDetails: []v7action.ProcessInstance{
									v7action.ProcessInstance{
										Index:        0,
										State:        constant.ProcessInstanceRunning,
										MemoryUsage:  1000000,
										DiskUsage:    1000000,
										LogRate:      1024 * 5,
										MemoryQuota:  33554432,
										DiskQuota:    2000000,
										LogRateLimit: 1024 * 10,
										Uptime:       time.Since(time.Unix(267321600, 0)),
									},
									v7action.ProcessInstance{
										Index:        1,
										State:        constant.ProcessInstanceRunning,
										MemoryUsage:  2000000,
										DiskUsage:    2000000,
										LogRate:      1024 * 3,
										MemoryQuota:  33554432,
										DiskQuota:    4000000,
										LogRateLimit: 1024 * 10,
										Uptime:       time.Since(time.Unix(330480000, 0)),
									},
									v7action.ProcessInstance{
										Index:        2,
										State:        constant.ProcessInstanceRunning,
										MemoryUsage:  3000000,
										DiskUsage:    3000000,
										LogRate:      1024 * 4,
										MemoryQuota:  33554432,
										DiskQuota:    6000000,
										LogRateLimit: 1024 * 10,
										Uptime:       time.Since(time.Unix(1277164800, 0)),
									},
								},
							},
							{
								Process: resources.Process{
									Type:              "console",
									MemoryInMB:        types.NullUint64{Value: 16, IsSet: true},
									DiskInMB:          types.NullUint64{Value: 512, IsSet: true},
									LogRateLimitInBPS: types.NullInt{Value: 1024 * 5, IsSet: true},
								},
								InstanceDetails: []v7action.ProcessInstance{
									v7action.ProcessInstance{
										Index:        0,
										State:        constant.ProcessInstanceRunning,
										MemoryUsage:  1000000,
										DiskUsage:    1000000,
										LogRate:      1024,
										MemoryQuota:  33554432,
										DiskQuota:    8000000,
										LogRateLimit: 1024 * 5,
										Uptime:       time.Since(time.Unix(167572800, 0)),
									},
								},
							},
						},
					},
				}

				fakeActor.GetApplicationByNameAndSpaceReturns(
					app,
					v7action.Warnings{"get-app-warning"},
					nil)
			})

			When("no flag options are provided", func() {
				BeforeEach(func() {
					fakeActor.GetDetailedAppSummaryReturns(
						appSummary,
						v7action.Warnings{"get-app-summary-warning"},
						nil)
				})

				It("displays current scale properties and all warnings", func() {
					Expect(executeErr).ToNot(HaveOccurred())

					Expect(testUI.Out).To(Say(`Showing current scale of app some-app in org some-org / space some-space as some-user\.\.\.`))
					Expect(testUI.Out).ToNot(Say("Scaling | This will cause the app to restart | Stopping | Starting | Waiting"))

					firstAppTable := helpers.ParseV3AppProcessTable(output.Contents())
					Expect(len(firstAppTable.Processes)).To(Equal(2))

					webProcessSummary := firstAppTable.Processes[0]
					Expect(webProcessSummary.Type).To(Equal("web"))
					Expect(webProcessSummary.InstanceCount).To(Equal("3/3"))
					Expect(webProcessSummary.MemUsage).To(Equal("32M"))

					Expect(webProcessSummary.Instances[0].Memory).To(Equal("976.6K of 32M"))
					Expect(webProcessSummary.Instances[0].Disk).To(Equal("976.6K of 1.9M"))
					Expect(webProcessSummary.Instances[0].CPU).To(Equal("0.0%"))
					Expect(webProcessSummary.Instances[0].LogRate).To(Equal("5K/s of 10K/s"))

					Expect(webProcessSummary.Instances[1].Memory).To(Equal("1.9M of 32M"))
					Expect(webProcessSummary.Instances[1].Disk).To(Equal("1.9M of 3.8M"))
					Expect(webProcessSummary.Instances[1].CPU).To(Equal("0.0%"))
					Expect(webProcessSummary.Instances[1].LogRate).To(Equal("3K/s of 10K/s"))

					Expect(webProcessSummary.Instances[2].Memory).To(Equal("2.9M of 32M"))
					Expect(webProcessSummary.Instances[2].Disk).To(Equal("2.9M of 5.7M"))
					Expect(webProcessSummary.Instances[2].CPU).To(Equal("0.0%"))
					Expect(webProcessSummary.Instances[2].LogRate).To(Equal("4K/s of 10K/s"))

					consoleProcessSummary := firstAppTable.Processes[1]
					Expect(consoleProcessSummary.Type).To(Equal("console"))
					Expect(consoleProcessSummary.InstanceCount).To(Equal("1/1"))
					Expect(consoleProcessSummary.MemUsage).To(Equal("16M"))

					Expect(consoleProcessSummary.Instances[0].Memory).To(Equal("976.6K of 32M"))
					Expect(consoleProcessSummary.Instances[0].Disk).To(Equal("976.6K of 7.6M"))
					Expect(consoleProcessSummary.Instances[0].CPU).To(Equal("0.0%"))
					Expect(consoleProcessSummary.Instances[0].LogRate).To(Equal("1K/s of 5K/s"))

					Expect(testUI.Err).To(Say("get-app-warning"))
					Expect(testUI.Err).To(Say("get-app-summary-warning"))

					Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(0))
				})

				When("an error is encountered getting process information", func() {
					var expectedErr error

					BeforeEach(func() {
						expectedErr = errors.New("get process error")
						fakeActor.GetDetailedAppSummaryReturns(
							v7action.DetailedApplicationSummary{},
							v7action.Warnings{"get-process-warning"},
							expectedErr,
						)
					})

					It("returns the error and displays all warnings", func() {
						Expect(executeErr).To(Equal(expectedErr))
						Expect(testUI.Err).To(Say("get-process-warning"))
					})
				})
			})

			When("all flag options are provided", func() {
				BeforeEach(func() {
					cmd.Instances.Value = 2
					cmd.Instances.IsSet = true
					cmd.DiskLimit.Value = 50
					cmd.DiskLimit.IsSet = true
					cmd.MemoryLimit.Value = 100
					cmd.MemoryLimit.IsSet = true
					cmd.LogRateLimit.Value = 1024
					cmd.LogRateLimit.IsSet = true
					fakeActor.ScaleProcessByApplicationReturns(
						v7action.Warnings{"scale-warning"},
						nil)
					fakeActor.GetDetailedAppSummaryReturns(
						appSummary,
						v7action.Warnings{"get-instances-warning"},
						nil)
				})

				When("force flag is not provided", func() {
					When("the user chooses default", func() {
						BeforeEach(func() {
							_, err := input.Write([]byte("\n"))
							Expect(err).ToNot(HaveOccurred())
						})

						It("does not scale the app", func() {
							Expect(executeErr).ToNot(HaveOccurred())

							Expect(testUI.Out).To(Say(`Scaling app some-app in org some-org / space some-space as some-user\.\.\.`))
							Expect(testUI.Out).To(Say(`This will cause the app to restart\. Are you sure you want to scale some-app\? \[yN\]:`))
							Expect(testUI.Out).To(Say("Scaling cancelled"))
							Expect(testUI.Out).ToNot(Say("Showing | Stopping | Starting | Waiting"))

							Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(0))
						})
					})

					When("the user chooses no", func() {
						BeforeEach(func() {
							_, err := input.Write([]byte("n\n"))
							Expect(err).ToNot(HaveOccurred())
						})

						It("does not scale the app", func() {
							Expect(executeErr).ToNot(HaveOccurred())

							Expect(testUI.Out).To(Say(`Scaling app some-app in org some-org / space some-space as some-user\.\.\.`))
							Expect(testUI.Out).To(Say(`This will cause the app to restart\. Are you sure you want to scale some-app\? \[yN\]:`))
							Expect(testUI.Out).To(Say("Scaling cancelled"))
							Expect(testUI.Out).ToNot(Say("Showing | Stopping | Starting | Waiting"))

							Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(0))
						})
					})

					When("the user chooses yes", func() {
						BeforeEach(func() {
							_, err := input.Write([]byte("y\n"))
							Expect(err).ToNot(HaveOccurred())
						})

						When("polling succeeds and the app has running instances", func() {
							BeforeEach(func() {
								fakeActor.PollStartReturns(v7action.Warnings{"some-poll-warning-1", "some-poll-warning-2"}, nil)
							})

							It("delegates the right appGUID", func() {
								actualApp, _, handleInstanceDetails := fakeActor.PollStartArgsForCall(0)
								Expect(actualApp).To(Equal(app))
								handleInstanceDetails("instance details")
								Expect(testUI.Out).To(Say("instance details"))
							})

							When("Restarting the app fails to stop the app", func() {
								BeforeEach(func() {
									fakeActor.StopApplicationReturns(v7action.Warnings{"some-restart-warning"}, errors.New("stop-error"))
								})

								It("Prints warnings and returns an error", func() {
									Expect(executeErr).To(MatchError("stop-error"))

									Expect(testUI.Err).To(Say("some-restart-warning"))
								})
							})

							When("Restarting the app fails to start the app", func() {
								BeforeEach(func() {
									fakeActor.StartApplicationReturns(v7action.Warnings{"some-start-warning"}, errors.New("start-error"))
								})

								It("Delegates the correct appGUID", func() {
									actualAppGUID := fakeActor.StartApplicationArgsForCall(0)
									Expect(actualAppGUID).To(Equal("some-app-guid"))
								})

								It("Prints warnings and returns an error", func() {
									Expect(executeErr).To(MatchError("start-error"))

									Expect(testUI.Err).To(Say("some-start-warning"))
								})
							})

							It("scales, restarts, and displays scale properties", func() {
								Expect(executeErr).ToNot(HaveOccurred())

								Expect(testUI.Out).To(Say(`Scaling app some-app in org some-org / space some-space as some-user\.\.\.`))
								Expect(testUI.Out).To(Say(`This will cause the app to restart\. Are you sure you want to scale some-app\? \[yN\]:`))
								Expect(testUI.Out).To(Say(`Stopping app some-app in org some-org / space some-space as some-user\.\.\.`))
								Expect(testUI.Out).To(Say(`Starting app some-app in org some-org / space some-space as some-user\.\.\.`))

								// Note that this does test that the disk quota was scaled to 96M,
								// it is tested below when we check the arguments
								// passed to ScaleProcessByApplication
								firstAppTable := helpers.ParseV3AppProcessTable(output.Contents())
								Expect(len(firstAppTable.Processes)).To(Equal(2))

								webProcessSummary := firstAppTable.Processes[0]
								Expect(webProcessSummary.Type).To(Equal("web"))
								Expect(webProcessSummary.InstanceCount).To(Equal("3/3"))
								Expect(webProcessSummary.MemUsage).To(Equal("32M"))

								Expect(webProcessSummary.Instances[0].Memory).To(Equal("976.6K of 32M"))
								Expect(webProcessSummary.Instances[0].Disk).To(Equal("976.6K of 1.9M"))
								Expect(webProcessSummary.Instances[0].CPU).To(Equal("0.0%"))
								Expect(webProcessSummary.Instances[0].LogRate).To(Equal("5K/s of 10K/s"))

								Expect(webProcessSummary.Instances[1].Memory).To(Equal("1.9M of 32M"))
								Expect(webProcessSummary.Instances[1].Disk).To(Equal("1.9M of 3.8M"))
								Expect(webProcessSummary.Instances[1].CPU).To(Equal("0.0%"))
								Expect(webProcessSummary.Instances[1].LogRate).To(Equal("3K/s of 10K/s"))

								Expect(webProcessSummary.Instances[2].Memory).To(Equal("2.9M of 32M"))
								Expect(webProcessSummary.Instances[2].Disk).To(Equal("2.9M of 5.7M"))
								Expect(webProcessSummary.Instances[2].CPU).To(Equal("0.0%"))
								Expect(webProcessSummary.Instances[2].LogRate).To(Equal("4K/s of 10K/s"))

								consoleProcessSummary := firstAppTable.Processes[1]
								Expect(consoleProcessSummary.Type).To(Equal("console"))
								Expect(consoleProcessSummary.InstanceCount).To(Equal("1/1"))
								Expect(consoleProcessSummary.MemUsage).To(Equal("16M"))

								Expect(consoleProcessSummary.Instances[0].Memory).To(Equal("976.6K of 32M"))
								Expect(consoleProcessSummary.Instances[0].Disk).To(Equal("976.6K of 7.6M"))
								Expect(consoleProcessSummary.Instances[0].CPU).To(Equal("0.0%"))
								Expect(consoleProcessSummary.Instances[0].LogRate).To(Equal("1K/s of 5K/s"))

								Expect(testUI.Err).To(Say("get-app-warning"))
								Expect(testUI.Err).To(Say("scale-warning"))
								Expect(testUI.Err).To(Say("some-poll-warning-1"))
								Expect(testUI.Err).To(Say("some-poll-warning-2"))
								Expect(testUI.Err).To(Say("get-instances-warning"))

								Expect(fakeActor.GetApplicationByNameAndSpaceCallCount()).To(Equal(1))
								appNameArg, spaceGUIDArg := fakeActor.GetApplicationByNameAndSpaceArgsForCall(0)
								Expect(appNameArg).To(Equal(app.Name))
								Expect(spaceGUIDArg).To(Equal("some-space-guid"))

								Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(1))
								appGUIDArg, scaleProcess := fakeActor.ScaleProcessByApplicationArgsForCall(0)
								Expect(appGUIDArg).To(Equal("some-app-guid"))
								Expect(scaleProcess).To(Equal(resources.Process{
									Type:              constant.ProcessTypeWeb,
									Instances:         types.NullInt{Value: 2, IsSet: true},
									DiskInMB:          types.NullUint64{Value: 50, IsSet: true},
									MemoryInMB:        types.NullUint64{Value: 100, IsSet: true},
									LogRateLimitInBPS: types.NullInt{Value: 1024, IsSet: true},
								}))

								Expect(fakeActor.StopApplicationCallCount()).To(Equal(1))
								Expect(fakeActor.StopApplicationArgsForCall(0)).To(Equal("some-app-guid"))

								Expect(fakeActor.StartApplicationCallCount()).To(Equal(1))
								Expect(fakeActor.StartApplicationArgsForCall(0)).To(Equal("some-app-guid"))
							})
						})

						When("polling succeeds but all the app's instances have crashed", func() {
							BeforeEach(func() {
								fakeActor.PollStartReturns(v7action.Warnings{"some-poll-warning-1", "some-poll-warning-2"}, actionerror.AllInstancesCrashedError{})
							})

							It("delegates the right appGUID", func() {
								actualApp, _, handleInstanceDetails := fakeActor.PollStartArgsForCall(0)
								Expect(actualApp).To(Equal(app))
								handleInstanceDetails("instance details")
								Expect(testUI.Out).To(Say("instance details"))
							})

							It("displays the process table", func() {
								Expect(testUI.Out).To(Say("Showing current scale of app " + app.Name))
							})

							It("displays all warnings and fails", func() {
								Expect(testUI.Err).To(Say("some-poll-warning-1"))
								Expect(testUI.Err).To(Say("some-poll-warning-2"))

								Expect(executeErr).To(MatchError(translatableerror.ApplicationUnableToStartError{
									AppName:    app.Name,
									BinaryName: binaryName,
								}))
							})
						})

						When("polling the start fails", func() {
							BeforeEach(func() {
								fakeActor.PollStartReturns(v7action.Warnings{"some-poll-warning-1", "some-poll-warning-2"}, errors.New("some-error"))
							})

							It("delegates the right appGUID", func() {
								actualApp, _, handleInstanceDetails := fakeActor.PollStartArgsForCall(0)
								Expect(actualApp).To(Equal(app))
								handleInstanceDetails("instance details")
								Expect(testUI.Out).To(Say("instance details"))
							})

							It("displays all warnings and fails", func() {
								Expect(testUI.Err).To(Say("some-poll-warning-1"))
								Expect(testUI.Err).To(Say("some-poll-warning-2"))

								Expect(executeErr).To(MatchError("some-error"))
							})
						})

						When("polling times out", func() {
							BeforeEach(func() {
								fakeActor.PollStartReturns(nil, actionerror.StartupTimeoutError{})
							})

							It("delegates the right appGUID", func() {
								actualApp, _, handleInstanceDetails := fakeActor.PollStartArgsForCall(0)
								Expect(actualApp).To(Equal(app))
								handleInstanceDetails("instance details")
								Expect(testUI.Out).To(Say("instance details"))
							})

							It("returns the StartupTimeoutError", func() {
								Expect(executeErr).To(MatchError(translatableerror.StartupTimeoutError{
									AppName:    "some-app",
									BinaryName: binaryName,
								}))
							})
						})
					})
				})

				When("force flag is provided", func() {
					BeforeEach(func() {
						cmd.Force = true
					})

					It("does not prompt user to confirm app restart", func() {
						Expect(executeErr).ToNot(HaveOccurred())

						Expect(testUI.Out).To(Say(`Scaling app some-app in org some-org / space some-space as some-user\.\.\.`))
						Expect(testUI.Out).To(Say(`Stopping app some-app in org some-org / space some-space as some-user\.\.\.`))
						Expect(testUI.Out).To(Say(`Starting app some-app in org some-org / space some-space as some-user\.\.\.`))
						Expect(testUI.Out).NotTo(Say(`This will cause the app to restart\. Are you sure you want to scale some-app\? \[yN\]:`))

						Expect(fakeActor.GetApplicationByNameAndSpaceCallCount()).To(Equal(1))
						Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(1))
						Expect(fakeActor.StopApplicationCallCount()).To(Equal(1))
						Expect(fakeActor.StartApplicationCallCount()).To(Equal(1))
						Expect(fakeActor.GetDetailedAppSummaryCallCount()).To(Equal(1))
					})
				})
			})

			When("only the instances flag option is provided", func() {
				BeforeEach(func() {
					cmd.Instances.Value = 3
					cmd.Instances.IsSet = true
					fakeActor.ScaleProcessByApplicationReturns(
						v7action.Warnings{"scale-warning"},
						nil)
					fakeActor.GetDetailedAppSummaryReturns(
						appSummary,
						v7action.Warnings{"get-instances-warning"},
						nil)
				})

				It("scales the number of instances, displays scale properties, and does not restart the application", func() {
					Expect(executeErr).ToNot(HaveOccurred())

					Expect(testUI.Out).To(Say("Scaling"))
					Expect(testUI.Out).NotTo(Say("This will cause the app to restart | Stopping | Starting"))

					Expect(testUI.Err).To(Say("get-app-warning"))
					Expect(testUI.Err).To(Say("scale-warning"))
					Expect(testUI.Err).To(Say("get-instances-warning"))

					Expect(fakeActor.GetApplicationByNameAndSpaceCallCount()).To(Equal(1))
					appNameArg, spaceGUIDArg := fakeActor.GetApplicationByNameAndSpaceArgsForCall(0)
					Expect(appNameArg).To(Equal(app.Name))
					Expect(spaceGUIDArg).To(Equal("some-space-guid"))

					Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(1))
					appGUIDArg, scaleProcess := fakeActor.ScaleProcessByApplicationArgsForCall(0)
					Expect(appGUIDArg).To(Equal("some-app-guid"))
					Expect(scaleProcess).To(Equal(resources.Process{
						Type:      constant.ProcessTypeWeb,
						Instances: types.NullInt{Value: 3, IsSet: true},
					}))

					Expect(fakeActor.StopApplicationCallCount()).To(Equal(0))
					Expect(fakeActor.StartApplicationCallCount()).To(Equal(0))
				})

				When("the app is started", func() {
					BeforeEach(func() {
						app.State = constant.ApplicationStarted
						fakeActor.GetApplicationByNameAndSpaceReturns(
							app, nil, nil)
					})

					It("polls for the app being started", func() {
						Expect(fakeActor.PollStartCallCount()).To(Equal(1))
					})
				})

				When("the app is stopped", func() {
					BeforeEach(func() {
						app.State = constant.ApplicationStopped
						fakeActor.GetApplicationByNameAndSpaceReturns(
							app, nil, nil)
					})
					It("does not poll for the app being started", func() {
						Expect(fakeActor.PollStartCallCount()).To(Equal(0))
					})
				})
			})

			When("only the memory flag option is provided", func() {
				BeforeEach(func() {
					cmd.MemoryLimit.Value = 256
					cmd.MemoryLimit.IsSet = true
					fakeActor.ScaleProcessByApplicationReturns(
						v7action.Warnings{"scale-warning"},
						nil)
					fakeActor.GetDetailedAppSummaryReturns(
						appSummary,
						v7action.Warnings{"get-instances-warning"},
						nil)

					_, err := input.Write([]byte("y\n"))
					Expect(err).ToNot(HaveOccurred())
				})

				It("scales, restarts, and displays scale properties", func() {
					Expect(executeErr).ToNot(HaveOccurred())

					Expect(testUI.Out).To(Say("Scaling"))
					Expect(testUI.Out).To(Say("This will cause the app to restart"))
					Expect(testUI.Out).To(Say("Stopping"))
					Expect(testUI.Out).To(Say("Starting"))

					Expect(testUI.Err).To(Say("get-app-warning"))
					Expect(testUI.Err).To(Say("scale-warning"))
					Expect(testUI.Err).To(Say("get-instances-warning"))

					Expect(fakeActor.GetApplicationByNameAndSpaceCallCount()).To(Equal(1))
					appNameArg, spaceGUIDArg := fakeActor.GetApplicationByNameAndSpaceArgsForCall(0)
					Expect(appNameArg).To(Equal(app.Name))
					Expect(spaceGUIDArg).To(Equal("some-space-guid"))

					Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(1))
					appGUIDArg, scaleProcess := fakeActor.ScaleProcessByApplicationArgsForCall(0)
					Expect(appGUIDArg).To(Equal("some-app-guid"))
					Expect(scaleProcess).To(Equal(resources.Process{
						Type:       constant.ProcessTypeWeb,
						MemoryInMB: types.NullUint64{Value: 256, IsSet: true},
					}))

					Expect(fakeActor.StopApplicationCallCount()).To(Equal(1))
					appGUID := fakeActor.StopApplicationArgsForCall(0)
					Expect(appGUID).To(Equal("some-app-guid"))

					Expect(fakeActor.StartApplicationCallCount()).To(Equal(1))
					appGUID = fakeActor.StartApplicationArgsForCall(0)
					Expect(appGUID).To(Equal("some-app-guid"))

					Expect(fakeActor.GetDetailedAppSummaryCallCount()).To(Equal(1))
				})
			})

			When("only the disk flag option is provided", func() {
				BeforeEach(func() {
					cmd.DiskLimit.Value = 1025
					cmd.DiskLimit.IsSet = true
					fakeActor.ScaleProcessByApplicationReturns(
						v7action.Warnings{"scale-warning"},
						nil)
					fakeActor.GetDetailedAppSummaryReturns(
						appSummary,
						v7action.Warnings{"get-instances-warning"},
						nil)
					_, err := input.Write([]byte("y\n"))
					Expect(err).ToNot(HaveOccurred())
				})

				It("scales the number of instances, displays scale properties, and restarts the application", func() {
					Expect(executeErr).ToNot(HaveOccurred())

					Expect(testUI.Out).To(Say("Scaling"))
					Expect(testUI.Out).To(Say("This will cause the app to restart"))
					Expect(testUI.Out).To(Say("Stopping"))
					Expect(testUI.Out).To(Say("Starting"))

					Expect(testUI.Err).To(Say("get-app-warning"))
					Expect(testUI.Err).To(Say("scale-warning"))
					Expect(testUI.Err).To(Say("get-instances-warning"))

					Expect(fakeActor.GetApplicationByNameAndSpaceCallCount()).To(Equal(1))
					appNameArg, spaceGUIDArg := fakeActor.GetApplicationByNameAndSpaceArgsForCall(0)
					Expect(appNameArg).To(Equal(app.Name))
					Expect(spaceGUIDArg).To(Equal("some-space-guid"))

					Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(1))
					appGUIDArg, scaleProcess := fakeActor.ScaleProcessByApplicationArgsForCall(0)
					Expect(appGUIDArg).To(Equal("some-app-guid"))
					Expect(scaleProcess).To(Equal(resources.Process{
						Type:     constant.ProcessTypeWeb,
						DiskInMB: types.NullUint64{Value: 1025, IsSet: true},
					}))

					Expect(fakeActor.StopApplicationCallCount()).To(Equal(1))
					appGUID := fakeActor.StopApplicationArgsForCall(0)
					Expect(appGUID).To(Equal("some-app-guid"))

					Expect(fakeActor.StartApplicationCallCount()).To(Equal(1))
					appGUID = fakeActor.StartApplicationArgsForCall(0)
					Expect(appGUID).To(Equal("some-app-guid"))
				})
			})

			When("process flag is provided", func() {
				BeforeEach(func() {
					cmd.ProcessType = "some-process-type"
					cmd.Instances.Value = 2
					cmd.Instances.IsSet = true
					fakeActor.ScaleProcessByApplicationReturns(
						v7action.Warnings{"scale-warning"},
						nil)
					fakeActor.GetDetailedAppSummaryReturns(
						appSummary,
						v7action.Warnings{"get-instances-warning"},
						nil)
					_, err := input.Write([]byte("y\n"))
					Expect(err).ToNot(HaveOccurred())
				})

				It("scales the specified process", func() {
					Expect(executeErr).ToNot(HaveOccurred())

					Expect(testUI.Out).To(Say("Scaling"))

					Expect(testUI.Err).To(Say("get-app-warning"))
					Expect(testUI.Err).To(Say("scale-warning"))
					Expect(testUI.Err).To(Say("get-instances-warning"))

					Expect(fakeActor.GetApplicationByNameAndSpaceCallCount()).To(Equal(1))
					appNameArg, spaceGUIDArg := fakeActor.GetApplicationByNameAndSpaceArgsForCall(0)
					Expect(appNameArg).To(Equal(app.Name))
					Expect(spaceGUIDArg).To(Equal("some-space-guid"))

					Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(1))
					appGUIDArg, scaleProcess := fakeActor.ScaleProcessByApplicationArgsForCall(0)
					Expect(appGUIDArg).To(Equal("some-app-guid"))
					Expect(scaleProcess).To(Equal(resources.Process{
						Type:      "some-process-type",
						Instances: types.NullInt{Value: 2, IsSet: true},
					}))
				})
			})

			When("only the log rate limit option is provided", func() {
				BeforeEach(func() {
					cmd.LogRateLimit.Value = 2048
					cmd.LogRateLimit.IsSet = true
					fakeActor.ScaleProcessByApplicationReturns(
						v7action.Warnings{"scale-warning"},
						nil)
					fakeActor.GetDetailedAppSummaryReturns(
						appSummary,
						v7action.Warnings{"get-instances-warning"},
						nil)

					_, err := input.Write([]byte("y\n"))
					Expect(err).ToNot(HaveOccurred())
				})

				It("scales, restarts, and displays scale properties", func() {
					Expect(executeErr).ToNot(HaveOccurred())

					Expect(testUI.Out).To(Say("Scaling"))
					Expect(testUI.Out).To(Say("This will cause the app to restart"))
					Expect(testUI.Out).To(Say("Stopping"))
					Expect(testUI.Out).To(Say("Starting"))

					Expect(testUI.Err).To(Say("get-app-warning"))
					Expect(testUI.Err).To(Say("scale-warning"))
					Expect(testUI.Err).To(Say("get-instances-warning"))

					Expect(fakeActor.GetApplicationByNameAndSpaceCallCount()).To(Equal(1))
					appNameArg, spaceGUIDArg := fakeActor.GetApplicationByNameAndSpaceArgsForCall(0)
					Expect(appNameArg).To(Equal(app.Name))
					Expect(spaceGUIDArg).To(Equal("some-space-guid"))

					Expect(fakeActor.ScaleProcessByApplicationCallCount()).To(Equal(1))
					appGUIDArg, scaleProcess := fakeActor.ScaleProcessByApplicationArgsForCall(0)
					Expect(appGUIDArg).To(Equal("some-app-guid"))
					Expect(scaleProcess).To(Equal(resources.Process{
						Type:              constant.ProcessTypeWeb,
						LogRateLimitInBPS: types.NullInt{Value: 2048, IsSet: true},
					}))

					Expect(fakeActor.StopApplicationCallCount()).To(Equal(1))
					appGUID := fakeActor.StopApplicationArgsForCall(0)
					Expect(appGUID).To(Equal("some-app-guid"))

					Expect(fakeActor.StartApplicationCallCount()).To(Equal(1))
					appGUID = fakeActor.StartApplicationArgsForCall(0)
					Expect(appGUID).To(Equal("some-app-guid"))

					Expect(fakeActor.GetDetailedAppSummaryCallCount()).To(Equal(1))
				})
			})

			When("an error is encountered scaling the application", func() {
				var expectedErr error

				BeforeEach(func() {
					cmd.Instances.Value = 3
					cmd.Instances.IsSet = true
					expectedErr = errors.New("scale process error")
					fakeActor.ScaleProcessByApplicationReturns(
						v7action.Warnings{"scale-process-warning"},
						expectedErr,
					)
				})

				It("returns the error and displays all warnings", func() {
					Expect(executeErr).To(Equal(expectedErr))
					Expect(testUI.Err).To(Say("scale-process-warning"))
				})
			})
		})
	})
})


text:
<?php

namespace SuperCMS\Controls\KeyValue;

use Rhubarb\Crown\Request\WebRequest;
use Rhubarb\Leaf\Leaves\Controls\ControlView;
use Rhubarb\Leaf\Leaves\LeafDeploymentPackage;

class KeyValueView extends ControlView
{
    protected $requiresContainerDiv = true;

    /**
     * @var KeyValueModel
     */
    protected $model;

    protected function parseRequest(WebRequest $request)
    {
        $keys = $request->post($this->model->leafPath . "_key");
        $values = $request->post($this->model->leafPath . "_value");

        $data = [];

        if ($keys) {
            foreach ($keys as $key => $value) {
                $data[] = [$value, $values[$key]];
            }
            $this->setControlValueForIndex(null, $data);
        }
    }

    protected function printViewContent()
    {
        ?>
        <xmp id="hidden-line-placeholders" style="display: none;"><?php $this->printLine('', '') ?></xmp>

            <?php
            if ($this->model->value) {
                foreach ($this->model->value as $value) {
                    $this->printLine($value[0], $value[1]);
                }
            }
            ?>

        <?php
        $this->printAddButton();
    }

    public function printAddButton()
    {
        print 'model->addClasses) . '" id="addTrigger">' . $this->model->addText . '';
    }

    public function printRemoveButton()
    {
        print 'model->removeClasses) . '" id="removeTrigger">' . $this->model->removeText . '';
    }

    public function printLine($key, $value)
    {
        $inputClass = implode(' ', $this->model->inputClasses);
        print '

                <input placeholder="Key" class="' . $inputClass . '" id="' . $this->model->leafPath . '_key[' . $key . ']" name="' . $this->model->leafPath . '_key[' . $key . ']" type="text" value="' . htmlentities($key) . '">
                <input placeholder="Value" class="' . $inputClass . '" id="' . $this->model->leafPath . '_value[' . $key . ']" name="' . $this->model->leafPath . '_value[' . $key . ']" type="text" value="' . htmlentities($value) . '">';
        $this->printRemoveButton();
        print '
';
    }

    protected function getViewBridgeName()
    {
        return 'KeyValueViewBridge';
    }

    public function getDeploymentPackage()
    {
        $package = new LeafDeploymentPackage();
        $package->resourcesToDeploy[] = __DIR__ . '/' . $this->getViewBridgeName() . '.js';

        return $package;
    }
}


text:
import TextField from '@ember/component/text-field';
import { computed } from '@ember/object';
import hasTextSelected from 'ember-credit-cards/utils/has-text-selected';
import formatters from 'ember-credit-cards/utils/formatters';
import cards from 'ember-credit-cards/utils/cards';
import isDigitKeypress from 'ember-credit-cards/utils/is-digit-keypress';

const cardFromNumber = cards.fromNumber;

function inputValid(value) {
  value = (value + '').replace(/\D/g, '');

  var card = cardFromNumber(value);

  if (card) {
    return value.length <= card.length[card.length.length - 1];
  } else {
    return value.length <= 16;
  }
}

export default TextField.extend({
  classNames: ['input-credit-card-number'],
  placeholder: '•••• •••• •••• ••••',
  autocomplete: 'cc-number',
  type: 'tel',
  required: true,

  keyPress: function(e) {
    if (!isDigitKeypress(e)) {
      return false;
    }

    if (hasTextSelected(this.element)) {
      return true;
    }

    var digit = String.fromCharCode(e.which);
    var value = this.element.value + digit;
    return inputValid(value);
  },

  value: computed('number', {
    get() {
      return formatters.formatNumber(this.number);
    },
    set(key, value) {
      this.set('number', value);
      return formatters.formatNumber(value);
    }
  })
});


text:
// Copyright 2015 Apcera Inc. All rights reserved.

using System;
using NATS.Client;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using Xunit;

namespace NATSUnitTests
{
    /// <summary>
    /// Run these tests with the gnatsd auth.conf configuration file.
    /// </summary>
    public class TestCluster
    {
        string[] testServers = new string[] {
            "nats://localhost:1222",
            "nats://localhost:1223",
            "nats://localhost:1224",
            "nats://localhost:1225",
            "nats://localhost:1226",
            "nats://localhost:1227",
            "nats://localhost:1228"
        };

        string[] testServersShortList = new string[] {
            "nats://localhost:1222",
            "nats://localhost:1223"
        };

        UnitTestUtilities utils = new UnitTestUtilities();

        [Fact]
        public void TestServersOption()
        {
            IConnection c = null;
            ConnectionFactory cf = new ConnectionFactory();
            Options o = ConnectionFactory.GetDefaultOptions();

            o.NoRandomize = true;

            Assert.ThrowsAny<NATSNoServersException>(() => cf.CreateConnection());

            o.Servers = testServers;

            Assert.ThrowsAny<NATSNoServersException>(() => cf.CreateConnection(o));

            // Make sure we can connect to first server if running
            using (NATSServer ns = utils.CreateServerOnPort(1222))
            {
                c = cf.CreateConnection(o);
                Assert.True(testServers[0].Equals(c.ConnectedUrl));
                c.Close();
            }

            // make sure we can connect to a non-first server.
            using (NATSServer ns = utils.CreateServerOnPort(1227))
            {
                c = cf.CreateConnection(o);
                Assert.True(testServers[5].Equals(c.ConnectedUrl));
                c.Close();
            }
        }

        [Fact]
        public void TestAuthServers()
        {
            string[] plainServers = new string[] {
                "nats://localhost:1222",
		        "nats://localhost:1224"
            };

            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.NoRandomize = true;
            opts.Servers = plainServers;
            opts.Timeout = 5000;

            using (NATSServer as1 = utils.CreateServerWithConfig("auth_1222.conf"),
                              as2 = utils.CreateServerWithConfig("auth_1224.conf"))
            {
                Assert.ThrowsAny<NATSException>(() => new ConnectionFactory().CreateConnection(opts));

                // Test that we can connect to a subsequent correct server.
                string[] authServers = new string[] {
                    "nats://localhost:1222",
		            "nats://username:password@localhost:1224"};

                opts.Servers = authServers;

                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    Assert.Equal(authServers[1], c.ConnectedUrl);
                }
            }
        }

        [Fact]
        public void TestBasicClusterReconnect()
        {
            string[] plainServers = new string[] {
                "nats://localhost:1222",
		        "nats://localhost:1224"
            };

            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.MaxReconnect = 2;
            opts.ReconnectWait = 1000;
            opts.NoRandomize = true;
            opts.Servers = plainServers;

            Object disconnectLock = new Object();
            opts.DisconnectedEventHandler += (sender, args) =>
            {
                // Suppress any additional calls
                opts.DisconnectedEventHandler = null;
                lock (disconnectLock)
                {
                    Monitor.Pulse(disconnectLock);
                }
            };

            Object reconnectLock = new Object();

            opts.ReconnectedEventHandler = (sender, args) =>
            {
                // Suppress any additional calls
                lock (reconnectLock)
                {
                    Monitor.Pulse(reconnectLock);
                }
            };

            opts.Timeout = 200;

            using (NATSServer s1 = utils.CreateServerOnPort(1222),
                              s2 = utils.CreateServerOnPort(1224))
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    Stopwatch reconnectSw = new Stopwatch();

                    System.Console.WriteLine("Connected to: " + c.ConnectedUrl);
                    lock (disconnectLock)
                    {
                        s1.Shutdown();
                        Assert.True(Monitor.Wait(disconnectLock, 20000));
                    }

                    reconnectSw.Start();

                    lock (reconnectLock)
                    {
                        Assert.True(Monitor.Wait(reconnectLock, 20000));
                    }

                    Assert.True(c.ConnectedUrl.Equals(testServers[2]));

                    reconnectSw.Stop();

                    // Make sure we did not wait on reconnect for default time.
                    // Reconnect should be fast since it will be a switch to the
                    // second server and not be dependent on server restart time.
                    // TODO:  .NET connect timeout is exceeding long compared to
                    // GO's.  Look shortening it, or living with it.
                    //if (reconnectSw.ElapsedMilliseconds > opts.ReconnectWait)
                    //{
                    //   Assert.Fail("Reconnect time took to long: {0} millis.",
                    //        reconnectSw.ElapsedMilliseconds);
                    //}
                }
            }
        }

        private class SimClient
        {
            IConnection c;
            Object mu = new Object();

            public string ConnectedUrl
            {
                get { return c.ConnectedUrl; }
            }

            public void waitForReconnect()
            {
                lock (mu)
                {
                    Monitor.Wait(mu);
                }
            }

            public void Connect(string[] servers)
            {
                Options opts = ConnectionFactory.GetDefaultOptions();
                opts.Servers = servers;
                c = new ConnectionFactory().CreateConnection(opts);
                opts.ReconnectedEventHandler = (sender, args) =>
                {
                    lock (mu)
                    {
                        Monitor.Pulse(mu);
                    }
                };
            }

            public void close()
            {
                c.Close();
            }
        }

        // TODO:  Create smaller variant [Fact]
        public void TestHotSpotReconnect()
        {
            int numClients = 10;
            SimClient[] clients = new SimClient[100];

            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.Servers = testServers;

            NATSServer s1 = utils.CreateServerOnPort(1222);
            Task[] waitgroup = new Task[numClients];

            for (int i = 0; i < numClients; i++)
            {
                clients[i] = new SimClient();
                Task t = new Task(() => {
                    clients[i].Connect(testServers);
                    clients[i].waitForReconnect();
                });
                t.Start();
                waitgroup[i] = t;
            }

            NATSServer s2 = utils.CreateServerOnPort(1224);
            NATSServer s3 = utils.CreateServerOnPort(1226);

            s1.Shutdown();
            Task.WaitAll(waitgroup);

            int s2Count = 0;
            int s3Count = 0;
            int unknown = 0;

            for (int i = 0; i < numClients; i++)
            {
                if (testServers[3].Equals(clients[i].ConnectedUrl))
                    s2Count++;
                else if (testServers[5].Equals(clients[i].ConnectedUrl))
                    s3Count++;
                else
                    unknown++;
            }

            Assert.True(unknown == 0);
            int delta = Math.Abs(s2Count - s3Count);
            int range = numClients / 30;

            Assert.False(delta > range, string.Format("Connected clients to servers out of range: {0}/{0}", delta, range));

        }

        [Fact]
        public void TestProperReconnectDelay()
        {
            Object mu = new Object();
            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.Servers = testServers;
            opts.NoRandomize = true;

            bool disconnectHandlerCalled = false;
            opts.DisconnectedEventHandler = (sender, args) =>
            {
                opts.DisconnectedEventHandler = null;
                disconnectHandlerCalled = true;
                lock (mu)
                {
                    disconnectHandlerCalled = true;
                    Monitor.Pulse(mu);
                }
            };

            bool closedCbCalled = false;
            opts.ClosedEventHandler = (sender, args) =>
            {
                closedCbCalled = true;
            };

            using (NATSServer s1 = utils.CreateServerOnPort(1222))
            {
                IConnection c = new ConnectionFactory().CreateConnection(opts);

                lock (mu)
                {
                    s1.Shutdown();
                    // wait for disconnect
                    Assert.True(Monitor.Wait(mu, 10000));

                    // Wait, want to make sure we don't spin on
                    //reconnect to non-existant servers.
                    Thread.Sleep(1000);

                    Assert.False(closedCbCalled);
                    Assert.True(disconnectHandlerCalled);
                    Assert.True(c.State == ConnState.RECONNECTING);
                }

            }
        }

        [Fact]
        public void TestProperFalloutAfterMaxAttempts()
        {
            Options opts = ConnectionFactory.GetDefaultOptions();

            Object dmu = new Object();
            Object cmu = new Object();

            opts.Servers = this.testServersShortList;
            opts.NoRandomize = true;
            opts.MaxReconnect = 2;
            opts.ReconnectWait = 25; // millis
            opts.Timeout = 500;

            bool disconnectHandlerCalled = false;

            opts.DisconnectedEventHandler = (sender, args) =>
            {
                lock (dmu)
                {
                    disconnectHandlerCalled = true;
                    Monitor.Pulse(dmu);
                }
            };

            bool closedHandlerCalled = false;
            opts.ClosedEventHandler = (sender, args) =>
            {
                lock (cmu)
                {
                    closedHandlerCalled = true;
                    Monitor.Pulse(cmu);
                }
            };

            using (NATSServer s1 = utils.CreateServerOnPort(1222))
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    s1.Shutdown();

                    lock (dmu)
                    {
                        if (!disconnectHandlerCalled)
                            Assert.True(Monitor.Wait(dmu, 20000));
                    }

                    lock (cmu)
                    {
                        if (!closedHandlerCalled)
                            Assert.True(Monitor.Wait(cmu, 60000));
                    }

                    Assert.True(disconnectHandlerCalled);
                    Assert.True(closedHandlerCalled);
                    Assert.True(c.IsClosed());
                }
            }
        }

        [Fact]
        public void TestProperFalloutAfterMaxAttemptsWithAuthMismatch()
        {
            Options opts = ConnectionFactory.GetDefaultOptions();

            Object dmu = new Object();
            Object cmu = new Object();

            opts.Servers = new string[] {
                "nats://localhost:1220",
                "nats://localhost:1222"
            };

            opts.NoRandomize = true;
            opts.MaxReconnect = 2;
            opts.ReconnectWait = 25; // millis
            opts.Timeout = 500;

            bool disconnectHandlerCalled = false;

            opts.DisconnectedEventHandler = (sender, args) =>
            {
                lock (dmu)
                {
                    disconnectHandlerCalled = true;
                    Monitor.Pulse(dmu);
                }
            };

            bool closedHandlerCalled = false;
            opts.ClosedEventHandler = (sender, args) =>
            {
                lock (cmu)
                {
                    closedHandlerCalled = true;
                    Monitor.Pulse(cmu);
                }
            };

            using (NATSServer s1 = utils.CreateServerOnPort(1220),
                   s2 = utils.CreateServerWithConfig("tls_1222_verify.conf"))
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    s1.Shutdown();

                    lock (dmu)
                    {
                        if (!disconnectHandlerCalled)
                            Assert.True(Monitor.Wait(dmu, 20000));
                    }

                    lock (cmu)
                    {
                        if (!closedHandlerCalled)
                            Assert.True(Monitor.Wait(cmu, 600000));
                    }

                    Assert.True(c.Stats.Reconnects != opts.MaxReconnect);

                    Assert.True(disconnectHandlerCalled);
                    Assert.True(closedHandlerCalled);
                    Assert.True(c.IsClosed());
                }
            }
        }

        [Fact]
        public void TestTimeoutOnNoServers()
        {
            Options opts = ConnectionFactory.GetDefaultOptions();
            Object dmu = new Object();
            Object cmu = new Object();

            opts.Servers = testServersShortList;
            opts.NoRandomize = true;
            opts.MaxReconnect = 2;
            opts.ReconnectWait = 100; // millis

            bool disconnectHandlerCalled = false;
            bool closedHandlerCalled = false;

            opts.DisconnectedEventHandler = (sender, args) =>
            {
                lock (dmu)
                {
                    disconnectHandlerCalled = true;
                    Monitor.Pulse(dmu);
                }
            };

            opts.ClosedEventHandler = (sender, args) =>
            {
                lock (cmu)
                {
                    closedHandlerCalled = true;
                    Monitor.Pulse(cmu);
                }
            };

            using (NATSServer s1 = utils.CreateServerOnPort(1222))
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    s1.Shutdown();

                    lock (dmu)
                    {
                        if (!disconnectHandlerCalled)
                           Assert.True(Monitor.Wait(dmu, 20000));
                    }

                    Stopwatch sw = new Stopwatch();
                    sw.Start();

                    lock (cmu)
                    {
                        if (!closedHandlerCalled)
                            Assert.True(Monitor.Wait(cmu, 60000));
                    }

                    sw.Stop();

                    int expected = opts.MaxReconnect * opts.ReconnectWait;

                    // .NET has long connect times, so revisit this after
                    // a connect timeout has been added.
                    //Assert.IsTrue(sw.ElapsedMilliseconds < (expected + 500));

                    Assert.True(disconnectHandlerCalled);
                    Assert.True(closedHandlerCalled);
                    Assert.True(c.IsClosed());
                }
            }
        }

        //[Fact]
        public void TestPingReconnect()
        {
            /// Work in progress
            int RECONNECTS = 4;

            Options opts = ConnectionFactory.GetDefaultOptions();
            Object mu = new Object();

            opts.Servers = testServersShortList;
            opts.NoRandomize = true;
            opts.ReconnectWait = 200;
            opts.PingInterval = 50;
            opts.MaxPingsOut = -1;
            opts.Timeout = 1000;

            Stopwatch disconnectedTimer = new Stopwatch();

            opts.DisconnectedEventHandler = (sender, args) =>
            {
                disconnectedTimer.Reset();
                disconnectedTimer.Start();
            };

            opts.ReconnectedEventHandler = (sender, args) =>
            {
                lock (mu)
                {
                    args.Conn.Opts.MaxPingsOut = 500;
                    disconnectedTimer.Stop();
                    Monitor.Pulse(mu);
                }
            };

            using (NATSServer s1 = utils.CreateServerOnPort(1222))
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    s1.Shutdown();
                    for (int i = 0; i < RECONNECTS; i++)
                    {
                        lock (mu)
                        {
                            Assert.True(Monitor.Wait(mu, 100000));
                        }
                    }
                }
            }
        }

    } // class

} // namespace


text:
using System;
using System.Reflection;

namespace FlatBuffers
{
    internal class FieldValueProvider : IValueProvider
    {
        private readonly FieldInfo _field;

        public FieldValueProvider(FieldInfo field)
        {
            _field = field;
        }

        public object GetValue(object obj)
        {
            return _field.GetValue(obj);
        }

        public void SetValue(object obj, object value)
        {
            _field.SetValue(obj, value);
        }

        public Type ValueType { get { return _field.FieldType; } }
    }
}


text:
import os
import sys

os.chdir(os.path.join(os.path.dirname(sys.argv[0]), '../../..'))

def check_port_platform_inclusion(directory_root):
    bad_files = []
    for root, dirs, files in os.walk(directory_root):
        for filename in files:
            path = os.path.join(root, filename)
            if os.path.splitext(path)[1] not in ['.c', '.cc', '.h']: continue
            if path in [
                    os.path.join('include', 'grpc', 'support',
                                 'port_platform.h'),
                    os.path.join('include', 'grpc', 'impl', 'codegen',
                                 'port_platform.h'),
            ]:
                continue
            if filename.endswith('.pb.h') or filename.endswith('.pb.c'):
                continue
            # Skip check for upb generated code.
            if filename.endswith('.upb.h') or filename.endswith('.upb.c'):
                continue
            with open(path) as f:
                all_lines_in_file = f.readlines()
                for index, l in enumerate(all_lines_in_file):
                    if '#include' in l:
                        if l not in [
                                '#include <grpc/support/port_platform.h>\n',
                                '#include <grpc/impl/codegen/port_platform.h>\n'
                        ]:
                            bad_files.append(path)
                        elif all_lines_in_file[index + 1] != '\n':
                            # Require a blank line after including port_platform.h in
                            # order to prevent the formatter from reording it's
                            # inclusion order upon future changes.
                            bad_files.append(path)
                        break
    return bad_files

all_bad_files = []
all_bad_files += check_port_platform_inclusion(os.path.join('src', 'core'))
all_bad_files += check_port_platform_inclusion(os.path.join('include', 'grpc'))

if len(all_bad_files) > 0:
    for f in all_bad_files:
        print(('port_platform.h is not the first included header or there '
               'is not a blank line following its inclusion in %s') % f)
    sys.exit(1)


text:
package org.apache.cassandra.service.reads.repair;

import java.util.Arrays;

import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;

import org.apache.cassandra.db.Clustering;
import org.apache.cassandra.db.ClusteringBound;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.DeletionTime;
import org.apache.cassandra.db.LivenessInfo;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.db.RangeTombstone;
import org.apache.cassandra.db.ReadCommand;
import org.apache.cassandra.db.RegularAndStaticColumns;
import org.apache.cassandra.db.Slice;
import org.apache.cassandra.db.filter.ColumnFilter;
import org.apache.cassandra.db.partitions.PartitionUpdate;
import org.apache.cassandra.db.rows.BTreeRow;
import org.apache.cassandra.db.rows.Cell;
import org.apache.cassandra.db.rows.RangeTombstoneMarker;
import org.apache.cassandra.db.rows.Row;
import org.apache.cassandra.db.rows.RowDiffListener;
import org.apache.cassandra.db.rows.Rows;
import org.apache.cassandra.db.rows.UnfilteredRowIterators;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.schema.ColumnMetadata;
import org.apache.cassandra.schema.TableMetadata;

public class RowIteratorMergeListener implements UnfilteredRowIterators.MergeListener
{
    private final DecoratedKey partitionKey;
    private final RegularAndStaticColumns columns;
    private final boolean isReversed;
    private final InetAddressAndPort[] sources;
    private final ReadCommand command;

    private final PartitionUpdate.Builder[] repairs;

    private final Row.Builder[] currentRows;
    private final RowDiffListener diffListener;

    // The partition level deletion for the merge row.
    private DeletionTime partitionLevelDeletion;
    // When merged has a currently open marker, its time. null otherwise.
    private DeletionTime mergedDeletionTime;
    // For each source, the time of the current deletion as known by the source.
    private final DeletionTime[] sourceDeletionTime;
    // For each source, record if there is an open range to send as repair, and from where.
    private final ClusteringBound[] markerToRepair;

    private final RepairListener repairListener;

    public RowIteratorMergeListener(DecoratedKey partitionKey, RegularAndStaticColumns columns, boolean isReversed, InetAddressAndPort[] sources, ReadCommand command, RepairListener repairListener)
    {
        this.partitionKey = partitionKey;
        this.columns = columns;
        this.isReversed = isReversed;
        this.sources = sources;
        repairs = new PartitionUpdate.Builder[sources.length];
        currentRows = new Row.Builder[sources.length];
        sourceDeletionTime = new DeletionTime[sources.length];
        markerToRepair = new ClusteringBound[sources.length];
        this.command = command;
        this.repairListener = repairListener;

        this.diffListener = new RowDiffListener()
        {
            public void onPrimaryKeyLivenessInfo(int i, Clustering clustering, LivenessInfo merged, LivenessInfo original)
            {
                if (merged != null && !merged.equals(original))
                    currentRow(i, clustering).addPrimaryKeyLivenessInfo(merged);
            }

            public void onDeletion(int i, Clustering clustering, Row.Deletion merged, Row.Deletion original)
            {
                if (merged != null && !merged.equals(original))
                    currentRow(i, clustering).addRowDeletion(merged);
            }

            public void onComplexDeletion(int i, Clustering clustering, ColumnMetadata column, DeletionTime merged, DeletionTime original)
            {
                if (merged != null && !merged.equals(original))
                    currentRow(i, clustering).addComplexDeletion(column, merged);
            }

            public void onCell(int i, Clustering clustering, Cell merged, Cell original)
            {
                if (merged != null && !merged.equals(original) && isQueried(merged))
                    currentRow(i, clustering).addCell(merged);
            }

            private boolean isQueried(Cell cell)
            {
                // When we read, we may have some cell that have been fetched but are not selected by the user. Those cells may
                // have empty values as optimization (see CASSANDRA-10655) and hence they should not be included in the read-repair.
                // This is fine since those columns are not actually requested by the user and are only present for the sake of CQL
                // semantic (making sure we can always distinguish between a row that doesn't exist from one that do exist but has
                /// no value for the column requested by the user) and so it won't be unexpected by the user that those columns are
                // not repaired.
                ColumnMetadata column = cell.column();
                ColumnFilter filter = RowIteratorMergeListener.this.command.columnFilter();
                return column.isComplex() ? filter.fetchedCellIsQueried(column, cell.path()) : filter.fetchedColumnIsQueried(column);
            }
        };
    }

    private PartitionUpdate.Builder update(int i)
    {
        if (repairs[i] == null)
            repairs[i] = new PartitionUpdate.Builder(command.metadata(), partitionKey, columns, 1);
        return repairs[i];
    }

    /**
     * The partition level deletion with with which source {@code i} is currently repaired, or
     * {@code DeletionTime.LIVE} if the source is not repaired on the partition level deletion (meaning it was
     * up to date on it). The output* of this method is only valid after the call to
     * {@link #onMergedPartitionLevelDeletion}.
     */
    private DeletionTime partitionLevelRepairDeletion(int i)
    {
        return repairs[i] == null ? DeletionTime.LIVE : repairs[i].partitionLevelDeletion();
    }

    private Row.Builder currentRow(int i, Clustering clustering)
    {
        if (currentRows[i] == null)
        {
            currentRows[i] = BTreeRow.sortedBuilder();
            currentRows[i].newRow(clustering);
        }
        return currentRows[i];
    }

    public void onMergedPartitionLevelDeletion(DeletionTime mergedDeletion, DeletionTime[] versions)
    {
        this.partitionLevelDeletion = mergedDeletion;
        for (int i = 0; i < versions.length; i++)
        {
            if (mergedDeletion.supersedes(versions[i]))
                update(i).addPartitionDeletion(mergedDeletion);
        }
    }

    public void onMergedRows(Row merged, Row[] versions)
    {
        // If a row was shadowed post merged, it must be by a partition level or range tombstone, and we handle
        // those case directly in their respective methods (in other words, it would be inefficient to send a row
        // deletion as repair when we know we've already send a partition level or range tombstone that covers it).
        if (merged.isEmpty())
            return;

        Rows.diff(diffListener, merged, versions);
        for (int i = 0; i < currentRows.length; i++)
        {
            if (currentRows[i] != null)
                update(i).add(currentRows[i].build());
        }
        Arrays.fill(currentRows, null);
    }

    private DeletionTime currentDeletion()
    {
        return mergedDeletionTime == null ? partitionLevelDeletion : mergedDeletionTime;
    }

    public void onMergedRangeTombstoneMarkers(RangeTombstoneMarker merged, RangeTombstoneMarker[] versions)
    {
        try
        {
            // The code for merging range tombstones is a tad complex and we had the assertions there triggered
            // unexpectedly in a few occasions (CASSANDRA-13237, CASSANDRA-13719). It's hard to get insights
            // when that happen without more context that what the assertion errors give us however, hence the
            // catch here that basically gather as much as context as reasonable.
            internalOnMergedRangeTombstoneMarkers(merged, versions);
        }
        catch (AssertionError e)
        {
            // The following can be pretty verbose, but it's really only triggered if a bug happen, so we'd
            // rather get more info to debug than not.
            TableMetadata table = command.metadata();
            String details = String.format("Error merging RTs on %s: merged=%s, versions=%s, sources={%s}",
                                           table,
                                           merged == null ? "null" : merged.toString(table),
                                           '[' + Joiner.on(", ").join(Iterables.transform(Arrays.asList(versions), rt -> rt == null ? "null" : rt.toString(table))) + ']',
                                           Arrays.toString(sources));
            throw new AssertionError(details, e);
        }
    }

    private void internalOnMergedRangeTombstoneMarkers(RangeTombstoneMarker merged, RangeTombstoneMarker[] versions)
    {
        // The current deletion as of dealing with this marker.
        DeletionTime currentDeletion = currentDeletion();

        for (int i = 0; i < versions.length; i++)
        {
            RangeTombstoneMarker marker = versions[i];

            // Update what the source now thinks is the current deletion
            if (marker != null)
                sourceDeletionTime[i] = marker.isOpen(isReversed) ? marker.openDeletionTime(isReversed) : null;

            // If merged == null, some of the source is opening or closing a marker
            if (merged == null)
            {
                // but if it's not this source, move to the next one
                if (marker == null)
                    continue;

                // We have a close and/or open marker for a source, with nothing corresponding in merged.
                // Because merged is a superset, this imply that we have a current deletion (being it due to an
                // early opening in merged or a partition level deletion) and that this deletion will still be
                // active after that point. Further whatever deletion was open or is open by this marker on the
                // source, that deletion cannot supersedes the current one.
                //
                // But while the marker deletion (before and/or after this point) cannot supersede the current
                // deletion, we want to know if it's equal to it (both before and after), because in that case
                // the source is up to date and we don't want to include repair.
                //
                // So in practice we have 2 possible case:
                //  1) the source was up-to-date on deletion up to that point: then it won't be from that point
                //     on unless it's a boundary and the new opened deletion time is also equal to the current
                //     deletion (note that this implies the boundary has the same closing and opening deletion
                //     time, which should generally not happen, but can due to legacy reading code not avoiding
                //     this for a while, see CASSANDRA-13237).
                //  2) the source wasn't up-to-date on deletion up to that point and it may now be (if it isn't
                //     we just have nothing to do for that marker).
                assert !currentDeletion.isLive() : currentDeletion.toString();

                // Is the source up to date on deletion? It's up to date if it doesn't have an open RT repair
                // nor an "active" partition level deletion (where "active" means that it's greater or equal
                // to the current deletion: if the source has a repaired partition deletion lower than the
                // current deletion, this means the current deletion is due to a previously open range tombstone,
                // and if the source isn't currently repaired for that RT, then it means it's up to date on it).
                DeletionTime partitionRepairDeletion = partitionLevelRepairDeletion(i);
                if (markerToRepair[i] == null && currentDeletion.supersedes(partitionRepairDeletion))
                {
                    // Since there is an ongoing merged deletion, the only way we don't have an open repair for
                    // this source is that it had a range open with the same deletion as current and it's
                    // closing it.
                    assert marker.isClose(isReversed) && currentDeletion.equals(marker.closeDeletionTime(isReversed))
                    : String.format("currentDeletion=%s, marker=%s", currentDeletion, marker.toString(command.metadata()));

                    // and so unless it's a boundary whose opening deletion time is still equal to the current
                    // deletion (see comment above for why this can actually happen), we have to repair the source
                    // from that point on.
                    if (!(marker.isOpen(isReversed) && currentDeletion.equals(marker.openDeletionTime(isReversed))))
                        markerToRepair[i] = marker.closeBound(isReversed).invert();
                }
                // In case 2) above, we only have something to do if the source is up-to-date after that point
                // (which, since the source isn't up-to-date before that point, means we're opening a new deletion
                // that is equal to the current one).
                else if (marker.isOpen(isReversed) && currentDeletion.equals(marker.openDeletionTime(isReversed)))
                {
                    closeOpenMarker(i, marker.openBound(isReversed).invert());
                }
            }
            else
            {
                // We have a change of current deletion in merged (potentially to/from no deletion at all).

                if (merged.isClose(isReversed))
                {
                    // We're closing the merged range. If we're recorded that this should be repaird for the
                    // source, close and add said range to the repair to send.
                    if (markerToRepair[i] != null)
                        closeOpenMarker(i, merged.closeBound(isReversed));

                }

                if (merged.isOpen(isReversed))
                {
                    // If we're opening a new merged range (or just switching deletion), then unless the source
                    // is up to date on that deletion (note that we've updated what the source deleteion is
                    // above), we'll have to sent the range to the source.
                    DeletionTime newDeletion = merged.openDeletionTime(isReversed);
                    DeletionTime sourceDeletion = sourceDeletionTime[i];
                    if (!newDeletion.equals(sourceDeletion))
                        markerToRepair[i] = merged.openBound(isReversed);
                }
            }
        }

        if (merged != null)
            mergedDeletionTime = merged.isOpen(isReversed) ? merged.openDeletionTime(isReversed) : null;
    }

    private void closeOpenMarker(int i, ClusteringBound close)
    {
        ClusteringBound open = markerToRepair[i];
        update(i).add(new RangeTombstone(Slice.make(isReversed ? close : open, isReversed ? open : close), currentDeletion()));
        markerToRepair[i] = null;
    }

    public void close()
    {
        RepairListener.PartitionRepair repair = null;
        for (int i = 0; i < repairs.length; i++)
        {
            if (repairs[i] == null)
                continue;

            if (repair == null)
            {
                repair = repairListener.startPartitionRepair();
            }
            repair.reportMutation(sources[i], new Mutation(repairs[i].build()));
        }

        if (repair != null)
        {
            repair.finish();
        }
    }
}


text:
<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="speicher210_fastbill.transport_collector" class="Speicher210\FastbillBundle\DataCollector\TransportCollector" decorates="speicher210_fastbill.transport">
            <argument type="service" id="speicher210_fastbill.transport_collector.inner" />
            <argument type="service" id="debug.stopwatch" />
        </service>

        <service id="speicher210_fastbill.data_collector" class="Speicher210\FastbillBundle\DataCollector\FastbillDataCollector" public="false">
            <argument type="service" id="speicher210_fastbill.api_credentials" />
            <argument type="service" id="speicher210_fastbill.transport_collector"/>
            <tag name="data_collector" template="@Speicher210Fastbill/Collector/speicher210_fastbill.html.twig" id="speicher210_fastbill" />
        </service>
    </services>
</container>


text:
using System;

namespace Avalara.AvaTax.RestClient
{
    /// <summary>
    /// A list of possible AvaFile filing types.
    /// </summary>
    public enum FilingTypeId
    {
        /// <summary>
        /// Denotes the tax return is being filed on paper.
        /// </summary>
        PaperReturn,

        /// <summary>
        /// Denotes the tax return is being filed via electronic means; excludes SST electronic filing.
        /// </summary>
        ElectronicReturn,

        /// <summary>
        /// Denotes the tax return is an SST filing.
        /// </summary>
        SER,

        /// <summary>
        /// Denotes a return is paid via EFT and filed on paper without payment.
        /// </summary>
        EFTPaper,

        /// <summary>
        /// Denotes a return is paid via phone and filed on paper without payment.
        /// </summary>
        PhonePaper,

        /// <summary>
        /// Denotes a return is prepared but delivered to the customer for filing and payment.
        /// </summary>
        SignatureReady,

        /// <summary>
        /// Denotes a return which is filed online but paid by check.
        /// </summary>
        EfileCheck,

    }
}


text:
<!DOCTYPE html>

    <title>{{ _("Sign up") }} / CvI done</title>
    <link type="text/css" rel="stylesheet" href="/static/css/base.css">

    <form id="reg_form">

            Sign up

                or login
                or try it without registration.

            E-mail:
            <input id="email" type="email" style="width: 150px;" required autofocus>

            {{ _("Password") }}:

                <input id="pwd" type="text" style="width: 150px;" required>

                    {{ _("Please don't use simple passwords like «qwerty», «12345678» or «password».") }}

            Language:

                <select id="locale">
                    <option value="en">English</option>
                    <option value="ru">Русский</option>
                </select>

            Time zone:
            <select id="time_zone"></select>

                <button type="submit">{{ _("Sign up") }}</button>

</form>


text:
var app;
var sound;

define(["sugar-web/activity/activity"], function (activity) {

	// Manipulate the DOM only when it is ready.
	require(['domReady!'], function (doc) {
		// Initialize the activity.
		activity.setup();

		// Create sound component
		sound = new TamTam.Audio();
		sound.renderInto(document.getElementById("audio"));

		// Launch main screen
		app = new TamTam.App({activity: activity});
		app.renderInto(document.getElementById("keyboard"));

		// Stop sound at end of game to sanitize media environment, specifically on Android
		document.getElementById("stop-button").addEventListener('click', function (event) {
			sound.pause();
		});
	});

});


text:
package ru.satahippy.learning.design_patterns.observer.currency_rate;

/**
 * Observer impliment examples using java api (java.util.Observable and java.util.Observer).
 * Currency is a basic class for Dollar, Ruble and Yuan.
 */
public class Main
{
	public static int updatePeriod = 1000;
	public static double minRateAdd = -5;
	public static double maxRateAdd = 5;

	public static void main(String[] args)
	{
		Dollar dollar = new Dollar(5);
		Currency ruble = new Currency("р.", 30);

		Logger logger = new Logger();
		dollar.addObserver(logger);
		ruble.addObserver(logger);

		Notifier rubNorifier = new Notifier(ruble, Notifier.MODE_MORE, 50, "Oh my god! The ruble is fall!");
		Notifier dolNorifier = new Notifier(dollar, Notifier.MODE_LESS, 0, "What's going on?!");

		simulateRateLife(dollar);
		simulateRateLife(ruble);
	}

	protected static Thread simulateRateLife(final Currency currency)
	{
		Thread thread = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				try {
					while (true) {
						currency.setRate(currency.getRate() + getRateAdd());
						Thread.sleep(updatePeriod);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		thread.start();

		return thread;
	}

	protected static double getRateAdd()
	{
		return Math.random() * (maxRateAdd - minRateAdd) + minRateAdd;
	}
}


text:
package FanaticsTestNGAutomationPackage;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class FanaticsSiteSearchBox {

//PAGE OBJECTS

	private final By _btnSiteSearchBoxButton = By.xpath("//button[contains(.,'Search')]");
	private final By _txtSiteSearchBox = By.xpath("//input[@id='searchquery']");

	private final By _h2PeytonManningAutographText = By.xpath("//h2[contains(.,'Autographed Peyton Manning Footballs & Jerseys')]");

//PAGE INITS

	private WebDriver fanaticsSiteSearchBox;

	public void InitfanaticsSiteSearchBox(WebDriver driver)
	{
		fanaticsSiteSearchBox = driver;
	}

//OBJECT METHODS

	public void ClickSiteSearchBoxButton()
	{
		WebDriverWait wait = new WebDriverWait(fanaticsSiteSearchBox, 15);

		WebElement siteSearchBoxButton = wait.until(ExpectedConditions.elementToBeClickable(_btnSiteSearchBoxButton));

		siteSearchBoxButton.click();
	}

	public void EnterTextInSiteSearchBox()
	{
		WebDriverWait wait = new WebDriverWait(fanaticsSiteSearchBox, 15);

		WebElement txtSiteSearchBox = wait.until(ExpectedConditions.elementToBeClickable(_txtSiteSearchBox));

		txtSiteSearchBox.sendKeys("peyton manning");
	}

	public String PeytonManningAutographText()
	{
		WebDriverWait wait = new WebDriverWait(fanaticsSiteSearchBox, 15);

		WebElement peytonManningAutographText = wait.until(ExpectedConditions.elementToBeClickable(_h2PeytonManningAutographText));

		String titleText = peytonManningAutographText.getText();
		return titleText;

	}

}