text:
package cucumber.java.connectors.wire;

import cucumber.java.CucumberOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Socket server that calls a protocol handler line by line
 */
public class SocketServer {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private ProtocolHandler protocolHandler;
    private ServerSocket serverSocket;
    private Socket socket;

    /**
     * Constructor for DI
     */
    public SocketServer(ProtocolHandler protocolHandler) {
        this.protocolHandler = protocolHandler;
    }

    /**
     * Bind and listen to a TCP port
     */
    public void listen(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    /**
     * Accept one connection
     */
    public void acceptOnce() throws Throwable {
        socket = serverSocket.accept();
        processStream(socket.getInputStream(), socket.getOutputStream());
        socket.close();
    }

    private void processStream(InputStream inputStream, OutputStream outputStream) throws Throwable {
        Scanner input = new Scanner(inputStream);
        PrintWriter output = new PrintWriter(outputStream);
        while (input.hasNextLine()) {
            String request = input.nextLine();
            if (CucumberOptions.getOptions().isVerbose()) {
                logger.debug("request " + request);
            }
            String response = protocolHandler.handle(request);
            if (CucumberOptions.getOptions().isVerbose()) {
                logger.debug("response " + response);
            }
            output.println(response);
            output.flush();
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.shumakriss</groupId>
    <artifactId>spring-boot-docker-demo</artifactId>
    <version>1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <profiles>
        <profile>
            <id>local</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>integration-test</goal>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>pre-integration-test</id>
                                <goals>
                                    <goal>start</goal>
                                </goals>
                            </execution>
                            <execution>
                                <id>post-integration-test</id>
                                <goals>
                                    <goal>stop</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>container</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <executions>
                            <execution>
                                <goals>
                                    <goal>integration-test</goal>
                                    <goal>verify</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

redpajama_set_name: RedPajamaGithub


text:
Install Ray for Java
====================

Ray works for Java 8 and above. Currently, we only support building Ray from source.

Build from source
-----------------

Install dependencies
^^^^^^^^^^^^^^^^^^^^

First, make sure JDK 8 or above is installed on your machine. If not, you can download it from `here <http://www.oracle.com/technetwork/java/javase/downloads/index.html>`_.

Then install the following dependencies.

For Ubuntu users, run the following commands:
::

  sudo apt-get update
  sudo apt-get install -y maven build-essential curl unzip psmisc python # we install python here because python2 is required to build the webui

  # If you are not using Anaconda, you need the following.
  sudo apt-get install python-dev  # For Python 2.
  sudo apt-get install python3-dev  # For Python 3.

  pip install cython==0.29.0

For macOS users, run the following commands:
::

  brew update
  brew install maven wget

  pip install cython==0.29.0

Build Ray
^^^^^^^^^

Then we can start building Ray with the following commands:
::

  git clone https://github.com/ray-project/ray.git
  cd ray

  # Install Bazel.
  ci/travis/install-bazel.sh

  # build native components
  ./build.sh -l java

  # build java API
  cd java
  mvn clean install -Dmaven.test.skip

Run tests
^^^^^^^^^
::

  # in `ray/java` directory
  mvn test


text:
<?php
/**
 * Content handler for JavaScript pages.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

/**
 * Content handler for JavaScript pages.
 *
 * @since 1.21
 * @ingroup Content
 * @todo make ScriptContentHandler base class, do highlighting stuff there?
 */
class JavaScriptContentHandler extends TextContentHandler {

	/**
	 * @param string $modelId
	 */
	public function __construct( $modelId = CONTENT_MODEL_JAVASCRIPT ) {
		parent::__construct( $modelId, array( CONTENT_FORMAT_JAVASCRIPT ) );
	}

	/**
	 * @param string $text
	 * @param string $format
	 *
	 * @return JavaScriptContent
	 *
	 * @see ContentHandler::unserializeContent()
	 */
	public function unserializeContent( $text, $format = null ) {
		$this->checkFormat( $format );

		return new JavaScriptContent( $text );
	}

	/**
	 * @return JavaScriptContent A new JavaScriptContent object with empty text.
	 *
	 * @see ContentHandler::makeEmptyContent()
	 */
	public function makeEmptyContent() {
		return new JavaScriptContent( '' );
	}

	/**
	 * Returns the english language, because JS is english, and should be handled as such.
	 *
	 * @param Title $title
	 * @param Content $content
	 *
	 * @return Language wfGetLangObj( 'en' )
	 *
	 * @see ContentHandler::getPageLanguage()
	 */
	public function getPageLanguage( Title $title, Content $content = null ) {
		return wfGetLangObj( 'en' );
	}

	/**
	 * Returns the english language, because JS is english, and should be handled as such.
	 *
	 * @param Title $title
	 * @param Content $content
	 *
	 * @return Language wfGetLangObj( 'en' )
	 *
	 * @see ContentHandler::getPageViewLanguage()
	 */
	public function getPageViewLanguage( Title $title, Content $content = null ) {
		return wfGetLangObj( 'en' );
	}

}


text:
using UnityEngine;
using System.Collections;

public class CameraDrag : MonoBehaviour {

	private float dragSpeed = 0.25f;
	private Vector3 dragOrigin;
	private float spinSpeed = 100f;
	private Vector3 spinTarget = Vector3.zero;
	private float spinThreshold = 1.5f;

	void Start () {

	}

	void Update () {
		if(Input.GetMouseButtonDown (0)){
			dragOrigin = Input.mousePosition;
		}else{
			if(Input.GetMouseButton(0)){
				if(Input.mousePosition.x != dragOrigin.x){
					Camera.main.transform.RotateAround(Vector3.zero, Camera.main.transform.up, dragSpeed * (Input.mousePosition.x - dragOrigin.x));
				}

				if(Input.mousePosition.y != dragOrigin.y){
					Camera.main.transform.RotateAround(Vector3.zero, -Camera.main.transform.right, dragSpeed * (Input.mousePosition.y - dragOrigin.y));
				}
			}
			dragOrigin = Input.mousePosition;
		}

		Vector2 diff = dragOrigin - Input.mousePosition;

		if(spinTarget != Vector3.zero){
			if(Vector3.Distance(Camera.main.transform.position, spinTarget) > spinThreshold){
				Camera.main.transform.RotateAround (Vector3.zero, -Vector3.Cross (spinTarget, Camera.main.transform.position), spinSpeed * Time.deltaTime);
			}
		}
	}

	public void RotateToLookAt (Vector3 pos) {
		spinTarget = pos.normalized * Camera.main.transform.position.magnitude;
	}
}


text:
package org.appfuse.dao.base;

import java.util.List;

import org.appfuse.model.base.BaseObject;

public interface BaseDAO {
	void save(BaseObject object);

	void saveOrUpdate(BaseObject object);

	void update(BaseObject object);

	void removeAll(BaseObject object);

	void removeSome(BaseObject object, String[] ids);

	void remove(BaseObject object);

	void removeSome(String remove_condition);

	List query(String query_condition);

	List query(BaseObject object);

	BaseObject getObject(BaseObject object);

	List getObjects(BaseObject object);
}


text:
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

namespace TunnelVisionLabs.Collections.Trees.Test.Immutable
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.Immutable;
    using System.Linq;
    using TunnelVisionLabs.Collections.Trees.Immutable;
    using Xunit;

    public partial class ImmutableTreeListBuilderTest
    {
        [Fact]
        public void TestTreeListConstructor()
        {
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            Assert.Empty(list);
        }

        [Fact]
        public void TestIListInterface()
        {
            TestIListInterfaceImpl(ImmutableTreeList.Create(600, 601).ToBuilder(), supportsNullValues: false);
            TestIListInterfaceImpl(ImmutableTreeList.Create<int?>(600, 601).ToBuilder(), supportsNullValues: true);
            TestIListInterfaceImpl(ImmutableTreeList.Create<object>(600, 601).ToBuilder(), supportsNullValues: true);

            // Run the same set of tests on List<T> to ensure consistent behavior
            TestIListInterfaceImpl(new List<int> { 600, 601 }, supportsNullValues: false);
            TestIListInterfaceImpl(new List<int?> { 600, 601 }, supportsNullValues: true);
            TestIListInterfaceImpl(new List<object> { 600, 601 }, supportsNullValues: true);
        }

        private static void TestIListInterfaceImpl(IList list, bool supportsNullValues)
        {
            Assert.False(list.IsFixedSize);
            Assert.False(list.IsReadOnly);

            Assert.Equal(600, list[0]);
            Assert.Equal(601, list[1]);

            Assert.True(list.Contains(600));
            Assert.False(list.Contains("Text"));
            Assert.False(list.Contains(null));

            Assert.Equal(0, list.IndexOf(600));
            Assert.Equal(1, list.IndexOf(601));
            Assert.Equal(-1, list.IndexOf("Text"));
            Assert.Equal(-1, list.IndexOf(null));

            Assert.Throws<ArgumentOutOfRangeException>(() => list[-1]);
            Assert.Throws<ArgumentOutOfRangeException>(() => list[-1] = 1);
            Assert.Throws<ArgumentOutOfRangeException>(() => list[list.Count]);
            Assert.Throws<ArgumentOutOfRangeException>(() => list[list.Count] = 1);
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, 602));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(list.Count + 1, 602));

            Assert.NotEqual(list[1], list[0]);
            list.Insert(0, list[0]);
            Assert.Equal(list[1], list[0]);

            int originalCount = list.Count;
            list.Remove(null);
            list.Remove("Text");
            Assert.Equal(originalCount, list.Count);

            object? removedItem = list[0];
            list.Remove(list[0]);
            Assert.Equal(originalCount - 1, list.Count);
            Assert.True(list.Contains(removedItem));

            if (supportsNullValues)
            {
                Assert.Equal(list.Count, list.Add(null));
                Assert.Null(list[list.Count - 1]);
                Assert.True(list.Contains(null));
                Assert.Equal(list.Count - 1, list.IndexOf(null));

                list[list.Count - 1] = 603;
                Assert.Equal(603, list[list.Count - 1]);
                Assert.False(list.Contains(null));
                Assert.Equal(-1, list.IndexOf(null));

                list[list.Count - 1] = null;
                Assert.Null(list[list.Count - 1]);
            }
            else
            {
                // In the face of two errors, verify consistent behavior
                Assert.Throws<ArgumentNullException>(() => list[list.Count] = null);
                Assert.Throws<ArgumentNullException>(() => list.Insert(-1, null));

                Assert.Throws<ArgumentNullException>(() => list.Add(null));
                Assert.Throws<ArgumentNullException>(() => list[list.Count - 1] = null);
                Assert.Throws<ArgumentException>(() => list.Add(new object()));
                Assert.Throws<ArgumentException>(() => list[list.Count - 1] = new object());
                Assert.Throws<ArgumentException>(() => list.Insert(0, new object()));
                Assert.Equal(list.Count, list.Add(602));
            }
        }

        [Fact]
        public void TestICollectionInterface()
        {
            TestICollectionInterfaceImpl(ImmutableTreeList.Create(600, 601).ToBuilder(), isOwnSyncRoot: true, supportsNullValues: false);
            TestICollectionInterfaceImpl(ImmutableTreeList.Create<int?>(600, 601).ToBuilder(), isOwnSyncRoot: true, supportsNullValues: true);
            TestICollectionInterfaceImpl(ImmutableTreeList.Create<object>(600, 601).ToBuilder(), isOwnSyncRoot: true, supportsNullValues: true);

            ICollection collection = ImmutableTreeList<int>.Empty.ToBuilder();
            collection.CopyTo(new int[0], 0);

            // Type checks are only performed if the collection has items
            collection.CopyTo(new string[0], 0);

            collection = ImmutableTreeList.CreateRange(Enumerable.Range(0, 100)).ToBuilder();
            var array = new int[collection.Count];
            collection.CopyTo(array, 0);
            Assert.Equal(array, collection);

            // Run the same set of tests on ImmutableList<T>.Builder to ensure consistent behavior
            TestICollectionInterfaceImpl(ImmutableList.Create(600, 601).ToBuilder(), isOwnSyncRoot: false, supportsNullValues: false);
            TestICollectionInterfaceImpl(ImmutableList.Create<int?>(600, 601).ToBuilder(), isOwnSyncRoot: false, supportsNullValues: true);
            TestICollectionInterfaceImpl(ImmutableList.Create<object>(600, 601).ToBuilder(), isOwnSyncRoot: false, supportsNullValues: true);
        }

        private static void TestICollectionInterfaceImpl(ICollection collection, bool isOwnSyncRoot, bool supportsNullValues)
        {
            Assert.False(collection.IsSynchronized);

            if (isOwnSyncRoot)
            {
                Assert.Same(collection, collection.SyncRoot);
            }
            else
            {
                Assert.IsType<object>(collection.SyncRoot);
                Assert.Same(collection.SyncRoot, collection.SyncRoot);
            }

            Assert.Throws<ArgumentNullException>("array", () => collection.CopyTo(null!, 0));
            Assert.Throws<ArgumentException>(() => collection.CopyTo(new int[collection.Count, 1], 0));

            void CopyToArrayWithNonZeroLowerBound() => collection.CopyTo(Array.CreateInstance(typeof(int), lengths: new[] { collection.Count }, lowerBounds: new[] { 1 }), 0);
            if (collection.GetType().GetGenericTypeDefinition() == typeof(ImmutableList<>.Builder))
            {
                Assert.Throws<IndexOutOfRangeException>(CopyToArrayWithNonZeroLowerBound);
            }
            else
            {
                Assert.Throws<ArgumentException>(CopyToArrayWithNonZeroLowerBound);
            }

            if (supportsNullValues)
            {
                var copy = new object[collection.Count];

                Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(copy, -1));
                Assert.All(copy, Assert.Null);
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(copy, 1));
                Assert.All(copy, Assert.Null);

                collection.CopyTo(copy, 0);
                Assert.Equal(600, copy[0]);
                Assert.Equal(601, copy[1]);

                copy = new object[collection.Count + 2];
                collection.CopyTo(copy, 1);
                Assert.Null(copy[0]);
                Assert.Equal(600, copy[1]);
                Assert.Equal(601, copy[2]);
                Assert.Null(copy[3]);

                Assert.Throws<InvalidCastException>(() => collection.CopyTo(new string[collection.Count], 0));
            }
            else
            {
                var copy = new int[collection.Count];

                Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(copy, -1));
                Assert.All(copy, item => Assert.Equal(0, item));
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(copy, 1));
                Assert.All(copy, item => Assert.Equal(0, item));

                collection.CopyTo(copy, 0);
                Assert.Equal(600, copy[0]);
                Assert.Equal(601, copy[1]);

                copy = new int[collection.Count + 2];
                collection.CopyTo(copy, 1);
                Assert.Equal(0, copy[0]);
                Assert.Equal(600, copy[1]);
                Assert.Equal(601, copy[2]);
                Assert.Equal(0, copy[3]);

                Assert.Throws<InvalidCastException>(() => collection.CopyTo(new string[collection.Count], 0));
            }
        }

        [Fact]
        public void TestICollectionTInterface()
        {
            TestICollectionTInterfaceImpl(ImmutableTreeList.Create(600, 601).ToBuilder(), supportsNullValues: false);
            TestICollectionTInterfaceImpl(ImmutableTreeList.Create<int?>(600, 601).ToBuilder(), supportsNullValues: true);
            TestICollectionTInterfaceImpl(ImmutableTreeList.Create<object>(600, 601).ToBuilder(), supportsNullValues: true);

            // Run the same set of tests on ImmutableList<T>.Builder to ensure consistent behavior
            TestICollectionTInterfaceImpl(ImmutableList.Create(600, 601).ToBuilder(), supportsNullValues: false);
            TestICollectionTInterfaceImpl(ImmutableList.Create<int?>(600, 601).ToBuilder(), supportsNullValues: true);
            TestICollectionTInterfaceImpl(ImmutableList.Create<object>(600, 601).ToBuilder(), supportsNullValues: true);
        }

        private static void TestICollectionTInterfaceImpl<T>(ICollection<T> collection, bool supportsNullValues)
        {
            Assert.False(collection.IsReadOnly);

            Assert.Equal(2, collection.Count);

            if (supportsNullValues)
            {
                var copy = new T[collection.Count];

                Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(copy, -1));
                Assert.All(copy, item => Assert.Equal(default!, item));
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(copy, 1));
                Assert.All(copy, item => Assert.Equal(default!, item));

                collection.CopyTo(copy, 0);
                Assert.Equal<object?>(600, copy[0]);
                Assert.Equal<object?>(601, copy[1]);

                copy = new T[collection.Count + 2];
                collection.CopyTo(copy, 1);
                Assert.Equal(default!, copy[0]);
                Assert.Equal<object?>(600, copy[1]);
                Assert.Equal<object?>(601, copy[2]);
                Assert.Equal(default!, copy[3]);
            }
            else
            {
                var copy = new T[collection.Count];

                Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(copy, -1));
                Assert.All(copy, item => Assert.Equal(default!, item));
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(copy, 1));
                Assert.All(copy, item => Assert.Equal(default!, item));

                collection.CopyTo(copy, 0);
                Assert.Equal<object?>(600, copy[0]);
                Assert.Equal<object?>(601, copy[1]);

                copy = new T[collection.Count + 2];
                collection.CopyTo(copy, 1);
                Assert.Equal(default!, copy[0]);
                Assert.Equal<object?>(600, copy[1]);
                Assert.Equal<object?>(601, copy[2]);
                Assert.Equal(default!, copy[3]);
            }
        }

        [Fact]
        public void TestIndexer()
        {
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateRange(Enumerable.Range(0, 10)).ToBuilder();
            Assert.Throws<ArgumentOutOfRangeException>(() => list[-1]);
            Assert.Throws<ArgumentOutOfRangeException>(() => list[-1] = 0);
            Assert.Throws<ArgumentOutOfRangeException>(() => list[list.Count]);
            Assert.Throws<ArgumentOutOfRangeException>(() => list[list.Count] = 0);

            for (int i = 0; i < list.Count; i++)
            {
                Assert.Equal(i, list[i]);
                list[i] = ~list[i];
                Assert.Equal(~i, list[i]);
            }
        }

        [Fact]
        public void TestCopyToValidation()
        {
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateRange(Enumerable.Range(0, 10)).ToBuilder();
            Assert.Throws<ArgumentNullException>("array", () => list.CopyTo(null!));
            Assert.Throws<ArgumentNullException>("array", () => list.CopyTo(0, null!, 0, list.Count));
            Assert.Throws<ArgumentOutOfRangeException>("index", () => list.CopyTo(-1, new int[list.Count], 0, list.Count));
            Assert.Throws<ArgumentOutOfRangeException>("arrayIndex", () => list.CopyTo(0, new int[list.Count], -1, list.Count));
            Assert.Throws<ArgumentOutOfRangeException>("count", () => list.CopyTo(0, new int[list.Count], 0, -1));
            Assert.Throws<ArgumentOutOfRangeException>(null, () => list.CopyTo(1, new int[list.Count], 0, list.Count));
            Assert.Throws<ArgumentOutOfRangeException>(string.Empty, () => list.CopyTo(0, new int[list.Count], 1, list.Count));
        }

        [Fact]
        public void TestAdd()
        {
            const int Value = 600;

            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            Assert.Empty(list);
            list.Add(Value);
            Assert.Single(list);
            Assert.Equal(Value, list[0]);
            int[] expected = { Value };
            int[] actual = list.ToArray();
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestAddStaysPacked()
        {
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
                list.Add(i);

            list.Validate(ValidationRules.RequirePacked);
        }

        [Fact]
        public void TestAddMany()
        {
            int[] expected = Enumerable.Range(600, 8 * 9).ToArray();

            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            foreach (var item in expected)
            {
                list.Add(item);
                list.Validate(ValidationRules.RequirePacked);
                Assert.Equal(item, list[list.Count - 1]);
            }

            Assert.Equal(expected.Length, list.Count);

            int[] actual = list.ToArray();
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestAddRange()
        {
            int[] expected = Enumerable.Range(600, 8 * 9).ToArray();

            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            CollectionAssert.EnumeratorInvalidated(list, () => list.AddRange(expected));

            Assert.Throws<ArgumentNullException>("collection", () => list.AddRange(null!));
            CollectionAssert.EnumeratorNotInvalidated(list, () => list.AddRange(Enumerable.Empty<int>()));

            Assert.Equal(expected.Length, list.Count);

            int[] actual = list.ToArray();
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestClear()
        {
            var list = ImmutableTreeList.CreateRange(Enumerable.Range(600, 8 * 9)).ToBuilder();
            Assert.Equal(8 * 9, list.Count);
            CollectionAssert.EnumeratorInvalidated(list, () => list.Clear());
            Assert.Empty(list);

            // If the list is already clear, existing iterators are not invalidated
            CollectionAssert.EnumeratorNotInvalidated(list, () => list.Clear());
            Assert.Empty(list);
        }

        [Fact]
        public void TestInsert()
        {
            const int Value = 600;

            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            Assert.Empty(list);
            list.Insert(0, Value);
            Assert.Single(list);
            Assert.Equal(Value, list[0]);
            int[] expected = { Value };
            int[] actual = list.ToArray();
            Assert.Equal(expected, actual);

            List<int> reference = new List<int>(list);
            Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(-1, item: 0));
            Assert.Throws<ArgumentOutOfRangeException>("index", () => reference.Insert(-1, item: 0));
            Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Insert(list.Count + 1, item: 0));
            Assert.Throws<ArgumentOutOfRangeException>("index", () => reference.Insert(list.Count + 1, item: 0));
        }

        [Fact]
        public void TestInsertMany()
        {
            int[] expected = Enumerable.Range(600, 8 * 9).ToArray();

            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            foreach (var item in expected.Reverse())
            {
                list.Insert(0, item);
                list.Validate(ValidationRules.None);
                Assert.Equal(item, list[0]);
            }

            Assert.Equal(expected.Length, list.Count);

            int[] actual = list.ToArray();
            Assert.Equal(expected, actual);
        }

        [Fact]
        public void TestInsertRange()
        {
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();

            Assert.Throws<ArgumentNullException>("collection", () => list.InsertRange(0, null!));
            Assert.Throws<ArgumentOutOfRangeException>("index", () => list.InsertRange(-1, Enumerable.Empty<int>()));
            Assert.Throws<ArgumentOutOfRangeException>(null, () => list.InsertRange(1, Enumerable.Empty<int>()));

            // Add an initial range to each list
            list.InsertRange(0, Enumerable.Range(0, 8 * 9));
            reference.InsertRange(0, Enumerable.Range(0, 8 * 9));
            list.Validate(ValidationRules.RequirePacked);
            Assert.Equal(reference, list);

            // Adding more items to the end keeps things packed
            list.InsertRange(list.Count, Enumerable.Range(0, 8 * 9));
            reference.InsertRange(reference.Count, Enumerable.Range(0, 8 * 9));
            list.Validate(ValidationRules.RequirePacked);
            Assert.Equal(reference, list);

            // Add items to the beginning (no longer packed)
            list.InsertRange(0, Enumerable.Range(0, 8 * 9));
            reference.InsertRange(0, Enumerable.Range(0, 8 * 9));
            list.Validate(ValidationRules.None);
            Assert.Equal(reference, list);

            // Add items to the middle
            list.InsertRange(list.Count / 2, Enumerable.Range(0, 8 * 9));
            reference.InsertRange(reference.Count / 2, Enumerable.Range(0, 8 * 9));
            list.Validate(ValidationRules.None);
            Assert.Equal(reference, list);

            // Add a small range near the beginning
            list.InsertRange(1, Enumerable.Range(0, 1));
            reference.InsertRange(1, Enumerable.Range(0, 1));
            list.Validate(ValidationRules.None);
            Assert.Equal(reference, list);
        }

        [Fact]
        public void TestBinarySearchFullList()
        {
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                list.Add(i * 2);
                reference.Add(i * 2);
            }

            Assert.Throws<ArgumentOutOfRangeException>("index", () => list.BinarySearch(index: -1, list.Count, 0, comparer: null));
            Assert.Throws<ArgumentOutOfRangeException>("count", () => list.BinarySearch(0, count: -1, 0, comparer: null));
            Assert.Throws<ArgumentException>(() => list.BinarySearch(1, list.Count, 0, comparer: null));

            // Test below start value
            Assert.Equal(reference.BinarySearch(reference[0] - 1), list.BinarySearch(reference[0] - 1));

            for (int i = 0; i < reference.Count; i++)
            {
                // Test current value
                Assert.Equal(reference.BinarySearch(reference[i]), list.BinarySearch(reference[i]));

                // Test above current value
                Assert.Equal(reference.BinarySearch(reference[i] + 1), list.BinarySearch(reference[i] + 1));
            }

            // Test case where an exception is thrown by the comparer
            var expected = new NotSupportedException();
            InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => list.BinarySearch(0, new ComparisonComparer<int>((x, y) => throw expected)));
            Assert.Same(expected, exception.InnerException);
            exception = Assert.Throws<InvalidOperationException>(() => reference.BinarySearch(0, new ComparisonComparer<int>((x, y) => throw expected)));
            Assert.Same(expected, exception.InnerException);

            ImmutableTreeList<int>.Builder empty = ImmutableTreeList.CreateBuilder<int>();
            Assert.Equal(~0, empty.BinarySearch(0));
        }

        [Fact]
        public void TestIndexOf()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                list.Insert(index, i);
                reference.Insert(index, i);
            }

            Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(list[0], -1));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(list[0], 0, -1));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.IndexOf(list[0], 0, list.Count + 1));

            Assert.Equal(-1, list.IndexOf(-1));

            for (int i = 0; i < list.Count; i++)
            {
                Assert.Equal(reference.IndexOf(i), list.IndexOf(i));

                int firstIndex = list.IndexOf(i);
                Assert.Equal(reference.IndexOf(i, firstIndex + 1), list.IndexOf(i, firstIndex + 1));
            }

            ImmutableTreeList<int>.Builder empty = ImmutableTreeList.CreateBuilder<int>();
            Assert.Equal(-1, empty.IndexOf(0));

            // Test with a custom equality comparer
            var stringList = ImmutableTreeList.Create<string>("aa", "aA", "Aa", "AA").ToBuilder();
            Assert.Equal(3, stringList.IndexOf("AA", 0, stringList.Count, StringComparer.Ordinal));
            Assert.Equal(0, stringList.IndexOf("AA", 0, stringList.Count, StringComparer.OrdinalIgnoreCase));
        }

        [Fact]
        public void TestLastIndexOf()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            Assert.Equal(-1, list.LastIndexOf(0, -1, 0));
            Assert.Equal(-1, reference.LastIndexOf(0, -1, 0));

            // LastIndexOf does not validate anything for empty collections
            Assert.Equal(-1, list.LastIndexOf(0, 0, 0));
            Assert.Equal(-1, reference.LastIndexOf(0, 0, 0));
            Assert.Equal(-1, list.LastIndexOf(0, -40, -50));
            Assert.Equal(-1, reference.LastIndexOf(0, -40, -50));
            Assert.Equal(-1, list.LastIndexOf(0, 40, 50));
            Assert.Equal(-1, reference.LastIndexOf(0, 40, 50));

            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                list.Insert(index, i);
                reference.Insert(index, i);
            }

            Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(list[0], list.Count));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(list[0], list.Count - 1, -1));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.LastIndexOf(list[0], list.Count - 1, list.Count + 1));

            Assert.Equal(-1, list.LastIndexOf(-1));
            Assert.Equal(-1, list.LastIndexOf(-1, list.Count - 1, list.Count / 2));

            for (int i = 0; i < list.Count; i++)
            {
                Assert.Equal(reference.LastIndexOf(i), list.LastIndexOf(i));

                int lastIndex = list.LastIndexOf(i);
                if (lastIndex < 1)
                    continue;

                Assert.Equal(reference.LastIndexOf(i, lastIndex - 1), list.LastIndexOf(i, lastIndex - 1));
            }

            // Test with a custom equality comparer
            var stringList = ImmutableTreeList.Create<string>("aa", "aA", "Aa", "AA").ToBuilder();
            Assert.Equal(0, stringList.LastIndexOf("aa", stringList.Count - 1, stringList.Count, StringComparer.Ordinal));
            Assert.Equal(3, stringList.LastIndexOf("aa", stringList.Count - 1, stringList.Count, StringComparer.OrdinalIgnoreCase));
        }

        [Fact]
        public void TestLastIndexOfInvalidOperations()
        {
            ImmutableTreeList<int>.Builder single = ImmutableTreeList.CreateRange(Enumerable.Range(1, 1)).ToBuilder();
            Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => single.LastIndexOf(0, -1, 0));
            Assert.Throws<ArgumentOutOfRangeException>(() => single.LastIndexOf(0, 1, 0));
            Assert.Throws<ArgumentOutOfRangeException>("count", () => single.LastIndexOf(0, 0, -1));
            Assert.Throws<ArgumentOutOfRangeException>(() => single.LastIndexOf(0, 0, 2));
        }

        [Fact]
        public void TestFindIndex()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                list.Insert(index, i);
                reference.Insert(index, i);
            }

            Assert.Throws<ArgumentNullException>(() => list.FindIndex(null!));
            Assert.Throws<ArgumentNullException>(() => list.FindIndex(0, null!));
            Assert.Throws<ArgumentNullException>(() => list.FindIndex(0, 0, null!));

            Assert.Throws<ArgumentOutOfRangeException>(() => list.FindIndex(-1, i => true));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.FindIndex(0, -1, i => true));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.FindIndex(0, list.Count + 1, i => true));

            Assert.Equal(-1, list.FindIndex(_ => false));

            for (int i = 0; i < list.Count; i++)
            {
                Predicate<int> predicate = value => value == i;
                Assert.Equal(reference.FindIndex(predicate), list.FindIndex(predicate));

                int firstIndex = list.FindIndex(predicate);
                Assert.Equal(reference.FindIndex(firstIndex + 1, predicate), list.FindIndex(firstIndex + 1, predicate));
            }

            ImmutableTreeList<int>.Builder empty = ImmutableTreeList.CreateBuilder<int>();
            Assert.Equal(-1, empty.FindIndex(i => true));
        }

        [Fact]
        public void TestFindLastIndex()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            Assert.Throws<ArgumentOutOfRangeException>(() => list.FindLastIndex(0, 0, i => true));
            Assert.Throws<ArgumentOutOfRangeException>(() => reference.FindLastIndex(0, 0, i => true));
            Assert.Equal(-1, list.FindLastIndex(-1, 0, i => true));
            Assert.Equal(-1, reference.FindLastIndex(-1, 0, i => true));

            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                list.Insert(index, i);
                reference.Insert(index, i);
            }

            Assert.Throws<ArgumentNullException>(() => list.FindLastIndex(null!));
            Assert.Throws<ArgumentNullException>(() => list.FindLastIndex(-1, null!));
            Assert.Throws<ArgumentNullException>(() => list.FindLastIndex(-1, 0, null!));

            Assert.Throws<ArgumentOutOfRangeException>(() => list.FindLastIndex(list.Count, i => true));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.FindLastIndex(list.Count - 1, -1, i => true));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.FindLastIndex(list.Count - 1, list.Count + 1, i => true));

            Assert.Equal(-1, list.FindLastIndex(_ => false));
            Assert.Equal(-1, list.FindLastIndex(list.Count - 1, list.Count / 2, _ => false));

            for (int i = 0; i < list.Count; i++)
            {
                Predicate<int> predicate = value => value == i;
                Assert.Equal(reference.FindLastIndex(predicate), list.FindLastIndex(predicate));

                int lastIndex = list.FindLastIndex(predicate);
                if (lastIndex < 1)
                    continue;

                Assert.Equal(reference.FindLastIndex(lastIndex - 1, predicate), list.FindLastIndex(lastIndex - 1, predicate));
            }
        }

        [Fact]
        public void TestConvertAll()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                int item = random.Next();
                list.Insert(index, item);
                reference.Insert(index, item);
            }

            ImmutableTreeList<string> stringList = list.ConvertAll(value => value.ToString());
            List<string> referenceStringList = reference.ConvertAll(value => value.ToString());

            stringList.Validate(ValidationRules.None);
            Assert.Equal(reference, list);
            Assert.Equal(referenceStringList, stringList);

            ImmutableTreeList<int>.Builder empty = ImmutableTreeList.CreateBuilder<int>();
            Assert.Empty(empty);
            ImmutableTreeList<string> stringEmpty = empty.ConvertAll(value => value.ToString());
            Assert.Empty(stringEmpty);
        }

        [Fact]
        public void TestTrimExcess()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                list.Insert(index, i);
                reference.Insert(index, i);
            }

            list.Validate(ValidationRules.None);

            // In the first call to TrimExcess, items will move
            list.TrimExcess();
            list.Validate(ValidationRules.RequirePacked);
            Assert.Equal(reference, list);

            // In the second call, the list is already packed so nothing will move
            list.TrimExcess();
            list.Validate(ValidationRules.RequirePacked);
            Assert.Equal(reference, list);

            ImmutableTreeList<int>.Builder empty = ImmutableTreeList.CreateBuilder<int>();
            empty.Validate(ValidationRules.RequirePacked);
            empty.TrimExcess();
            empty.Validate(ValidationRules.RequirePacked);

            ImmutableTreeList<int>.Builder single = ImmutableTreeList.CreateRange(Enumerable.Range(0, 1)).ToBuilder();
            single.Validate(ValidationRules.RequirePacked);
            single.TrimExcess();
            single.Validate(ValidationRules.RequirePacked);

            // Construct a poorly-packed list with several levels
            ImmutableTreeList<int>.Builder many = ImmutableTreeList.CreateRange(Enumerable.Range(0, 100)).ToBuilder();
            for (int i = 0; i < 100; i++)
                many.Insert(many.Count / 2, i);

            many.TrimExcess();
            many.Validate(ValidationRules.RequirePacked);

            // Construct a poorly-packed list with frozen nodes
            many = ImmutableTreeList.CreateRange(Enumerable.Range(0, 8)).ToBuilder();
            many.Insert(0, -1);
            ImmutableTreeList<int> immutable = many.ToImmutable();
            ////Assert.Same(immutable, many.ToImmutable());
            many.TrimExcess();
            many.Validate(ValidationRules.RequirePacked);
            Assert.NotSame(immutable, many.ToImmutable());
            Assert.Equal(immutable, many.ToImmutable());
        }

        [Fact]
        public void TestSort()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                int item = random.Next();
                list.Insert(index, item);
                reference.Insert(index, item);
            }

            Assert.Throws<ArgumentOutOfRangeException>(() => list.Sort(-1, 0, null));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Sort(0, -1, null));
            Assert.Throws<ArgumentException>(() => list.Sort(0, list.Count + 1, null));

            // Start by sorting just the first 3 elements
            list.Sort(0, 3, null);
            reference.Sort(0, 3, null);
            list.Validate(ValidationRules.None);
            Assert.Equal(reference, list);

            // Then sort 8 index pages worth
            ImmutableTreeList<int>.Builder tempList = ImmutableTreeList.CreateRange(list.Concat(list)).ToBuilder();
            List<int> tempReference = new List<int>(reference.Concat(reference));
            tempList.Validate(ValidationRules.RequirePacked);
            tempList.Sort(0, 8 * 8, null);
            tempList.Validate(ValidationRules.RequirePacked);
            tempReference.Sort(0, 8 * 8, null);
            Assert.Equal(tempReference, tempList);

            // Then sort everything
            list.Sort();
            reference.Sort();
            list.Validate(ValidationRules.None);
            Assert.Equal(reference, list);

            // Then sort everything in reverse order
            list.Sort(ReverseComparer<int>.Default);
            reference.Sort(ReverseComparer<int>.Default);
            list.Validate(ValidationRules.None);
            Assert.Equal(reference, list);

            // Test sorting an empty list
            ImmutableTreeList<int>.Builder empty = ImmutableTreeList.CreateBuilder<int>();
            empty.Sort();
            Assert.Empty(empty);
            empty.Validate(ValidationRules.RequirePacked);

            // Test sorting a list with all the same value
            ImmutableTreeList<int>.Builder sameValue = ImmutableTreeList.CreateBuilder<int>();
            for (int i = 0; i < 100; i++)
                sameValue.Add(1);

            sameValue.Sort();
            sameValue.Validate(ValidationRules.RequirePacked);
            Assert.Equal(100, sameValue.Count);
            for (int i = 0; i < sameValue.Count; i++)
                Assert.Equal(1, sameValue[i]);
        }

        [Fact]
        public void TestSortComparison()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                int item = random.Next();
                list.Insert(index, item);
                reference.Insert(index, item);
            }

            Assert.Throws<ArgumentNullException>(() => list.Sort((Comparison<int>)null!));

            Comparison<int> comparison = (x, y) => x - y;
            list.Sort(comparison);
            reference.Sort(comparison);
            Assert.Equal(reference, list);
        }

        [Theory]
        [InlineData(1)]
        [InlineData(2)]
        [InlineData(3)]
        [InlineData(4)]
        [InlineData(5)]
        [InlineData(6)]
        [InlineData(11)]
        public void TestRemoveAt(int seed)
        {
            Random random = new Random(seed);
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                int item = random.Next();
                list.Insert(index, item);
                reference.Insert(index, item);
            }

            Assert.Throws<ArgumentOutOfRangeException>("index", () => list.RemoveAt(-1));
            Assert.Throws<ArgumentOutOfRangeException>(null, () => list.RemoveAt(list.Count));

            while (list.Count > 0)
            {
                int index = random.Next(list.Count);
                Assert.Equal(reference[index], list[index]);
                reference.RemoveAt(index);
                list.RemoveAt(index);
                list.Validate(ValidationRules.None);

                Assert.Equal(reference, list);
            }

            Assert.Empty(list);
            Assert.Empty(reference);
        }

        [Fact]
        public void TestReverse()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> ordered = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                int item = random.Next();
                list.Insert(index, item);
                ordered.Insert(index, item);
            }

            list.Reverse();
            for (int i = 0; i < list.Count; i++)
            {
                Assert.Equal(ordered[i], list[list.Count - 1 - i]);
            }

            list.Reverse();
            Assert.Equal(ordered, list);

            Assert.Throws<ArgumentOutOfRangeException>("index", () => list.Reverse(-1, 0));
            Assert.Throws<ArgumentOutOfRangeException>("count", () => list.Reverse(0, -1));
            Assert.Throws<ArgumentException>(null, () => list.Reverse(list.Count, 1));

            CollectionAssert.EnumeratorNotInvalidated(list, () => list.Reverse(3, count: 0));
            Assert.Equal(ordered, list);

            CollectionAssert.EnumeratorInvalidated(list, () => list.Reverse(3, count: 1));
            Assert.Equal(ordered, list);
        }

        [Fact]
        public void TestQueueLikeBehavior()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int item = random.Next();
                list.Add(item);
                reference.Add(item);
            }

            while (list.Count > 0)
            {
                Assert.Equal(reference[0], list[0]);
                reference.RemoveAt(0);
                list.RemoveAt(0);
                list.Validate(ValidationRules.None);

                Assert.Equal(reference, list);
            }

            Assert.Empty(list);
            Assert.Empty(reference);
        }

        [Fact]
        public void TestStackLikeBehavior()
        {
            Random random = new Random();
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int item = random.Next();
                list.Add(item);
                reference.Add(item);
            }

            while (list.Count > 0)
            {
                Assert.Equal(reference[reference.Count - 1], list[list.Count - 1]);
                reference.RemoveAt(reference.Count - 1);
                list.RemoveAt(list.Count - 1);
                list.Validate(ValidationRules.None);

                Assert.Equal(reference, list);
            }

            Assert.Empty(list);
            Assert.Empty(reference);
        }

        [Fact]
        public void TestEnumerator()
        {
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            ImmutableTreeList<int>.Enumerator enumerator = list.GetEnumerator();
            Assert.Equal(0, enumerator.Current);
            Assert.False(enumerator.MoveNext());
            Assert.Equal(0, enumerator.Current);
            Assert.False(enumerator.MoveNext());
            Assert.Equal(0, enumerator.Current);

            // Adding an item to the list invalidates it, but Current is still unchecked
            list.Add(1);
            Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
            Assert.Equal(0, enumerator.Current);

            enumerator = list.GetEnumerator();
            Assert.Equal(0, enumerator.Current);
            Assert.True(enumerator.MoveNext());
            Assert.Equal(1, enumerator.Current);

            // Reset has no effect due to boxing the value type
            ((IEnumerator<int>)enumerator).Reset();
            Assert.Equal(1, enumerator.Current);
            Assert.False(enumerator.MoveNext());
            Assert.Equal(1, enumerator.Current);
        }

        [Fact]
        public void TestPartialEnumeration()
        {
            Random random = new Random(1);
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            List<int> reference = new List<int>();
            for (int i = 0; i < 4 * 8 * 8; i++)
            {
                int index = random.Next(list.Count + 1);
                list.Insert(index, i);
                reference.Insert(index, i);
            }

            // Test a subsection of the list
            var listEnumerator = new ImmutableTreeList<int>.Enumerator(list.ToImmutable(), TreeSpan.FromBounds(1, list.Count - 1), list);
            IEnumerator<int> referenceEnumerator = reference.Skip(1).Take(reference.Count - 2).GetEnumerator();
            TestEnumerators(referenceEnumerator, listEnumerator);

            // Test the first half
            listEnumerator = new ImmutableTreeList<int>.Enumerator(list.ToImmutable(), TreeSpan.FromBounds(0, list.Count / 2), list);
            referenceEnumerator = reference.Take(reference.Count / 2).GetEnumerator();
            TestEnumerators(referenceEnumerator, listEnumerator);

            // Test the last half
            listEnumerator = new ImmutableTreeList<int>.Enumerator(list.ToImmutable(), TreeSpan.FromBounds(list.Count / 2, list.Count), list);
            referenceEnumerator = reference.Skip(reference.Count / 2).GetEnumerator();
            TestEnumerators(referenceEnumerator, listEnumerator);

            void TestEnumerators(IEnumerator<int> expected, ImmutableTreeList<int>.Enumerator actual)
            {
                Assert.Equal(referenceEnumerator.Current, listEnumerator.Current);

                while (true)
                {
                    if (!referenceEnumerator.MoveNext())
                    {
                        Assert.False(listEnumerator.MoveNext());
                        break;
                    }

                    Assert.True(listEnumerator.MoveNext());
                    Assert.Equal(referenceEnumerator.Current, listEnumerator.Current);
                }

                Assert.Equal(referenceEnumerator.Current, listEnumerator.Current);
            }
        }

        [Fact]
        public void TestIEnumeratorT()
        {
            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            IEnumerator<int> enumerator = list.GetEnumerator();
            Assert.Equal(0, enumerator.Current);
            Assert.False(enumerator.MoveNext());
            Assert.Equal(0, enumerator.Current);

            // Adding an item to the list invalidates it, but Current is still unchecked
            list.Add(1);
            Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
            Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
            Assert.Equal(0, enumerator.Current);

            enumerator = list.GetEnumerator();
            Assert.Equal(0, enumerator.Current);
            Assert.True(enumerator.MoveNext());
            Assert.Equal(1, enumerator.Current);
            Assert.False(enumerator.MoveNext());
            Assert.Equal(1, enumerator.Current);

            enumerator.Reset();
            Assert.Equal(0, enumerator.Current);
            Assert.True(enumerator.MoveNext());
            Assert.Equal(1, enumerator.Current);
            enumerator.Reset();
            Assert.Equal(0, enumerator.Current);
            Assert.True(enumerator.MoveNext());
            Assert.Equal(1, enumerator.Current);
            Assert.False(enumerator.MoveNext());
            Assert.Equal(1, enumerator.Current);
        }

        [Fact]
        public void TestRemoveValue()
        {
            var list = ImmutableTreeList.CreateRange(Enumerable.Range(0, 8 * 4)).ToBuilder();
            Assert.False(list.Remove(-1));
            Assert.Equal(8 * 4, list.Count);
            Assert.True(list.Remove(3));
            Assert.Equal((8 * 4) - 1, list.Count);
        }

        [Fact]
        public void TestRemoveAll()
        {
            var list = ImmutableTreeList.CreateRange(Enumerable.Range(0, 20)).ToBuilder();
            Assert.Throws<ArgumentNullException>(() => list.RemoveAll(null!));

            Assert.Equal(10, list.RemoveAll(i => (i % 2) == 0));
            Assert.Equal(new[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 }, list);
            Assert.Equal(0, list.RemoveAll(i => i < 0));
            Assert.Equal(10, list.Count);
        }

        [Fact]
        public void TestExists()
        {
            var list = ImmutableTreeList.CreateRange(Enumerable.Range(0, 20)).ToBuilder();
            Assert.Throws<ArgumentNullException>(() => list.Exists(null!));

            Assert.False(list.Exists(value => value < 0));
            foreach (var i in list)
            {
                Assert.True(list.Exists(value => value == i));
            }

            Assert.False(list.Exists(value => value > 20));
        }

        [Fact]
        public void TestFind()
        {
            var list = ImmutableTreeList.CreateRange(Enumerable.Range(1, 20)).ToBuilder();
            Assert.Throws<ArgumentNullException>(() => list.Find(null!));

            Assert.Equal(0, list.Find(value => value < 0));
            foreach (var i in list)
            {
                Assert.Equal(i, list.Find(value => value == i));
            }

            Assert.Equal(2, list.Find(value => value > 1));
        }

        [Fact]
        public void TestFindAll()
        {
            var list = ImmutableTreeList.CreateRange(Enumerable.Range(0, 20)).ToBuilder();
            Assert.Throws<ArgumentNullException>(() => list.FindAll(null!));

            ImmutableTreeList<int> found = list.FindAll(i => (i % 2) == 0);

            Assert.Equal(20, list.Count);
            Assert.Equal(10, found.Count);
            Assert.Equal(new[] { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18 }, found);

            Assert.Empty(list.FindAll(i => i < 0));
        }

        [Fact]
        public void TestFindLast()
        {
            var list = ImmutableTreeList.CreateRange(Enumerable.Range(1, 20)).ToBuilder();
            var reference = new List<int>(Enumerable.Range(1, 20));
            Assert.Throws<ArgumentNullException>(() => list.FindLast(null!));

            Assert.Equal(0, list.FindLast(i => i < 0));
            Assert.Equal(0, reference.FindLast(i => i < 0));

            Assert.Equal(20, list.FindLast(value => (value % 2) == 0));
            Assert.Equal(20, reference.FindLast(value => (value % 2) == 0));

            Assert.Equal(4, list.FindLast(value => value < 5));
            Assert.Equal(4, reference.FindLast(value => value < 5));
        }

        [Fact]
        public void TestToImmutable()
        {
            int value = Generator.GetInt32();

            ImmutableTreeList<int>.Builder list = ImmutableTreeList.CreateBuilder<int>();
            Assert.Empty(list);
            Assert.Same(ImmutableTreeList<int>.Empty, list.ToImmutable());

            list.Add(value);
            Assert.Equal(new[] { value }, list.ToImmutable());
            Assert.Same(list.ToImmutable(), list.ToImmutable());

            list.Add(value);
            Assert.Equal(new[] { value, value }, list.ToImmutable());
            Assert.Same(list.ToImmutable(), list.ToImmutable());
        }

        [Fact]
        public void TestTrueForAll()
        {
            var list = ImmutableTreeList.CreateBuilder<int>();
            Assert.True(list.TrueForAll(i => false));
            Assert.Throws<ArgumentNullException>(() => list.TrueForAll(null!));

            list.Add(1);
            Assert.True(list.TrueForAll(i => i > 0));
            Assert.False(list.TrueForAll(i => i <= 0));
        }
    }
}


