text:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using SharpSteer2;
using SharpSteer2.Helpers;
using SharpSteer2.Obstacles;
using Vector3 = System.Numerics.Vector3;

namespace Demo.PlugIns.Ctf
{ // spherical obstacle group

	// Capture the Flag   (a portion of the traditional game)
	//
	// The "Capture the Flag" sample steering problem, proposed by Marcin
	// Chady of the Working Group on Steering of the IGDA's AI Interface
	// Standards Committee (http://www.igda.org/Committees/ai.htm) in this
	// message (http://sourceforge.net/forum/message.php?msg_id=1642243):
	//
	//     "An agent is trying to reach a physical location while trying
	//     to stay clear of a group of enemies who are actively seeking
	//     him. The environment is littered with obstacles, so collision
	//     avoidance is also necessary."
	//
	// Note that the enemies do not make use of their knowledge of the
	// seeker's goal by "guarding" it.
	//
	// XXX hmm, rename them "attacker" and "defender"?
	//
	// 08-12-02 cwr: created

	public class CtfPlugIn : PlugIn
	{
	    private readonly bool _arrive;
	    public readonly float BaseRadius;
	    private readonly int _obstacles;

	    public CtfSeeker CtfSeeker = null;
        public readonly CtfEnemy[] CtfEnemies;

		public CtfPlugIn(IAnnotationService annotations, int enemyCount = 6, bool arrive = false, float baseRadius = 1.5f, int obstacles = 50)
            :base(annotations)
		{
		    _arrive = arrive;
		    BaseRadius = baseRadius;
		    _obstacles = obstacles;
		    CtfEnemies = new CtfEnemy[enemyCount];

			_all = new List<CtfBase>();
		}

		public override String Name { get { return "Capture the Flag"; } }

		public override float SelectionOrderSortKey { get { return 0.01f; } }

		public override void Open()
		{
			// create the seeker ("hero"/"attacker")
            CtfSeeker = new CtfSeeker(this, Annotations, _arrive);
			_all.Add(CtfSeeker);

			// create the specified number of enemies,
			// storing pointers to them in an array.
			for (int i = 0; i < CtfEnemies.Length; i++)
			{
                CtfEnemies[i] = new CtfEnemy(this, Annotations);
				_all.Add(CtfEnemies[i]);
			}

			// initialize camera
			Demo.Init2dCamera(CtfSeeker);
			Demo.Camera.Mode = Camera.CameraMode.FixedDistanceOffset;
			Demo.Camera.FixedTarget = Vector3.Zero;
            Demo.Camera.FixedTarget.X = 15;
			Demo.Camera.FixedPosition.X = 80;
            Demo.Camera.FixedPosition.Y = 60;
            Demo.Camera.FixedPosition.Z = 0;

            CtfBase.InitializeObstacles(BaseRadius, _obstacles);
		}

		public override void Update(float currentTime, float elapsedTime)
		{
		    // update the seeker
			CtfSeeker.Update(currentTime, elapsedTime);

			// update each enemy
		    foreach (CtfEnemy enemy in CtfEnemies)
		        enemy.Update(currentTime, elapsedTime);
		}

	    public override void Redraw(float currentTime, float elapsedTime)
		{
			// selected vehicle (user can mouse click to select another)
			IVehicle selected = Demo.SelectedVehicle;

			// vehicle nearest mouse (to be highlighted)
			IVehicle nearMouse = Demo.VehicleNearestToMouse ();

			// update camera
			Demo.UpdateCamera(elapsedTime, selected);

			// draw "ground plane" centered between base and selected vehicle
			Vector3 goalOffset = Globals.HomeBaseCenter - Demo.Camera.Position;
			Vector3 goalDirection = Vector3.Normalize(goalOffset);
			Vector3 cameraForward = Demo.Camera.xxxls().Forward;
            float goalDot = Vector3.Dot(cameraForward, goalDirection);
			float blend = Utilities.RemapIntervalClip(goalDot, 1, 0, 0.5f, 0);
            Vector3 gridCenter = Vector3.Lerp(selected.Position, Globals.HomeBaseCenter, blend);
			Demo.GridUtility(gridCenter);

			// draw the seeker, obstacles and home base
			CtfSeeker.Draw();
			DrawObstacles();
			DrawHomeBase();

			// draw each enemy
			foreach (CtfEnemy enemy in CtfEnemies)
			    enemy.Draw();

	        // highlight vehicle nearest mouse
			Demo.HighlightVehicleUtility(nearMouse);
		}

		public override void Close()
		{
			// delete seeker
			CtfSeeker = null;

			// delete each enemy
			for (int i = 0; i < CtfEnemies.Length; i++)
			{
				CtfEnemies[i] = null;
			}

			// clear the group of all vehicles
			_all.Clear();
		}

		public override void Reset()
		{
			// count resets
			Globals.ResetCount++;

			// reset the seeker ("hero"/"attacker") and enemies
			CtfSeeker.Reset();
			foreach (CtfEnemy enemy in CtfEnemies)
			    enemy.Reset();

		    // reset camera position
			Demo.Position2dCamera(CtfSeeker);

			// make camera jump immediately to new position
			Demo.Camera.DoNotSmoothNextMove();
		}

		public override void HandleFunctionKeys(Keys key)
		{
			switch (key)
			{
			case Keys.F1: CtfBase.AddOneObstacle(BaseRadius); break;
			case Keys.F2: CtfBase.RemoveOneObstacle(); break;
			}
		}

		public override void PrintMiniHelpForFunctionKeys()
		{
#if TODO
			std.ostringstream message;
			message << "Function keys handled by ";
			message << '"' << name() << '"' << ':' << std.ends;
			Demo.printMessage (message);
			Demo.printMessage ("  F1     add one obstacle.");
			Demo.printMessage ("  F2     remove one obstacle.");
			Demo.printMessage ("");
#endif
		}

        public override IEnumerable<IVehicle> Vehicles
		{
			get { return _all.ConvertAll<IVehicle>(v => (IVehicle) v); }
		}

	    private void DrawHomeBase()
		{
			Vector3 up = new Vector3(0, 0.01f, 0);
			Color atColor = new Color((byte)(255.0f * 0.3f), (byte)(255.0f * 0.3f), (byte)(255.0f * 0.5f));
			Color noColor = Color.Gray;
			bool reached = CtfSeeker.State == CtfBase.SeekerState.AtGoal;
			Color baseColor = (reached ? atColor : noColor);
            Drawing.DrawXZDisk(BaseRadius, Globals.HomeBaseCenter, baseColor, 40);
            Drawing.DrawXZDisk(BaseRadius / 15, Globals.HomeBaseCenter + up, Color.Black, 20);
		}

	    private static void DrawObstacles()
		{
			Color color = new Color((byte)(255.0f * 0.8f), (byte)(255.0f * 0.6f), (byte)(255.0f * 0.4f));
			List<SphericalObstacle> allSO = CtfBase.AllObstacles;
			foreach (SphericalObstacle soObstacle in allSO)
			    Drawing.DrawXZCircle(soObstacle.Radius, soObstacle.Center, color, 40);
		}

		// a group (STL vector) of all vehicles in the PlugIn
	    readonly List<CtfBase> _all;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary">#01b37c</color>
    <color name="primary_dark">#009b6b</color>
</resources>

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Account',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('username', models.CharField(max_length=20, unique=True)),
                ('password', models.CharField(max_length=40)),
            ],
        ),
        migrations.CreateModel(
            name='Personal',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('username', models.CharField(max_length=20, unique=True)),
                ('nickname', models.CharField(max_length=40)),
                ('gender', models.CharField(max_length=2)),
                ('telphone', models.CharField(max_length=20)),
                ('email', models.CharField(max_length=40)),
                ('status', models.CharField(max_length=200)),
            ],
        ),
    ]


text:
<Record>
<Term>Lamivudine-nevirapine-stavudine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType>
<Synonym>Lamivudine;nevirapine;stavudine</Synonym>
<Synonym>Lamivudine- stavudine- nevirapine</Synonym>
<Synonym>Stavudine- lamivudine wnevirapine</Synonym>
<Synonym>Lamivudine; stavudine; nevirapine</Synonym>
<Synonym>Stavudine- lamivudine- nevirapine</Synonym>
<Synonym>Stavudine; lamivudine; nevirapine</Synonym>
<Synonym>Stavudine; lamivudine wnevirapine</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
package org.robolectric;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import org.junit.Assert;
import org.junit.runner.Runner;
import org.junit.runners.Parameterized;
import org.junit.runners.Suite;
import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.TestClass;
import org.robolectric.internal.SandboxTestRunner;
import org.robolectric.util.ReflectionHelpers;