text:
/**
 * Swaggy Jenkins
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * The version of the OpenAPI document: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 6.0.0.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

/*
 * ComputerSet.h
 *
 *
 */

#ifndef ComputerSet_H_
#define ComputerSet_H_

#include <string>
#include "HudsonMasterComputer.h"
#include <vector>
#include <memory>
#include <vector>
#include <boost/property_tree/ptree.hpp>

namespace org {
namespace openapitools {
namespace server {
namespace model {

/// <summary>
///
/// </summary>
class  ComputerSet
{
public:
    ComputerSet() = default;
    explicit ComputerSet(boost::property_tree::ptree const& pt);
    virtual ~ComputerSet() = default;

    std::string toJsonString(bool prettyJson = false);
    void fromJsonString(std::string const& jsonString);
    boost::property_tree::ptree toPropertyTree();
    void fromPropertyTree(boost::property_tree::ptree const& pt);

    /////////////////////////////////////////////
    /// ComputerSet members

    /// <summary>
    ///
    /// </summary>
    std::string get_Class() const;
    void set_Class(std::string value);

    /// <summary>
    ///
    /// </summary>
    int32_t getBusyExecutors() const;
    void setBusyExecutors(int32_t value);

    /// <summary>
    ///
    /// </summary>
    std::vector<std::shared_ptr<HudsonMasterComputer>> getComputer() const;
    void setComputer(std::vector<std::shared_ptr<HudsonMasterComputer>> value);