/**
 * A Parameterized test runner for Robolectric. Copied from the {@link Parameterized} class, then
 * modified the custom test runner to extend the {@link RobolectricTestRunner}. The {@link
 * org.robolectric.RobolectricTestRunner#getHelperTestRunner(Class)} is overridden in order to
 * create instances of the test class with the appropriate parameters. Merged in the ability to name
 * your tests through the {@link Parameters#name()} property. Merged in support for {@link
 * Parameter} annotation alternative to providing a constructor.
 *
 *
This class takes care of the fact that the test runner and the test class are actually loaded
 * from different class loaders and therefore parameter objects created by one cannot be assigned to
 * instances of the other.
 */
public final class ParameterizedRobolectricTestRunner extends Suite {

  /**
   * Annotation for a method which provides parameters to be injected into the test class
   * constructor by Parameterized
   */
  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.METHOD)
  public @interface Parameters {

    /**
     * Optional pattern to derive the test's name from the parameters. Use numbers in braces to
     * refer to the parameters or the additional data as follows:
     *
     *

     * {index} - the current parameter index
     * {0} - the first parameter value
     * {1} - the second parameter value
     * etc...
     *

     *
     *
Default value is "{index}" for compatibility with previous JUnit versions.
     *
     * @return {@link MessageFormat} pattern string, except the index placeholder.
     * @see MessageFormat
     */
    String name() default "{index}";
  }

  /**
   * Annotation for fields of the test class which will be initialized by the method annotated by
   * Parameters

   * By using directly this annotation, the test class constructor isn't needed.

   * Index range must start at 0. Default value is 0.
   */
  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.FIELD)
  public @interface Parameter {
    /**
     * Method that returns the index of the parameter in the array returned by the method annotated
     * by Parameters.

     * Index range must start at 0. Default value is 0.
     *
     * @return the index of the parameter.
     */
    int value() default 0;
  }

  private static class TestClassRunnerForParameters extends RobolectricTestRunner {

    private final int parametersIndex;
    private final String name;

    TestClassRunnerForParameters(Class<?> type, int parametersIndex, String name)
        throws InitializationError {
      super(type);
      this.parametersIndex = parametersIndex;
      this.name = name;
    }

    private Object createTestInstance(Class bootstrappedClass) throws Exception {
      Constructor<?>[] constructors = bootstrappedClass.getConstructors();
      Assert.assertEquals(1, constructors.length);
      if (!fieldsAreAnnotated()) {
        return constructors[0].newInstance(computeParams(bootstrappedClass.getClassLoader()));
      } else {
        Object instance = constructors[0].newInstance();
        injectParametersIntoFields(instance, bootstrappedClass.getClassLoader());
        return instance;
      }
    }

    private Object[] computeParams(ClassLoader classLoader) throws Exception {
      // Robolectric uses a different class loader when running the tests, so the parameters objects
      // created by the test runner are not compatible with the parameters required by the test.
      // Instead, we compute the parameters within the test's class loader.
      try {
        List<Object[]> parametersList = getParametersList(getTestClass(), classLoader);
        if (parametersIndex >= parametersList.size()) {
          throw new Exception(
              "Re-computing the parameter list returned a different number of "
                  + "parameters values. Is the data() method of your test non-deterministic?");
        }
        return parametersList.get(parametersIndex);
      } catch (ClassCastException e) {
        throw new Exception(
            String.format(
                "%s.%s() must return a Collection of arrays.", getTestClass().getName(), name));
      } catch (Exception exception) {
        throw exception;
      } catch (Throwable throwable) {
        throw new Exception(throwable);
      }
    }

    @SuppressWarnings("unchecked")
    private void injectParametersIntoFields(Object testClassInstance, ClassLoader classLoader)
        throws Exception {
      // Robolectric uses a different class loader when running the tests, so referencing Parameter
      // directly causes type mismatches. Instead, we find its class within the test's class loader.
      Class<?> parameterClass = getClassInClassLoader(Parameter.class, classLoader);
      Object[] parameters = computeParams(classLoader);
      HashSet<Integer> parameterFieldsFound = new HashSet<>();
      for (Field field : testClassInstance.getClass().getFields()) {
        Annotation parameter = field.getAnnotation((Class<Annotation>) parameterClass);
        if (parameter != null) {
          int index = ReflectionHelpers.callInstanceMethod(parameter, "value");
          parameterFieldsFound.add(index);
          try {
            field.set(testClassInstance, parameters[index]);
          } catch (IllegalArgumentException iare) {
            throw new Exception(
                getTestClass().getName()
                    + ": Trying to set "
                    + field.getName()
                    + " with the value "
                    + parameters[index]
                    + " that is not the right type ("
                    + parameters[index].getClass().getSimpleName()
                    + " instead of "
                    + field.getType().getSimpleName()
                    + ").",
                iare);
          }
        }
      }
      if (parameterFieldsFound.size() != parameters.length) {
        throw new IllegalStateException(
            String.format(
                Locale.US,
                "Provided %d parameters, but only found fields for parameters: %s",
                parameters.length,
                parameterFieldsFound.toString()));
      }
    }

    @Override
    protected String getName() {
      return name;
    }

    @Override
    protected String testName(final FrameworkMethod method) {
      return method.getName() + getName();
    }

    @Override
    protected void validateConstructor(List<Throwable> errors) {
      validateOnlyOneConstructor(errors);
      if (fieldsAreAnnotated()) {
        validateZeroArgConstructor(errors);
      }
    }

    @Override
    public String toString() {
      return "TestClassRunnerForParameters " + name;
    }

    @Override
    protected void validateFields(List<Throwable> errors) {
      super.validateFields(errors);
      // Ensure that indexes for parameters are correctly defined
      if (fieldsAreAnnotated()) {
        List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
        int[] usedIndices = new int[annotatedFieldsByParameter.size()];
        for (FrameworkField each : annotatedFieldsByParameter) {
          int index = each.getField().getAnnotation(Parameter.class).value();
          if (index < 0 || index > annotatedFieldsByParameter.size() - 1) {
            errors.add(
                new Exception(
                    "Invalid @Parameter value: "
                        + index
                        + ". @Parameter fields counted: "
                        + annotatedFieldsByParameter.size()
                        + ". Please use an index between 0 and "
                        + (annotatedFieldsByParameter.size() - 1)
                        + "."));
          } else {
            usedIndices[index]++;
          }
        }
        for (int index = 0; index < usedIndices.length; index++) {
          int numberOfUse = usedIndices[index];
          if (numberOfUse == 0) {
            errors.add(new Exception("@Parameter(" + index + ") is never used."));
          } else if (numberOfUse > 1) {
            errors.add(
                new Exception(
                    "@Parameter(" + index + ") is used more than once (" + numberOfUse + ")."));
          }
        }
      }
    }

    @Override
    protected SandboxTestRunner.HelperTestRunner getHelperTestRunner(Class bootstrappedTestClass) {
      try {
        return new HelperTestRunner(bootstrappedTestClass) {
          @Override
          protected void validateConstructor(List<Throwable> errors) {
            TestClassRunnerForParameters.this.validateOnlyOneConstructor(errors);
          }

          @Override
          protected Object createTest() throws Exception {
            return TestClassRunnerForParameters.this.createTestInstance(
                getTestClass().getJavaClass());
          }

          @Override
          public String toString() {
            return "HelperTestRunner for " + TestClassRunnerForParameters.this.toString();
          }
        };
      } catch (InitializationError initializationError) {
        throw new RuntimeException(initializationError);
      }
    }

    private List<FrameworkField> getAnnotatedFieldsByParameter() {
      return getTestClass().getAnnotatedFields(Parameter.class);
    }

    private boolean fieldsAreAnnotated() {
      return !getAnnotatedFieldsByParameter().isEmpty();
    }
  }

  private final ArrayList<Runner> runners = new ArrayList<>();

  /*
   * Only called reflectively. Do not use programmatically.
   */
  public ParameterizedRobolectricTestRunner(Class<?> klass) throws Throwable {
    super(klass, Collections.<Runner>emptyList());
    TestClass testClass = getTestClass();
    ClassLoader classLoader = getClass().getClassLoader();
    Parameters parameters =
        getParametersMethod(testClass, classLoader).getAnnotation(Parameters.class);
    List<Object[]> parametersList = getParametersList(testClass, classLoader);
    for (int i = 0; i < parametersList.size(); i++) {
      Object[] parameterArray = parametersList.get(i);
      runners.add(
          new TestClassRunnerForParameters(
              testClass.getJavaClass(), i, nameFor(parameters.name(), i, parameterArray)));
    }
  }

  @Override
  protected List<Runner> getChildren() {
    return runners;
  }

  @SuppressWarnings("unchecked")
  private static List<Object[]> getParametersList(TestClass testClass, ClassLoader classLoader)
      throws Throwable {
    return (List<Object[]>) getParametersMethod(testClass, classLoader).invokeExplosively(null);
  }

  private static FrameworkMethod getParametersMethod(TestClass testClass, ClassLoader classLoader)
      throws Exception {
    List<FrameworkMethod> methods = testClass.getAnnotatedMethods(Parameters.class);
    for (FrameworkMethod each : methods) {
      int modifiers = each.getMethod().getModifiers();
      if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) {
        return getFrameworkMethodInClassLoader(each, classLoader);
      }
    }

    throw new Exception("No public static parameters method on class " + testClass.getName());
  }

  private static String nameFor(String namePattern, int index, Object[] parameters) {
    String finalPattern = namePattern.replaceAll("\\{index\\}", Integer.toString(index));
    String name = MessageFormat.format(finalPattern, parameters);
    return "[" + name + "]";
  }

  /**
   * Returns the {@link FrameworkMethod} object for the given method in the provided class loader.
   */
  private static FrameworkMethod getFrameworkMethodInClassLoader(
      FrameworkMethod method, ClassLoader classLoader)
      throws ClassNotFoundException, NoSuchMethodException {
    Method methodInClassLoader = getMethodInClassLoader(method.getMethod(), classLoader);
    if (methodInClassLoader.equals(method.getMethod())) {
      // The method was already loaded in the right class loader, return it as is.
      return method;
    }
    return new FrameworkMethod(methodInClassLoader);
  }

  /** Returns the {@link Method} object for the given method in the provided class loader. */
  private static Method getMethodInClassLoader(Method method, ClassLoader classLoader)
      throws ClassNotFoundException, NoSuchMethodException {
    Class<?> declaringClass = method.getDeclaringClass();

    if (declaringClass.getClassLoader() == classLoader) {
      // The method was already loaded in the right class loader, return it as is.
      return method;
    }

    // Find the class in the class loader corresponding to the declaring class of the method.
    Class<?> declaringClassInClassLoader = getClassInClassLoader(declaringClass, classLoader);

    // Find the method with the same signature in the class loader.
    return declaringClassInClassLoader.getMethod(method.getName(), method.getParameterTypes());
  }

  /** Returns the {@link Class} object for the given class in the provided class loader. */
  private static Class<?> getClassInClassLoader(Class<?> klass, ClassLoader classLoader)
      throws ClassNotFoundException {
    if (klass.getClassLoader() == classLoader) {
      // The method was already loaded in the right class loader, return it as is.
      return klass;
    }

    // Find the class in the class loader corresponding to the declaring class of the method.
    return classLoader.loadClass(klass.getName());
  }
}


text:
'use strict';

angular.module('webClientApp')
  .directive('articleRenderer', [function () {

    var getFirstLayoutType = function (article) {
      if (!article.hasCover()) {
        return false;
      }
      var layout = article.getFirstComponent();
      while (!layout.getLength() && layout.getNextComponent()) {
        layout = layout.getNextComponent();
      }
      return layout.type;
    };

    var isStaged = function (article) {
      return carbon.Layout.Types.Staged === getFirstLayoutType(article);
    };

    var isBleed = function (article) {
      return carbon.Layout.Types.Bleed === getFirstLayoutType(article);
    };

    return {
      require: '?ngModel',
      restrict: 'A',
      link: function (scope, element, attrs, ngModel) {
        ngModel.$render = function() {
          if (ngModel.$viewValue) {
            if (!carbon.Loader.load('embedProviders')) {
              carbon.Loader.register('embedProviders', {
                embedly: new carbon.EmbedlyProvider({
                  apiKey: '46c6ad376b1343359d774c5d8a940db7'
                }),
                carbon: new carbon.CarbonEmbedProvider({})
              });
            }

            var json = JSON.parse(ngModel.$viewValue);
            var article = carbon.Article.fromJSON(json);

            if (article.hasCover()) {
              document.body.classList.add('article-with-cover');
              if (isStaged(article)) {
                document.body.classList.add('staged-cover');
              } else if (isBleed(article)) {
                document.body.classList.add('bleed-cover');
              }
            }

            article.render(element[0]);
          }
        };

        scope.$on('$destroy', function() {
          document.body.classList.remove('article-with-cover');
          document.body.classList.remove('staged-cover');
          document.body.classList.remove('bleed-cover');
        });
      }
    };
  }]);


text:
import './setup';
import { StageComponent, ComponentTester } from 'aurelia-testing';
import { PLATFORM } from 'aurelia-pal';
import { bootstrap } from 'aurelia-bootstrapper';
import { validateScrolledState, waitForNextFrame, waitForFrames, scrollRepeat } from './utilities';
import { VirtualRepeat } from '../src/virtual-repeat';
import { ITestAppInterface } from './interfaces';
import { eachCartesianJoin } from './lib';

PLATFORM.moduleName('src/virtual-repeat');
PLATFORM.moduleName('test/noop-value-converter');
PLATFORM.moduleName('src/infinite-scroll-next');