    /// <summary>
    ///
    /// </summary>
    std::string getDisplayName() const;
    void setDisplayName(std::string value);

    /// <summary>
    ///
    /// </summary>
    int32_t getTotalExecutors() const;
    void setTotalExecutors(int32_t value);

protected:
    //////////////////////////////////////
    // Override these for customization //
    //////////////////////////////////////

    virtual std::string toJsonString_internal(bool prettyJson = false);
    virtual void fromJsonString_internal(std::string const& jsonString);
    virtual boost::property_tree::ptree toPropertyTree_internal();
    virtual void fromPropertyTree_internal(boost::property_tree::ptree const& pt);

protected:
    std::string m__class = "";
    int32_t m_BusyExecutors = 0;
    std::vector<std::shared_ptr<HudsonMasterComputer>> m_Computer;
    std::string m_DisplayName = "";
    int32_t m_TotalExecutors = 0;
};

std::vector<ComputerSet> createComputerSetVectorFromJsonString(const std::string& json);

}
}
}
}

#endif /* ComputerSet_H_ */


text:
<?php
namespace TYPO3\Flow\Utility\Exception;

/**
 * An Invalid Position Exception
 *
 * This exception is thrown by the ArraySorter if the given subject contains invalid "position" metadata
 *
 */
class InvalidPositionException extends \Exception
{
}