describe('vr-integration.infinite-scroll.spec.ts', () => {
  const resources = [
    'src/virtual-repeat',
    'src/infinite-scroll-next',
    'test/noop-value-converter',
  ];
  class IdentityValueConverter {
    static $resource = {
      type: 'valueConverter',
      name: 'identity',
    };
    toView(val: any[]) {
      return val;
    }
  }
  class CloneArrayValueConverter {
    static $resource = {
      type: 'valueConverter',
      name: 'cloneArray',
    };
    toView(val: any[]) {
      return Array.isArray(val) ? val.slice() : val;
    }
  }

  let component: ComponentTester<VirtualRepeat>;
  let view: string;
  let itemHeight = 100;

  beforeEach(() => {
    component = undefined;
  });

  afterEach(() => {
    try {
      if (component) {
        component.dispose();
      }
    } catch (ex) {
      console.log('Error disposing component');
      console.error(ex);
    }
  });

  const testGroups: ITestCaseGroup[] = [
    {
      desc: 'div > div',
      title: (repeatExpression, scrollNextAttr) =>
        `div > div[repeat ${repeatExpression}][${scrollNextAttr}]`,
      createView: (repeatExpression, scrollNextAttr) =>
        `

\${item}

`,
    },
    {
      desc: 'ul > li',
      title: (repeatExpression, scrollNextAttr) =>
        `ul > li[repeat ${repeatExpression}][${scrollNextAttr}]`,
      createView: (repeatExpression, scrollNextAttr) =>
        `

\${item}

`,
    },
    {
      desc: 'ol > li',
      title: (repeatExpression, scrollNextAttr) =>
        `ol > li[repeat ${repeatExpression}][${scrollNextAttr}]`,
      createView: (repeatExpression, scrollnextAttr) =>
        `

\${item}

`,
    },
    {
      desc: 'div > table > tr',
      title: (repeatExpression: string, scrollNextAttr: string): string => {
        return `div > table > tr[repeat ${repeatExpression}][${scrollNextAttr}]`;
      },
      createView: (repeatExpression: string, scrollNextAttr: string): string => {
        return `

\${item}

`;
      },
    },
    {
      desc: 'div > table > tbody',
      title: (repeatExpression: string, scrollNextAttr: string): string => {
        return `div > table > tbody[repeat${repeatExpression}][${scrollNextAttr}]`;
      },
      createView: (repeatExpression: string, scrollNextAttr: string): string => {
        return `

                \${item}

`;
      },
    },
  ];

  const repeatScrollNextCombos: IRepeatScrollNextCombo[] = [
    ['', 'infinite-scroll-next="getNextPage"'],
    ['', 'infinite-scroll-next.call="getNextPage($scrollContext)"'],
    [' & toView', 'infinite-scroll-next="getNextPage"'],
    [' & twoWay', 'infinite-scroll-next="getNextPage"'],
    [' & twoWay', 'infinite-scroll-next.call="getNextPage($scrollContext)"'],
    [' | cloneArray', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]],
    [' | cloneArray', 'infinite-scroll-next.call="getNextPage($scrollContext)"', [CloneArrayValueConverter]],
    [' | identity | cloneArray & toView', 'infinite-scroll-next="getNextPage"', [IdentityValueConverter, CloneArrayValueConverter]],
    [' | identity | cloneArray & toView', 'infinite-scroll-next.call="getNextPage($scrollContext)"', [IdentityValueConverter, CloneArrayValueConverter]],
    [' | cloneArray & toView', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]],

    // cloneArray and two way creates infinite loop
    // [' | cloneArray & twoWay', 'infinite-scroll-next="getNextPage"', [CloneArrayValueConverter]]
  ];

  eachCartesianJoin(
    [repeatScrollNextCombos, testGroups],
    ([repeatExpression, scrollNextAttr, extraResources], { title, createView }) => {
      runTestGroup(
        title(repeatExpression, scrollNextAttr),
        createView(repeatExpression, scrollNextAttr),
        extraResources
      );
    }
  );

  type IRepeatScrollNextCombo = [/*repeat extra expression*/string, /*infinite-scroll-next attr*/string, /*extraResources*/ any[]?];

  interface ITestCaseGroup {
    desc?: string;
    title: (repeatExpression: string, scrollNextAttr: string) => string;
    createView: (repeatExpression: string, scrollNextAttr: string) => string;
  }

  function runTestGroup(title: string, $view: string, extraResources: any[] = []): void {

    it([
      title,
      'Initial 3 - 4 - 5 - 6 items',
      ' -- wait',
      ' -- assert get more',
      '',
    ].join('\n\t'), async () => {
      let scrollNextArgs: [number, boolean, boolean];
      const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
        scrollNextArgs = normalizeScrollNextArgs(args);
        let itemLength = this.items.length;
        for (let i = 0; i < 100; ++i) {
          let itemNum = itemLength + i;
          this.items.push('item' + itemNum);
        }
      }).and.callThrough();
      let { component, virtualRepeat, viewModel } = await bootstrapComponent(
        {
          items: createItems(3),
          getNextPage: spy,
        },
        extraResources,
        $view
      );

      await waitForNextFrame();
      expect(virtualRepeat.minViewsRequired).toBe(6, 'repeat.elementsInView');
      expect(spy.calls.count()).toBe(1, '3 items getNextPage() calls');
      // await waitForNextFrame();
      // expect(spy.calls.count()).toBe(1, '3 items - next frame -- getNextPage() calls');
      let [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
      expect(firstIndex).toBe(0, 'scrollNextArgs[0] 1');
      expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 1');
      expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 1');

      expect(viewModel.items.length).toBe(103, 'items.length 1');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      component.dispose();
      spy.calls.reset();

      ({ component, virtualRepeat, viewModel } = await bootstrapComponent(
        {
          items: createItems(4),
          getNextPage: spy,
        },
        extraResources,
        $view
      ));
      await waitForNextFrame();
      expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
      expect(spy.calls.count()).toBe(1, '4 items getNextPage() calls');
      [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
      expect(firstIndex).toBe(0, 'scrollNextArgs[0] 2');
      expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 2');
      expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 2');

      expect(viewModel.items.length).toBe(104, 'items.length 2');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      component.dispose();
      spy.calls.reset();

      ({ component, virtualRepeat, viewModel } = await bootstrapComponent(
        {
          items: createItems(5),
          getNextPage: spy,
        },
        extraResources,
        $view
      ));
      await waitForNextFrame();
      expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
      expect(spy.calls.count()).toBe(1, '5 items getNextPage() calls');
      [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
      expect(firstIndex).toBe(0, 'scrollNextArgs[0] 3');
      expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 3');
      expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 3');

      expect(viewModel.items.length).toBe(105, 'items.length 3');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      component.dispose();
      spy.calls.reset();

      ({ component, virtualRepeat, viewModel } = await bootstrapComponent(
        {
          items: createItems(6),
          getNextPage: spy,
        },
        extraResources,
        $view
      ));
      await waitForNextFrame();
      expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
      expect(spy.calls.count()).toBe(0, '6 items = 0 getNextPage() calls');
      [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
      expect(firstIndex).toBe(0, 'scrollNextArgs[0] 4');
      expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 4');
      expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 4');

      expect(viewModel.items.length).toBe(6, 'items.length 4');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);
    });

    it([
      title,
      'Initial 100 items',
      ' -- scroll down + get 100 more',
      ' -- wait',
      ' -- scroll up + get 100 more',
      '',
    ].join('\n\t'), async () => {
      const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>) {
        let itemLength = this.items.length;
        for (let i = 0; i < 100; ++i) {
          let itemNum = itemLength + i;
          this.items.push('item' + itemNum);
        }
      }).and.callThrough();
      const { virtualRepeat, viewModel } = await bootstrapComponent(
        {
          items: createItems(100),
          getNextPage: spy,
        },
        extraResources,
        $view
      );
      expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
      expect(spy.calls.count()).toBe(0, 'no getNextPage() calls');

      expect(viewModel.items.length).toBe(100, 'items.length 1');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      scrollRepeat(virtualRepeat, 'end');
      expect(spy.calls.count()).toBe(0, '@scroll 1 start -> end');
      await waitForFrames(1);
      expect(spy.calls.count()).toBe(0, '@scroll 1 start -> end');
      await waitForFrames(2);
      expect(spy.calls.count()).toBe(1, '@scroll 1 start -> end');
      expect(viewModel.items.length).toBe(200, 'items.length 2');
      let firstViewIndex = virtualRepeat.firstViewIndex();
      let lastViewIndex = virtualRepeat.lastViewIndex();
      expect(firstViewIndex).toBeGreaterThanOrEqual(100 - (5 + 1) * 2, 'repeat._firstViewIndex() 1');
      expect(firstViewIndex).toBeLessThan(200 - (5 + 1) * 2, 'repeat._firstViewIndex < bottom');
      expect(lastViewIndex).toBeGreaterThanOrEqual(100, 'repeat._lastViewIndex() 1');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      scrollRepeat(virtualRepeat, 'start');
      expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
      await waitForFrames(1);
      expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
      await waitForFrames(2);
      expect(spy.calls.count()).toBe(2, '@scroll 2 end -> start');
      expect(viewModel.items.length).toBe(300, 'items.length 3');
      firstViewIndex = virtualRepeat.firstViewIndex();
      lastViewIndex = virtualRepeat.lastViewIndex();
      expect(firstViewIndex).toBe(0, 'repeat._firstViewIndex() 2');
      expect(lastViewIndex).toBe(11, 'repeat._lastViewIndex() 2');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);
    });

    it([
      title,
      'passes the current index and location state',
      ' -- start 100',
      ' -- jump to end',
      ' -- wait and assert',
      ' -- jump to start',
      ' -- wait and assert',
    ].join('\n\t'), async () => {
      let scrollNextArgs: [number, /*is near bottom*/boolean, /*is near top*/boolean];
      const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
        scrollNextArgs = normalizeScrollNextArgs(args);
        if (scrollNextArgs[2]) {
          let itemLength = this.items.length;
          for (let i = 0; i < 100; ++i) {
            let itemNum = itemLength + i;
            this.items.unshift('item' + itemNum);
          }
        }
      }).and.callThrough();
      const { virtualRepeat, viewModel } = await bootstrapComponent(
        {
          items: createItems(100),
          getNextPage: spy,
        },
        extraResources,
        $view
      );
      expect(scrollNextArgs).toBe(undefined, 'getNextPage() args[]');
      expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
      expect(virtualRepeat.viewCount()).toBe(12, 'repeat.viewCount()');
      expect(spy.calls.count()).toBe(0, 'no getNextPage() calls');

      expect(viewModel.items.length).toBe(100, 'items.length 1');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      scrollRepeat(virtualRepeat, 'end');
      expect(spy.calls.count()).toBe(0, '@scroll 1 start -> end');
      await waitForFrames(1);
      expect(spy.calls.count()).toBe(0, '@scroll 1 start -> end');
      await waitForFrames(2);
      expect(spy.calls.count()).toBe(1, '@scroll 1 start -> end');
      expect(viewModel.items.length).toBe(100, 'items.length 2');
      let virtualRepeatFirst = virtualRepeat.$first;
      let firstViewIndex = virtualRepeat.firstViewIndex();
      let lastViewIndex = virtualRepeat.lastViewIndex();
      expect(firstViewIndex).toBe(88, 'repeat._firstViewIndex() 1');
      expect(virtualRepeatFirst).toBe(88, 'repeat._first 1 = 88');
      // expect(virtualRepeatFirst).toBe(94, 'repeat._first 1 <= 94');
      expect(lastViewIndex).toBe(99, 'repeat._lastViewIndex() 1');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);
      expect(Array.isArray(scrollNextArgs)).toBe(true, 'scrollNextArgs is defined');
      let [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
      expect(firstIndex).toBe(88, 'scrollNextArgs[0] 1');
      expect(isAtBottom).toBe(true, 'scrollNextArgs[1] -- isAtBottom 1');
      expect(isAtTop).toBe(false, 'scrollNextArgs[2] -- isAtTop 1');

      scrollRepeat(virtualRepeat, 'start');
      expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
      await waitForFrames(1);
      expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
      await waitForFrames(2);
      expect(spy.calls.count()).toBe(2, '@scroll 2 end -> start');
      expect(viewModel.items.length).toBe(200, 'items.length 3');
      virtualRepeatFirst = virtualRepeat.$first;
      firstViewIndex = virtualRepeat.firstViewIndex();
      lastViewIndex = virtualRepeat.lastViewIndex();
      expect(firstViewIndex).toBe(0, 'repeat._firstViewIndex() 2');
      expect(lastViewIndex).toBe(11, 'repeat._lastViewIndex() 2');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);
      [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
      expect(firstIndex).toBe(virtualRepeatFirst, 'scrollNextArgs[0] 2');
      expect(isAtBottom).toBe(false, 'scrollNextArgs[1] -- isAtBottom 2');
      expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 2');
    });

    it([
      title,
      'passes the current index and location state',
      ' -- start 100',
      ' -- scroll down 20',
      ' -- wait and assert',
      ' -- scroll up',
      ' -- wait and assert',
    ].join('\n\t'), async () => {
      let scrollNextArgs: [number, /*is near bottom*/boolean, /*is near top*/boolean];
      const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
        scrollNextArgs = normalizeScrollNextArgs(args);
        if (scrollNextArgs[2]) {
          let itemLength = this.items.length;
          for (let i = 0; i < 100; ++i) {
            let itemNum = itemLength + i;
            this.items.unshift('item' + itemNum);
          }
        }
      }).and.callThrough();
      const { virtualRepeat, viewModel } = await bootstrapComponent(
        {
          items: createItems(100),
          getNextPage: spy,
        },
        extraResources,
        $view
      );
      expect(scrollNextArgs).toBe(undefined, 'getNextPage() args[]');
      expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
      expect(virtualRepeat.viewCount()).toBe(12, 'repeat.viewCount()');
      expect(spy.calls.count()).toBe(0, 'no getNextPage() calls');

      expect(viewModel.items.length).toBe(100, 'items.length 1');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      scrollRepeat(virtualRepeat, 20 * itemHeight);
      await waitForFrames(2);
      expect(viewModel.items.length).toBe(100, 'items.length 2');
      let virtualRepeatFirst = virtualRepeat.$first;
      let firstViewIndex = virtualRepeat.firstViewIndex();
      let lastViewIndex = virtualRepeat.lastViewIndex();
      expect(firstViewIndex).toBe(20, 'repeat._firstViewIndex() 1');
      expect(virtualRepeatFirst).toBe(20, 'repeat._first 1 = 88');
      expect(lastViewIndex).toBe(20 + virtualRepeat.minViewsRequired * 2 - 1, 'repeat._lastViewIndex() 1');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);
      expect(scrollNextArgs).toBe(undefined, 'scrollNextArgs is undefined');

      for (let i = 0; 15 >= i; ++i) {
        scrollRepeat(virtualRepeat, (20 - i) * itemHeight);
        await waitForFrames(2);
        virtualRepeatFirst = virtualRepeat.$first;
        firstViewIndex = virtualRepeat.firstViewIndex();
        lastViewIndex = virtualRepeat.lastViewIndex();
        expect(firstViewIndex).toBe(20 - i, 'repeat._firstViewIndex() 2');
        expect(lastViewIndex).toBe(20 - i + virtualRepeat.minViewsRequired * 2 - 1, 'repeat._lastViewIndex() 2');
      }

      scrollRepeat(virtualRepeat, 4 * itemHeight);
      expect(spy.calls.count()).toBe(0, '@scroll 2 end -> start');
      await waitForFrames(1);
      expect(spy.calls.count()).toBe(0, '@scroll 2 end -> start');
      await waitForFrames(2);
      expect(spy.calls.count()).toBe(1, '@scroll 2 end -> start');
      expect(viewModel.items.length).toBe(200, 'items.length 3');

      let hasValueConverterInExpression = extraResources.length > 0;
      virtualRepeatFirst = virtualRepeat.$first;
      firstViewIndex = virtualRepeat.firstViewIndex();
      lastViewIndex = virtualRepeat.lastViewIndex();

      expect(firstViewIndex).toBe(hasValueConverterInExpression ? 4 : 104, 'repeat._firstViewIndex() 3');
      expect(lastViewIndex).toBe((hasValueConverterInExpression ? 4 : 104) + virtualRepeat.minViewsRequired * 2 - 1, 'repeat._lastViewIndex() 3');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      let [firstIndex, isAtBottom, isAtTop] = scrollNextArgs;
      expect(firstIndex).toBe(4, 'scrollNextArgs[0] 2');
      expect(isAtBottom).toBe(false, 'scrollNextArgs[1] -- isAtBottom 2');
      expect(isAtTop).toBe(true, 'scrollNextArgs[2] -- isAtTop 2');
    });

    it([
      title,
      'handles getting next data set with promises',
      ' -- sroll to end',
      ' -- wait',
      ' -- scroll to top',
    ].join('\n\t'), async () => {
      let scrollNextArgs: [number, boolean, boolean];
      const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        let [_, isAtBottom] = scrollNextArgs = normalizeScrollNextArgs(args);
        return new Promise<void>(async (resolve) => {
          await waitForFrames(2);
          let itemLength = this.items.length;
          for (let i = 0; i < 100; ++i) {
            let itemNum = itemLength + i;
            this.items.push('item' + itemNum);
          }
          resolve();
        });
      }).and.callThrough();
      let { virtualRepeat, viewModel } = await bootstrapComponent(
        {
          items: createItems(100),
          getNextPage: spy,
        },
        extraResources,
        $view
      );

      expect(scrollNextArgs).toBe(undefined, 'getNextPage() args[]');
      expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
      expect(virtualRepeat.viewCount()).toBe(12, 'repeat.viewCount()');
      expect(spy.calls.count()).toBe(0, 'no getNextPage() calls 1');

      expect(viewModel.items.length).toBe(100, 'items.length 1');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      scrollRepeat(virtualRepeat, 'end');
      // assert that nothing changed after
      // 1 frame for scroll handler to start working
      // 1 frame for getMore to be invoked
      await waitForFrames(2);
      expect(scrollNextArgs).toEqual([88, true, false], 'scrollNextArgs 1');
      expect(spy.calls.count()).toBe(1, '1 getNextPage() calls 2');

      // not yet loaded
      expect(viewModel.items.length).toBe(100, 'items.length 2 | promise started, not loaded');
      await waitForFrames(2);
      // loaded
      expect(viewModel.items.length).toBe(200, 'items.length 2 | promise resolved, loaded');
    });

    it([
      title,
      'handles getting next data set with promises',
      ' -- start 10 (smaller than min views required: 12)',
      ' -- sroll 1px (no change in indices)',
    ].join('\n\t'), async () => {
      let scrollNextArgs: [number, boolean, boolean];
      const spy = jasmine.createSpy('viewModel.getNextPage(): void', function(this: ITestAppInterface<string>, ...args: any[]) {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        let [_, isAtBottom] = scrollNextArgs = normalizeScrollNextArgs(args);
        return new Promise<void>(async (resolve) => {
          await waitForFrames(2);
          let itemLength = this.items.length;
          for (let i = 0; i < 1; ++i) {
            let itemNum = itemLength + i;
            this.items.push('item' + itemNum);
          }
          resolve();
        });
      }).and.callThrough();
      let { virtualRepeat, viewModel } = await bootstrapComponent(
        {
          items: createItems(10),
          getNextPage: spy,
        },
        extraResources,
        $view
      );

      expect(scrollNextArgs).toBe(undefined, 'getNextPage() args[]');
      expect(virtualRepeat.minViewsRequired * 2).toBe(12, 'repeat._viewsLength');
      expect(virtualRepeat.viewCount()).toBe(10, 'repeat.viewCount()');
      expect(spy.calls.count()).toBe(0, 'no getNextPage() calls 1');

      expect(viewModel.items.length).toBe(10, 'items.length 1');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      scrollRepeat(virtualRepeat, 1);
      // assert that nothing changed after
      // 1 frame for scroll handler to start working
      // 1 frame for getMore to be invoked
      await waitForFrames(2);
      assertScrollNextArgsEqual(scrollNextArgs, [0, true, true], 'scrollnextArgs 1');
      // expect(scrollNextArgs).toEqual([/* first view index */0, true, false], 'scrollNextArgs 1');
      expect(spy.calls.count()).toBe(1, '1 getNextPage() calls 2');

      // not yet loaded
      expect(viewModel.items.length).toBe(10, 'items.length 2 | promise started, not loaded');
      await waitForFrames(2);
      // loaded
      expect(viewModel.items.length).toBe(11, 'items.length 2 | promise resolved, loaded');
      validateScrolledState(virtualRepeat, viewModel, itemHeight);

      // ========================
      // try to scroll again, but back to 0 from 1px
      scrollRepeat(virtualRepeat, 0);
      // assert that nothing changed after
      // 1 frame for scroll handler to start working
      // 1 frame for getMore to be invoked
      await waitForFrames(2);
      assertScrollNextArgsEqual(scrollNextArgs, [0, true, true], 'scrollnextArgs 2');
      expect(spy.calls.count()).toBe(2, '2 getNextPage() calls 3');

      // not yet loaded
      expect(viewModel.items.length).toBe(11, 'items.length 3 | promise started, not loaded');
      await waitForFrames(2);
      // loaded
      expect(viewModel.items.length).toBe(12, 'items.length 3 | promise resolved, loaded');

    });
  }

  async function bootstrapComponent<T>($viewModel?: ITestAppInterface<T>, extraResources?: any[], $view = view) {
    component = StageComponent
      .withResources([
        ...resources,
        ...extraResources,
      ])
      .inView($view)
      .boundTo($viewModel);
    await component.create(bootstrap);
    expect(document.body.contains(component.element)).toBe(true, 'repeat is setup in document');
    return { virtualRepeat: component.viewModel, viewModel: $viewModel, component: component };
  }

  function createItems(amount: number, name = 'item') {
    return Array.from({ length: amount }, (_, index) => name + index);
  }

  function normalizeScrollNextArgs(args: any[]): [number, boolean, boolean] {
    return typeof args[0] === 'number'
      ? [args[0], args[1], args[2]]
      : [args[0].topIndex, args[0].isAtBottom, args[0].isAtTop];
  }

  function assertScrollNextArgsEqual(scrollnextInfo: [number, boolean, boolean], expectedScrollnextInfo: [number, boolean, boolean], prefixMessage = ''): void {
    expect(Array.isArray(scrollnextInfo)).toBe(true, `[${prefixMessage}] scroll next info should have been defined`);
    const [actualTopIndex, actualIsNearBottom, actualIsNearTop] = scrollnextInfo;
    const [expectedTopIndex, expectedIsNearBottom, expectedIsNearTop] = expectedScrollnextInfo;
    expect(actualTopIndex).toBe(expectedTopIndex, `[${prefixMessage}] {top index(${actualTopIndex})} to be ${expectedTopIndex}`);
    expect(actualIsNearBottom).toBe(expectedIsNearBottom, `[${prefixMessage}] {is near bottom(${actualIsNearBottom})} to be ${expectedIsNearBottom}`);
    expect(actualIsNearTop).toBe(expectedIsNearTop, `[${prefixMessage}] {is near top (${actualIsNearTop})} to be ${expectedIsNearTop}`);
  }
});


text:
package main

import (
	"flag"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"time"
)

func main() {
	// Parse the command line.
	fAddr := flag.String("addr", "localhost:9876", "network addres to listen on")
	fVerbose := flag.Bool("verbose", false, "print verbose output to stderr")

	flag.Parse()

	if flag.NArg() != 1 {
		usage()
	}
	root := flag.Arg(0)

	if !*fVerbose {
		log.SetOutput(ioutil.Discard)
	}

	// Set up the HTTP handler.
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		log.Printf("%v %v from %v", req.Method, req.URL, req.RemoteAddr)

		// Only GET method is allowed.
		if req.Method != "GET" {
			http.Error(rw, "Method Not Allowed", http.StatusMethodNotAllowed)
			return
		}

		urlPath := req.URL.Path

		// Only pseudo-files called "latest" can be requested.
		if base := path.Base(urlPath); base != "latest" {
			http.Error(rw, "Filename Not Allowed", http.StatusForbidden)
			return
		}

		// Find the most recently modified file.
		infos, err := ioutil.ReadDir(filepath.Join(root, path.Dir(urlPath)))
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		if len(infos) == 0 {
			http.Error(rw, "Directory Empty", http.StatusNotFound)
			return
		}

		var (
			k int
			t time.Time
		)
		for i, info := range infos {
			if mt := info.ModTime(); mt.After(t) {
				t = mt
				k = i
			}
		}

		// Return a redirect.
		newPath := path.Join(path.Dir(urlPath), infos[k].Name())
		http.Redirect(rw, req, newPath, http.StatusTemporaryRedirect)
	})

	// Listen and serve until killed.
	if err := http.ListenAndServe(*fAddr, nil); err != nil {
		log.Fatal(err)
	}
}