text:
package org.immutables.fixture;

import nonimmutables.NoNilType;
import org.immutables.value.Value.Immutable;

@Immutable
public interface WithThisCheckForNoNilString {
  @NoNilType
  String a(); // with method should not generate `== this.a`
  // check because of the type annotation. Should be equals
  // ErrorProne

  String b();
}


text:
.class Lo/ˠ$If;
.super Lo/ˠ$ˋ;
.source ""

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lo/ˠ;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "If"
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .line 84
    invoke-direct {p0}, Lo/ˠ$ˋ;-><init>()V

    return-void
.end method

# virtual methods
.method public ˊ(Lo/ˠ;)Ljava/lang/Object;
    .locals 1

    .line 88
    new-instance v0, Lo/ϲ;

    invoke-direct {v0, p0, p1}, Lo/ϲ;-><init>(Lo/ˠ$If;Lo/ˠ;)V

    invoke-static {v0}, Lo/с;->ˊ(Lo/с$if;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method


text:
<?php

// File generated from our OpenAPI spec

namespace Stripe\Terminal;

/**
 * A Location represents a grouping of readers.
 *
 * Related guide: Fleet Management.
 *
 * @property string $id Unique identifier for the object.
 * @property string $object String representing the object's type. Objects of the same type share the same value.
 * @property \Stripe\StripeObject $address
 * @property string $display_name The display name of the location.
 * @property bool $livemode Has the value true if the object exists in live mode or the value false if the object exists in test mode.
 * @property \Stripe\StripeObject $metadata Set of key-value pairs that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
 */
class Location extends \Stripe\ApiResource
{
    const OBJECT_NAME = 'terminal.location';

    use \Stripe\ApiOperations\All;
    use \Stripe\ApiOperations\Create;
    use \Stripe\ApiOperations\Delete;
    use \Stripe\ApiOperations\Retrieve;
    use \Stripe\ApiOperations\Update;
}


text:
import * as metrics from '@opentelemetry/api';
import { ExportResult } from '@opentelemetry/core';
import { ConsoleMetricExporter } from '../../src/export/ConsoleMetricExporter';
import { PeriodicExportingMetricReader } from '../../src/export/PeriodicExportingMetricReader';
import { ResourceMetrics } from '../../src/export/MetricData';
import { MeterProvider } from '../../src/MeterProvider';
import { defaultResource } from '../util';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { assertAggregationTemporalitySelector } from './utils';
import {
  DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR
} from '../../src/export/AggregationSelector';
import {
  AggregationTemporality,
  InstrumentType
} from '../../src';

async function waitForNumberOfExports(exporter: sinon.SinonSpy<[metrics: ResourceMetrics, resultCallback: (result: ExportResult) => void], void>, numberOfExports: number): Promise<void> {
  if (numberOfExports <= 0) {
    throw new Error('numberOfExports must be greater than or equal to 0');
  }

  let totalExports = 0;
  while (totalExports < numberOfExports) {
    await new Promise(resolve => setTimeout(resolve, 20));
    totalExports = exporter.callCount;
  }
}

/* eslint-disable no-console */
describe('ConsoleMetricExporter', () => {
  describe('export', () => {
    let previousConsoleDir: any;
    let exporter: ConsoleMetricExporter;
    let meterProvider: MeterProvider;
    let meterReader: PeriodicExportingMetricReader;
    let meter: metrics.Meter;

    beforeEach(() => {
      previousConsoleDir = console.dir;
      console.dir = () => {};

      exporter = new ConsoleMetricExporter();
      meterProvider = new MeterProvider({ resource: defaultResource });
      meter = meterProvider.getMeter('ConsoleMetricExporter', '1.0.0');
      meterReader = new PeriodicExportingMetricReader({
        exporter: exporter,
        exportIntervalMillis: 100,
        exportTimeoutMillis: 100
      });
      meterProvider.addMetricReader(meterReader);
    });

    afterEach(async () => {
      console.dir = previousConsoleDir;

      await meterReader.shutdown();
    });

    it('should export information about metric', async () => {
      const counter = meter.createCounter('counter_total', {
        description: 'a test description',
      });
      const counterAttribute = { key1: 'attributeValue1' };
      counter.add(10, counterAttribute);
      counter.add(10, counterAttribute);

      const histogram = meter.createHistogram('histogram', { description: 'a histogram' });
      histogram.record(10);
      histogram.record(100);
      histogram.record(1000);

      const spyConsole = sinon.spy(console, 'dir');
      const spyExport = sinon.spy(exporter, 'export');

      await waitForNumberOfExports(spyExport, 1);
      const resourceMetrics = spyExport.args[0];
      const firstResourceMetric = resourceMetrics[0];
      const consoleArgs = spyConsole.args[0];
      const consoleMetric = consoleArgs[0];
      const keys = Object.keys(consoleMetric).sort().join(',');

      const expectedKeys = [
        'dataPointType',
        'dataPoints',
        'descriptor',
      ].join(',');

      assert.ok(firstResourceMetric.resource.attributes.resourceKey === 'my-resource', 'resourceKey');
      assert.ok(keys === expectedKeys, 'expectedKeys');
      assert.ok(consoleMetric.descriptor.name === 'counter_total', 'name');
      assert.ok(consoleMetric.descriptor.description === 'a test description', 'description');
      assert.ok(consoleMetric.descriptor.type === 'COUNTER', 'type');
      assert.ok(consoleMetric.descriptor.unit === '', 'unit');
      assert.ok(consoleMetric.descriptor.valueType === 1, 'valueType');
      assert.ok(consoleMetric.dataPoints[0].attributes.key1 === 'attributeValue1', 'ensure metric attributes exists');

      assert.ok(spyExport.calledOnce);
    });
  });

  describe('constructor', () => {
    it('with no arguments should select cumulative temporality', () => {
      const exporter = new ConsoleMetricExporter();
      assertAggregationTemporalitySelector(exporter, DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR);
    });

    it('with empty options should select cumulative temporality', () => {
      const exporter = new ConsoleMetricExporter({});
      assertAggregationTemporalitySelector(exporter, DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR);
    });

    it('with cumulative preference should select cumulative temporality', () => {
      const exporter = new ConsoleMetricExporter({ temporalitySelector: _ => AggregationTemporality.CUMULATIVE });
      assertAggregationTemporalitySelector(exporter, _ => AggregationTemporality.CUMULATIVE);
    });

    it('with mixed preference should select matching temporality', () => {
      // use delta-ish example as a representation of a commonly used "mixed" preference.
      const selector = (instrumentType: InstrumentType) => {
        switch (instrumentType) {
          case InstrumentType.COUNTER:
          case InstrumentType.OBSERVABLE_COUNTER:
          case InstrumentType.HISTOGRAM:
          case InstrumentType.OBSERVABLE_GAUGE:
            return AggregationTemporality.DELTA;
          case InstrumentType.UP_DOWN_COUNTER:
          case InstrumentType.OBSERVABLE_UP_DOWN_COUNTER:
            return AggregationTemporality.CUMULATIVE;
        }
      };
      const exporter = new ConsoleMetricExporter({ temporalitySelector: selector });
      assertAggregationTemporalitySelector(exporter, selector);
    });
  });
});


text:
(function($){
  $(function(){
    var savingsInvestments = $('.retirement-needs-type-savings-investements');

    $(savingsInvestments).on('change', 'input', function() {
        var wrapper = $(this).closest('.ficheck-section-type');

        var currentValueEmployeeRetirementSavings = (wrapper.find('[name=employee_retirement_savings]').val() || 0) / 1;
        var currentValuePersonalRetirementSavings = (wrapper.find('[name=personal_retirement_savings]').val() || 0) / 1;
        var currentValueInvestments = (wrapper.find('[name=investements_value]').val() || 0) / 1;
        var currentValueSavingsAndInvestmentsElement = wrapper.find('[name=retirement_savings_and_investments]');

        var currentValueSavingsAndInvestments = Math.round((currentValueEmployeeRetirementSavings + currentValuePersonalRetirementSavings + currentValueInvestments) * 100) / 100;
        currentValueSavingsAndInvestmentsElement.val(currentValueSavingsAndInvestments);

        wrapper.next('.ficheck-section-type').find('[name="retirement_years_factor"]').trigger('change');
    });
  });
}(jQuery));


text:
<html>
  <head>
<style>
  * {
    -webkit-locale: 'xx-_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    -webkit-text-security: disc;
  }
</style>
</head>
<body>
xx
</body>
</html>


text:
require 'board'
require 'busted'
require 'human_player'

describe('HumanPlayer', function()

  it('returns false when get move is called', function()
    human_player = HumanPlayer:new("X")
    board = Board:new()
    assert.False(human_player:get_move(board))
  end)
end)


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

/**
 * @fileoverview Google API taming tests.
 *
 * This file tests the taming framework, not the taming of specific Google APIs.
 * For those tests, see tests/com/google/caja/apitaming.
 *
 * @author ihab.awad@gmail.com
 * @requires caja, jsunitRun, readyToTest, basicCajaConfig
 */

////////////////////////////////////////////////////////////////////////
// A dummy "Google API" for testing

(function() {
  "use strict";

  // Miscellaneous functions
  function getValue(a) { return 'foo' + a; }
  function getValueProhibited(a) { return 'fooProhibited' + a; }
  function advisedBA(a) { return 'v' + a + 'v'; }
  function advisedAround(a) { return 'x' + a + 'x'; }

  function Sup(x) { this.x = x; }
  Sup.someStatic = function(x) { return x + 19; };
  Sup.prototype.getX = function() { return this.x; };
  Sup.prototype.setX = function(x) { this.x = x; };

  function Sub(x, y) { Sup.apply(this, [x]); this.y = y; }
  Sub.prototype = new Sup(0);
  Sub.prototype.getY = function() { return this.y; };
  Sub.prototype.setY = function(y) { this.y = y; };

  window.google = {
    foo: {
      getValue: getValue,
      getValueProhibited: getValueProhibited,
      advisedBA: advisedBA,
      advisedAround: advisedAround,
      Sup: Sup,
      Sub: Sub
    },
    bar: {
      customGoogleLoadCalled: false,
      getValue: function(a) { return 'bar' + a; },
      isCustomGoogleLoadCalled: function() {
        return window.google.bar.customGoogleLoadCalled;
      }
    },
    load: function(name, opt_version, opt_info) {
      window.setTimeout(opt_info.callback, 0);
    }
  };
})();

////////////////////////////////////////////////////////////////////////
// Insert taming framework scripts

(function() {
  "use strict";
  function loadScript(url, cb) {
    var s = document.createElement('script');
    s.setAttribute('src', url);
    s.onload = cb;  // TODO(ihab.awad): Will not work on IE
    document.head.appendChild(s);
  }

  loadScript('../apitaming/cajaTamingGoogleLoader.js', function() {
    loadScript('../apitaming/google.load.loaderFactory.js', function() {
      runtests();
    });
  });
})();

////////////////////////////////////////////////////////////////////////
// Tests

function runtests() {
  "use strict";

  caja.initialize(basicCajaConfig);

  var uriPolicy = {
    rewrite: function (uri, uriEffect, loaderType, hints) { return uri; }
  };

  caja.tamingGoogleLoader.addPolicyFactoryUrl(
      'google.foo',
      './google.foo.policyFactory.js');
  caja.tamingGoogleLoader.addPolicyFactoryUrl(
      'google.bar',
      './google.bar.policyFactory.js');

  var goArray = [];

  ///////////////////////////////////////////////////////////////////////
  // Test guest "0". Whitelisted for both APIs "foo" and "bar". Should
  // demonstrate that it has access to both.

  caja.load(createDiv(), uriPolicy, function (frame) {

    var t = caja.tamingGoogleLoader.applyToFrame(frame, {
      google: {
        initialObj: frame.markReadOnlyRecord({
          initialFcn: frame.markFunction(function(x) {
            return x + 19;
          })
        })
      }
    });

    t.whitelistApi('google.foo');
    t.whitelistApi('google.bar');

    frame.code('test-apitaming-guest-0.html')
         .api(createExtraImportsForTesting(caja, frame))
         .run(function (_) { goArray[0] = t; });
  });

  ///////////////////////////////////////////////////////////////////////
  // Test guest "1". Whitelisted for only API "foo". Should demonstrate
  // that it only has access to what it's allowed to have.

  caja.load(createDiv(), uriPolicy, function (frame) {

    var t = caja.tamingGoogleLoader.applyToFrame(frame);
    t.whitelistApi('google.foo');

    frame.code('test-apitaming-guest-1.html')
         .api(createExtraImportsForTesting(caja, frame))
         .run(function (_) { goArray[1] = t; });
  });

  ///////////////////////////////////////////////////////////////////////
  // Startup code, waits till both guests loaded before proceeding. This
  // ensures that the API "bar" is already loaded into guest "0"; otherwise
  // guest "1" could be failing to get "bar" because it hasn't been loaded
  // yet, and not due to the success of the selective whitelisting. :)

  function check() {
    window.setTimeout(function() {
      if (goArray[0] && goArray[1]) {
        goArray[0].signalOnload();
        goArray[1].signalOnload();
        readyToTest();
        jsunitRun();
      } else {
        check();
      }
    }, 250);
  }

  check();
}


text:
'use strict';

var express = require('express');
var router = express.Router();

router.use('/', function(req, res, next) {
  if(!req.user) {
    res.redirect('/');
  }
  next();
});

/* GET users listing. */
router.get('/', function(req, res) {
  res.render('users', {user: req.user});
});

module.exports = router;