func usage() {
	io.WriteString(os.Stderr, `USAGE
  latest-artifact [-verbose] [-addr=ADDR] ROOT

OPTIONS
`)
	flag.PrintDefaults()
	io.WriteString(os.Stderr, `
DESCRIPTION
  Start listening for artifacts GET requests using ROOT as the server root.

  This server does not serve any files itself, but when hit with a GET request
  for a pseudo-file called "latest", it returns a redirect to the most recently
  modified file in the relevant directory.

`)
	os.Exit(2)
}


text:
from django.contrib import admin
from django.utils.translation import gettext_lazy as _

from pingfmsmash.models import Message, Feed, PingFMAccount

class MessageAdmin(admin.ModelAdmin):
    list_display = ('feed', 'message', 'pinged', 'sent_to_pingfm')

class FeedAdmin(admin.ModelAdmin):
    list_display = ('name', 'url', 'link_shortener', 'tracking_codes', 'last_checked',)

class PingFMAccountAdmin(admin.ModelAdmin):
    list_display = ('name', 'pingfm_email', 'pingfm_user_key', 'prefer_api', 'minimum_datetime', 'active')

admin.site.register(Message, MessageAdmin)
admin.site.register(Feed, FeedAdmin)
admin.site.register(PingFMAccount, PingFMAccountAdmin)


text:
using UnityEngine;
using System.Collections;

namespace BehaviorDesigner.Runtime.Tasks.Basic.UnityAnimator
{
    [TaskCategory("Basic/Animator")]
    [TaskDescription("Sets the float parameter on an animator. Returns Success.")]
    public class SetFloatParameter : Action
    {
        [Tooltip("The GameObject that the task operates on. If null the task GameObject is used.")]
        public SharedGameObject targetGameObject;
        [Tooltip("The name of the parameter")]
        public SharedString paramaterName;
        [Tooltip("The value of the float parameter")]
        public SharedFloat floatValue;
        [Tooltip("Should the value be reverted back to its original value after it has been set?")]
        public bool setOnce;

        private int hashID;
        private Animator animator;
        private GameObject prevGameObject;

        public override void OnStart()
        {
            var currentGameObject = GetDefaultGameObject(targetGameObject.Value);
            if (currentGameObject != prevGameObject) {
                animator = currentGameObject.GetComponent<Animator>();
                prevGameObject = currentGameObject;
            }
        }

        public override TaskStatus OnUpdate()
        {
            if (animator == null) {
                Debug.LogWarning("Animator is null");
                return TaskStatus.Failure;
            }

            hashID = UnityEngine.Animator.StringToHash(paramaterName.Value);

            float prevValue = animator.GetFloat(hashID);
            animator.SetFloat(hashID, floatValue.Value);
            if (setOnce) {
                StartCoroutine(ResetValue(prevValue));
            }

            return TaskStatus.Success;
        }

        public IEnumerator ResetValue(float origVale)
        {
            yield return null;
            animator.SetFloat(hashID, origVale);
        }

        public override void OnReset()
        {
            targetGameObject = null;
            paramaterName = "";
            floatValue = 0;
        }
    }
}


text:
package org.pentaho.di.trans.steps.regexeval;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;

/**
 * Use regular expression to validate a field or capture new fields out of an existing field.
 *
 * @author deinspanjer
 * @since 27-03-2008
 * @author Matt
 * @since 15-08-2007
 */
public class RegexEval extends BaseStep implements StepInterface {
  private static Class<?> PKG = RegexEvalMeta.class; // for i18n purposes,
  // needed by
  // Translator2!!

  private RegexEvalMeta meta;
  private RegexEvalData data;

  public RegexEval( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta,
    Trans trans ) {
    super( stepMeta, stepDataInterface, copyNr, transMeta, trans );
  }

  public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException {
    meta = (RegexEvalMeta) smi;
    data = (RegexEvalData) sdi;

    Object[] row = getRow();

    if ( row == null ) { // no more input to be expected...

      setOutputDone();
      return false;
    }

    if ( first ) { // we just got started

      first = false;

      // get the RowMeta
      data.outputRowMeta = getInputRowMeta().clone();
      int captureIndex = getInputRowMeta().size();
      meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore );

      // Let's check that Result Field is given
      if ( Utils.isEmpty( environmentSubstitute( meta.getResultFieldName() ) ) ) {
        if ( !meta.isAllowCaptureGroupsFlagSet() ) {
          // Result field is missing !
          logError( BaseMessages.getString( PKG, "RegexEval.Log.ErrorResultFieldMissing" ) );
          throw new KettleStepException( BaseMessages.getString(
            PKG, "RegexEval.Exception.ErrorResultFieldMissing" ) );
        }
        data.indexOfResultField = -1;
      } else {
        if ( meta.isReplacefields() ) {
          data.indexOfResultField = getInputRowMeta().indexOfValue( meta.getResultFieldName() );
        }
        if ( data.indexOfResultField < 0 ) {
          data.indexOfResultField = getInputRowMeta().size();
          captureIndex++;
        }
      }

      // Check if a Field (matcher) is given
      if ( meta.getMatcher() == null ) {
        // Matcher is missing !
        logError( BaseMessages.getString( PKG, "RegexEval.Log.ErrorMatcherMissing" ) );
        throw new KettleStepException( BaseMessages.getString( PKG, "RegexEval.Exception.ErrorMatcherMissing" ) );
      }

      // Cache the position of the Field
      data.indexOfFieldToEvaluate = getInputRowMeta().indexOfValue( meta.getMatcher() );
      if ( data.indexOfFieldToEvaluate < 0 ) {
        // The field is unreachable !
        logError( BaseMessages.getString( PKG, "RegexEval.Log.ErrorFindingField" ) + "[" + meta.getMatcher() + "]" );
        throw new KettleStepException( BaseMessages.getString( PKG, "RegexEval.Exception.CouldnotFindField", meta
          .getMatcher() ) );
      }

      // Cache the position of the CaptureGroups
      if ( meta.isAllowCaptureGroupsFlagSet() ) {
        data.positions = new int[meta.getFieldName().length];
        String[] fieldName = meta.getFieldName();
        for ( int i = 0; i < fieldName.length; i++ ) {
          if ( fieldName[i] == null || fieldName[i].length() == 0 ) {
            continue;
          }
          if ( meta.isReplacefields() ) {
            data.positions[i] = data.outputRowMeta.indexOfValue( fieldName[i] );
          } else {
            data.positions[i] = captureIndex;
            captureIndex++;
          }
        }
      } else {
        data.positions = new int[0];
      }

      // Now create objects to do string to data type conversion...
      //
      data.conversionRowMeta = data.outputRowMeta.cloneToType( ValueMetaInterface.TYPE_STRING );
    }

    // reserve room
    Object[] outputRow = RowDataUtil.allocateRowData( data.outputRowMeta.size() );
    System.arraycopy( row, 0, outputRow, 0, getInputRowMeta().size() );

    try {
      // Get the Field value
      String fieldValue;
      boolean isMatch;

      if ( getInputRowMeta().isNull( row, data.indexOfFieldToEvaluate ) ) {
        fieldValue = "";
        isMatch = false;
      } else {
        fieldValue = getInputRowMeta().getString( row, data.indexOfFieldToEvaluate );

        // Start search engine
        Matcher m = data.pattern.matcher( fieldValue );
        isMatch = m.matches();

        if ( meta.isAllowCaptureGroupsFlagSet() && data.positions.length != m.groupCount() ) {
          // Runtime exception case. The number of capture groups in the
          // regex doesn't match the number of fields.
          logError( BaseMessages.getString( PKG, "RegexEval.Log.ErrorCaptureGroupFieldsMismatch", String
            .valueOf( m.groupCount() ), String.valueOf( data.positions.length ) ) );
          throw new KettleStepException( BaseMessages.getString(
            PKG, "RegexEval.Exception.ErrorCaptureGroupFieldsMismatch", String.valueOf( m.groupCount() ), String
              .valueOf( data.positions.length ) ) );
        }

        for ( int i = 0; i < data.positions.length; i++ ) {
          int index = data.positions[i];
          String value;
          if ( isMatch ) {
            value = m.group( i + 1 );
          } else {
            value = null;
          }

          // this part (or possibly the whole) of the regex didn't match
          // preserve the incoming data, but allow for "trim type", etc.
          if ( value == null ) {
            try {
              value = data.outputRowMeta.getString( outputRow, index );
            } catch ( ArrayIndexOutOfBoundsException err ) {
              // Ignore errors
            }
          }

          ValueMetaInterface valueMeta = data.outputRowMeta.getValueMeta( index );
          ValueMetaInterface conversionValueMeta = data.conversionRowMeta.getValueMeta( index );
          Object convertedValue =
            valueMeta.convertDataFromString( value, conversionValueMeta, meta.getFieldNullIf()[i], meta
              .getFieldIfNull()[i], meta.getFieldTrimType()[i] );

          outputRow[index] = convertedValue;
        }
      }

      if ( data.indexOfResultField >= 0 ) {
        outputRow[data.indexOfResultField] = isMatch;
      }

      if ( log.isRowLevel() ) {
        logRowlevel( BaseMessages.getString( PKG, "RegexEval.Log.ReadRow" )
          + " " + getInputRowMeta().getString( row ) );
      }

      // copy row to output rowset(s);
      //
      putRow( data.outputRowMeta, outputRow );
    } catch ( KettleException e ) {
      boolean sendToErrorRow = false;
      String errorMessage = null;

      if ( getStepMeta().isDoingErrorHandling() ) {
        sendToErrorRow = true;
        errorMessage = e.toString();
      } else {
        throw new KettleStepException( BaseMessages.getString( PKG, "RegexEval.Log.ErrorInStep" ), e );
      }

      if ( sendToErrorRow ) {
        // Simply add this row to the error row
        putError( getInputRowMeta(), outputRow, 1, errorMessage, null, "REGEX001" );
      }
    }
    return true;
  }

  public boolean init( StepMetaInterface smi, StepDataInterface sdi ) {
    meta = (RegexEvalMeta) smi;
    data = (RegexEvalData) sdi;

    if ( super.init( smi, sdi ) ) {
      // Embedded options
      String options = meta.getRegexOptions();

      // Regular expression
      String regularexpression = meta.getScript();
      if ( meta.isUseVariableInterpolationFlagSet() ) {
        regularexpression = environmentSubstitute( meta.getScript() );
      }
      if ( log.isDetailed() ) {
        logDetailed( BaseMessages.getString( PKG, "RegexEval.Log.Regexp" ) + " " + options + regularexpression );
      }

      if ( meta.isCanonicalEqualityFlagSet() ) {
        data.pattern = Pattern.compile( options + regularexpression, Pattern.CANON_EQ );
      } else {
        data.pattern = Pattern.compile( options + regularexpression );
      }
      return true;
    }
    return false;
  }

  public void dispose( StepMetaInterface smi, StepDataInterface sdi ) {
    meta = (RegexEvalMeta) smi;
    data = (RegexEvalData) sdi;

    data.pattern = null;

    super.dispose( smi, sdi );
  }

}


text:
'use strict';

angular.module('events').controller('CreateEventController', ['$scope', '$location', 'Events',
  function($scope, $location, Events) {
    $scope.save = function() {
      this.submitting = true;

      var event = new Events({
        title: this.title,
        category: this.category,
        description: this.description,
        start: this.start,
        end: this.end,
        featured: this.featured
      });

      event.$save(
        function(response) {
          $scope.success = true;
          $scope.error = false;

          $scope.title = '';
          $scope.start = '';
          $scope.end = '';
          $scope.category = '';
          $scope.description = '';

          $scope.submitting = false;
        },
        function(err) {
          $scope.error = err.data.message;
          $scope.success = true;

          $scope.submitting = false;
        }
      );
    };
  }
]);


text:
package com.xrtb.privatex.bidrequest;

import java.util.UUID;

/**
 * The RTB Impression object
 * @author Ben M. Faul
 *
 */

public class Impression {
   /** The impression id */
   public  String id = UUID.randomUUID().toString();
   /** Interstitial */
   public int  instl;
   /** The banner object */
   public Banner banner;
   /** The video object. */
   public Video video;
   /** An extension object */
   public Ext ext = new Ext();

   /**
    * Default constructor
    */
   public Impression() {

   }

   /**
    * Make this a banner impression. Nulls the video, if present.
    * @return Impression. A reference to itself.
    */
   public Impression doBanner() {
	   video = null;
	   banner = new Banner();
	   return this;
   }

   /**
    * Make this a video impression. Nulls the banner, if present.
    * @return A reference to itself.
    */
   public Impression doVideo() {
	   banner = null;
	   video = new Video();
	   return this;
   }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections;
using System.Collections.Generic;

namespace System.Linq
{
    public static partial class Enumerable
    {
        private sealed partial class DefaultIfEmptyIterator<TSource> : IIListProvider<TSource>
        {
            public TSource[] ToArray()
            {
                TSource[] array = _source.ToArray();
                return array.Length == 0 ? new[] { _default } : array;
            }

            public List<TSource> ToList()
            {
                List<TSource> list = _source.ToList();
                if (list.Count == 0)
                {
                    list.Add(_default);
                }

                return list;
            }

            public int GetCount(bool onlyIfCheap)
            {
                int count;
                if (!onlyIfCheap || _source is ICollection<TSource> || _source is ICollection)
                {
                    count = _source.Count();
                }
                else
                {
                    count = _source is IIListProvider<TSource> listProv ? listProv.GetCount(onlyIfCheap: true) : -1;
                }

                return count == 0 ? 1 : count;
            }
        }
    }
}


text:
import glob
import os

import mock
from six.moves import builtins

from nova import exception
from nova.pci import utils
from nova import test

class PciDeviceMatchTestCase(test.NoDBTestCase):
    def setUp(self):
        super(PciDeviceMatchTestCase, self).setUp()
        self.fake_pci_1 = {'vendor_id': 'v1',
                           'device_id': 'd1'}

    def test_single_spec_match(self):
        self.assertTrue(utils.pci_device_prop_match(
            self.fake_pci_1, [{'vendor_id': 'v1', 'device_id': 'd1'}]))

    def test_multiple_spec_match(self):
        self.assertTrue(utils.pci_device_prop_match(
            self.fake_pci_1,
            [{'vendor_id': 'v1', 'device_id': 'd1'},
             {'vendor_id': 'v3', 'device_id': 'd3'}]))

    def test_spec_dismatch(self):
        self.assertFalse(utils.pci_device_prop_match(
            self.fake_pci_1,
            [{'vendor_id': 'v4', 'device_id': 'd4'},
             {'vendor_id': 'v3', 'device_id': 'd3'}]))

    def test_spec_extra_key(self):
        self.assertFalse(utils.pci_device_prop_match(
            self.fake_pci_1,
            [{'vendor_id': 'v1', 'device_id': 'd1', 'wrong_key': 'k1'}]))

class PciDeviceAddressParserTestCase(test.NoDBTestCase):
    def test_parse_address(self):
        self.parse_result = utils.parse_address("0000:04:12.6")
        self.assertEqual(self.parse_result, ('0000', '04', '12', '6'))

    def test_parse_address_wrong(self):
        self.assertRaises(exception.PciDeviceWrongAddressFormat,
            utils.parse_address, "0000:04.12:6")

    def test_parse_address_invalid_character(self):
        self.assertRaises(exception.PciDeviceWrongAddressFormat,
            utils.parse_address, "0000:h4.12:6")

class GetFunctionByIfnameTestCase(test.NoDBTestCase):

    @mock.patch('os.path.isdir', return_value=True)
    @mock.patch.object(os, 'readlink')
    def test_virtual_function(self, mock_readlink, *args):
        mock_readlink.return_value = '../../../0000.00.00.1'
        with mock.patch.object(
            builtins, 'open', side_effect=IOError()):
            address, physical_function = utils.get_function_by_ifname('eth0')
            self.assertEqual(address, '0000.00.00.1')
            self.assertFalse(physical_function)

    @mock.patch('os.path.isdir', return_value=True)
    @mock.patch.object(os, 'readlink')
    def test_physical_function(self, mock_readlink, *args):
        mock_readlink.return_value = '../../../0000:00:00.1'
        with mock.patch.object(
            builtins, 'open', mock.mock_open(read_data='4')):
            address, physical_function = utils.get_function_by_ifname('eth0')
            self.assertEqual(address, '0000:00:00.1')
            self.assertTrue(physical_function)

    @mock.patch('os.path.isdir', return_value=False)
    def test_exception(self, *args):
        address, physical_function = utils.get_function_by_ifname('lo')
        self.assertIsNone(address)
        self.assertFalse(physical_function)

class IsPhysicalFunctionTestCase(test.NoDBTestCase):

    def setUp(self):
        super(IsPhysicalFunctionTestCase, self).setUp()
        self.pci_args = utils.get_pci_address_fields('0000:00:00.1')

    @mock.patch('os.path.isdir', return_value=True)
    def test_virtual_function(self, *args):
        with mock.patch.object(
            builtins, 'open', side_effect=IOError()):
            self.assertFalse(utils.is_physical_function(*self.pci_args))

    @mock.patch('os.path.isdir', return_value=True)
    def test_physical_function(self, *args):
        with mock.patch.object(
            builtins, 'open', mock.mock_open(read_data='4')):
            self.assertTrue(utils.is_physical_function(*self.pci_args))

    @mock.patch('os.path.isdir', return_value=False)
    def test_exception(self, *args):
        self.assertFalse(utils.is_physical_function(*self.pci_args))

class GetIfnameByPciAddressTestCase(test.NoDBTestCase):

    def setUp(self):
        super(GetIfnameByPciAddressTestCase, self).setUp()
        self.pci_address = '0000:00:00.1'

    @mock.patch.object(os, 'listdir')
    def test_physical_function_inferface_name(self, mock_listdir):
        mock_listdir.return_value = ['foo', 'bar']
        ifname = utils.get_ifname_by_pci_address(
            self.pci_address, pf_interface=True)
        self.assertEqual(ifname, 'bar')

    @mock.patch.object(os, 'listdir')
    def test_virtual_function_inferface_name(self, mock_listdir):
        mock_listdir.return_value = ['foo', 'bar']
        ifname = utils.get_ifname_by_pci_address(
            self.pci_address, pf_interface=False)
        self.assertEqual(ifname, 'bar')

    @mock.patch.object(os, 'listdir')
    def test_exception(self, mock_listdir):
        mock_listdir.side_effect = OSError('No such file or directory')
        self.assertRaises(
            exception.PciDeviceNotFoundById,
            utils.get_ifname_by_pci_address,
            self.pci_address
        )

class GetVfNumByPciAddressTestCase(test.NoDBTestCase):

    def setUp(self):
        super(GetVfNumByPciAddressTestCase, self).setUp()
        self.pci_address = '0000:00:00.1'
        self.paths = [
            '/sys/bus/pci/devices/0000:00:00.1/physfn/virtfn3',
        ]

    @mock.patch.object(os, 'readlink')
    @mock.patch.object(glob, 'iglob')
    def test_vf_number_found(self, mock_iglob, mock_readlink):
        mock_iglob.return_value = self.paths
        mock_readlink.return_value = '../../0000:00:00.1'
        vf_num = utils.get_vf_num_by_pci_address(self.pci_address)
        self.assertEqual(vf_num, '3')

    @mock.patch.object(os, 'readlink')
    @mock.patch.object(glob, 'iglob')
    def test_vf_number_not_found(self, mock_iglob, mock_readlink):
        mock_iglob.return_value = self.paths
        mock_readlink.return_value = '../../0000:00:00.2'
        self.assertRaises(
            exception.PciDeviceNotFoundById,
            utils.get_vf_num_by_pci_address,
            self.pci_address
        )

    @mock.patch.object(os, 'readlink')
    @mock.patch.object(glob, 'iglob')
    def test_exception(self, mock_iglob, mock_readlink):
        mock_iglob.return_value = self.paths
        mock_readlink.side_effect = OSError('No such file or directory')
        self.assertRaises(
            exception.PciDeviceNotFoundById,
            utils.get_vf_num_by_pci_address,
            self.pci_address
        )