text:
using System;
using Newtonsoft.Json;
using osu.Game.Graphics;
using osu.Game.Utils;
using osuTK.Graphics;

namespace osu.Game.Beatmaps.ControlPoints
{
    public abstract class ControlPoint : IComparable<ControlPoint>, IDeepCloneable<ControlPoint>
    {
        /// <summary>
        /// The time at which the control point takes effect.
        /// </summary>
        [JsonIgnore]
        public double Time { get; set; }

        public void AttachGroup(ControlPointGroup pointGroup) => Time = pointGroup.Time;

        public int CompareTo(ControlPoint other) => Time.CompareTo(other.Time);

        public virtual Color4 GetRepresentingColour(OsuColour colours) => colours.Yellow;

        /// <summary>
        /// Determines whether this <see cref="ControlPoint"/> results in a meaningful change when placed alongside another.
        /// </summary>
        /// <param name="existing">An existing control point to compare with.</param>
        /// <returns>Whether this <see cref="ControlPoint"/> is redundant when placed alongside <paramref name="existing"/>.</returns>
        public abstract bool IsRedundant(ControlPoint existing);

        /// <summary>
        /// Create an unbound copy of this control point.
        /// </summary>
        public ControlPoint DeepClone()
        {
            var copy = (ControlPoint)Activator.CreateInstance(GetType());

            copy.CopyFrom(this);

            return copy;
        }

        public virtual void CopyFrom(ControlPoint other)
        {
            Time = other.Time;
        }
    }
}


text:
'use strict';

module.exports = {
  trim (subject, param, opts) {
    return subject ? (subject || '').trim() : subject;
  },
  toUpperCase (subject, param, opts) {
    return subject ? (subject || '').toUpperCase() : subject;
  },
  toLowerCase (subject, param, opts) {
    return subject ? (subject || '').toLowerCase() : subject;
  }
};

redpajama_set_name: RedPajamaGithub


text:
<?php
date_default_timezone_set('America/Chicago');
set_include_path(
	dirname(__FILE__) . PATH_SEPARATOR .
	get_include_path()
);

function render($file, $args = array(), $use_cache = true) {
	static $cache;

	if (!isset($cache)) $cache = array();

	$cache_key = sha1($file.serialize($args));

	if (!$use_cache || !isset($cache[$cache_key])) {
		if (!file_exists($file))
			return "";

		extract($GLOBALS);
		extract($args);

		ob_start();
		include $file;

		if ($use_cache)
			$cache[$cache_key] = ob_get_clean();
		else
			return ob_get_clean();
	}

	return $cache[$cache_key];
}

include 'data.php';
$GLOBALS['version'] = file_get_contents('site.version');

echo render('templates/layout.php');


text:
package com.jeasonfire.galaxies.systems;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.annotations.Mapper;
import com.artemis.utils.ImmutableBag;
import com.badlogic.gdx.Gdx;
import com.jeasonfire.galaxies.components.COrbit;
import com.jeasonfire.galaxies.components.CPosition;
import com.jeasonfire.galaxies.util.GameState;

public class OrbitSystem extends EntitySystem {
	@Mapper
	private ComponentMapper<CPosition> positionMapper;
	@Mapper
	private ComponentMapper<COrbit> orbitMapper;

	private double time = 0;
	private boolean firstTicked = false;

	@SuppressWarnings("unchecked")
	public OrbitSystem() {
		super(Aspect.getAspectForAll(CPosition.class, COrbit.class));
	}

	@Override
	protected void processEntities(ImmutableBag<Entity> entities) {
		if (GameState.state != GameState.GAME && firstTicked) {
			return;
		} else {
			firstTicked = true;
		}

		time += Gdx.graphics.getDeltaTime();
		for (int i = 0; i < entities.size(); i++) {
			Entity e = entities.get(i);
			positionMapper.get(e).x = (float) Math.cos(Math.toRadians(time
					* 360f / orbitMapper.get(e).orbitSpeed + orbitMapper.get(e).orbitOffset))
					* orbitMapper.get(e).orbitRadius
					+ orbitMapper.get(e).orbitCenterX;
			positionMapper.get(e).y = (float) Math.sin(Math.toRadians(time
					* 360f / orbitMapper.get(e).orbitSpeed + orbitMapper.get(e).orbitOffset))
					* orbitMapper.get(e).orbitRadius
					+ orbitMapper.get(e).orbitCenterY;
		}
	}

	@Override
	protected boolean checkProcessing() {
		return true;
	}
}


text:
<?php

declare(strict_types=1);

namespace Tests\Unit;

use App\Models\DuesPackage;
use App\Models\DuesTransaction;
use App\Models\Payment;
use Tests\TestCase;

class UserTest extends TestCase
{
    /**
     * Test the is_student attribute.
     *
     * @return void
     */
    public function testIsStudent()
    {
        $user = $this->getTestUser(['member']);

        $user->primary_affiliation = 'member';
        $this->assertFalse($user->is_student);
        $user->primary_affiliation = 'faculty';
        $this->assertFalse($user->is_student);
        $user->primary_affiliation = 'staff';
        $this->assertFalse($user->is_student);
        $user->primary_affiliation = 'employee';
        $this->assertFalse($user->is_student);
        $user->primary_affiliation = 'affiliate';
        $this->assertFalse($user->is_student);

        $user->primary_affiliation = 'student';
        $this->assertTrue($user->is_student);

        // Create dues package / transaction / payment
        $package = DuesPackage::factory()->make();
        $package->effective_end = now()->addMonths(10);
        $package->restricted_to_students = true;
        $package->save();
        $transaction = new DuesTransaction();
        $transaction->user_id = $user->id;
        $transaction->dues_package_id = $package->id;
        $transaction->save();
        $payment = new Payment();
        $payment->payable_id = $transaction->id;
        $payment->payable_type = DuesTransaction::getMorphClassStatic();
        $payment->recorded_by = $user->id;
        $payment->method = 'cash';
        $payment->amount = $package->cost;
        // @phan-suppress-next-line PhanTypeMismatchPropertyProbablyReal
        $payment->processing_fee = 0;
        $payment->save();

        // They paid a student package
        $this->assertTrue($user->is_student);

        $package->restricted_to_students = false;
        $package->save();

        // They paid a non-student package
        $this->assertFalse($user->is_student);
    }
}


text:
using Open.Collections;
using Open.Numeric;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace Multiplexer
{
	[SuppressMessage("ReSharper", "IteratorNeverReturns")]
	public sealed class SampleCache
	{
		public sealed class Entry
		{
			public readonly IReadOnlyList<double> ParamValues;
			public readonly Lazy<double> Correct;

			public Entry(IReadOnlyList<double> paramValues, Formula f)
			{
				ParamValues = paramValues;
				Correct = Lazy.Create(() => f(ParamValues));
			}
		}

		readonly Formula _actualFormula;
		readonly ConcurrentDictionary<long, LazyList<Entry>> _sampleCache;

		public readonly double Range;

		public SampleCache(Formula actualFormula, double range = 100)
		{
			Range = range;
			_actualFormula = actualFormula;
			_sampleCache = new ConcurrentDictionary<long, LazyList<Entry>>();
		}

		public IEnumerable<Entry> Generate()
		{
			while (true)
				yield return new Entry(Samples()/*.Distinct()*/.Memoize(true), _actualFormula);
		}

		public LazyList<Entry> Get(long id)
			=> _sampleCache.GetOrAdd(id, key => Generate().Memoize(true));

		IEnumerable<double> Samples()
		{
			var offset = RandomUtilities.Random.Next(1000) - Range / 2;
			while (true)
			{
				yield return RandomUtilities.Random.NextDouble() * Range + offset;
			}
		}

	}
}


text:
package vault

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/hashicorp/terraform/helper/schema"

	"github.com/hashicorp/vault/api"
)

func genericSecretResource() *schema.Resource {
	return &schema.Resource{
		Create: genericSecretResourceWrite,
		Update: genericSecretResourceWrite,
		Delete: genericSecretResourceDelete,
		Read:   genericSecretResourceRead,

		Schema: map[string]*schema.Schema{
			"path": &schema.Schema{
				Type:        schema.TypeString,
				Required:    true,
				ForceNew:    true,
				Description: "Full path where the generic secret will be written.",
			},

			// Data is passed as JSON so that an arbitrary structure is
			// possible, rather than forcing e.g. all values to be strings.
			"data_json": &schema.Schema{
				Type:        schema.TypeString,
				Required:    true,
				Description: "JSON-encoded secret data to write.",
			},
		},
	}
}

func genericSecretResourceWrite(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*api.Client)

	path := d.Get("path").(string)

	var data map[string]interface{}
	err := json.Unmarshal([]byte(d.Get("data_json").(string)), &data)
	if err != nil {
		return fmt.Errorf("data_json %#v syntax error: %s", d.Get("data_json"), err)
	}

	log.Printf("[DEBUG] Writing generic Vault secret to %s", path)
	_, err = client.Logical().Write(path, data)
	if err != nil {
		return fmt.Errorf("error writing to Vault: %s", err)
	}

	d.SetId(path)

	return nil
}

func genericSecretResourceDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*api.Client)

	path := d.Id()

	log.Printf("[DEBUG] Deleting generic Vault from %s", path)
	_, err := client.Logical().Delete(path)
	if err != nil {
		return fmt.Errorf("error deleting from Vault: %s", err)
	}

	return nil
}

func genericSecretResourceRead(d *schema.ResourceData, meta interface{}) error {
	// We don't actually attempt to read back the secret data
	// here, so that Terraform can be configured with a token
	// that has only write access to the relevant part of the
	// store.
	//
	// This means that Terraform cannot detect drift for
	// generic secrets, but detecting drift seems less important
	// than being able to limit the effect of exposure of
	// Terraform's Vault token.
	log.Printf("[WARN] vault_generic_secret does not automatically refresh")
	return nil
}


text:
package org.hisp.dhis.system.filter;

import org.hisp.dhis.commons.filter.Filter;
import org.hisp.dhis.dataelement.DataElement;

/**
 * @author Lars Helge Overland
 */
public class AggregatableDataElementFilter
    implements Filter<DataElement>
{
    public static final AggregatableDataElementFilter INSTANCE = new AggregatableDataElementFilter();

    @Override
    public boolean retain( DataElement object )
    {
        return object != null && object.getValueType().isAggregateable() && object.getAggregationType().isAggregateable();
    }
}


text:
<?php

class Controller_Admin_Help extends Controller_Admin_Base
{
	public $page_title = 'Ajuda';

	public function action_index()
	{
		// Breadcrumb
		$this->set_breadcrumb();

		$this->template->content = View::forge('admin/help/index');
	}
}


text:
package org.apache.haox.asn1;

public enum TagClass {
    UNKNOWN(-1),
    UNIVERSAL(0x00),
    APPLICATION(0x40),
    CONTEXT_SPECIFIC(0x80),
    PRIVATE(0xC0);

    private int value;

    private TagClass(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public boolean isUniversal() {
        return this == UNIVERSAL;
    }

    public boolean isAppSpecific() {
        return this == APPLICATION;
    }

    public boolean isContextSpecific() {
        return this == CONTEXT_SPECIFIC;
    }

    public boolean isTagged() {
        return this == APPLICATION || this == CONTEXT_SPECIFIC;
    }

    public static TagClass fromValue(int value) {
        // Optimized by Emmanuel
        switch (value) {
            case 0x00:
                return TagClass.UNIVERSAL;
            case 0x40:
                return TagClass.APPLICATION;
            case 0x80:
                return TagClass.CONTEXT_SPECIFIC;
            case 0xC0:
                return TagClass.PRIVATE;
            default:
                return TagClass.UNKNOWN;
        }
    }

    public static TagClass fromTagFlags(int tag) {
        return fromValue(tag & 0xC0);
    }
}


text:
namespace
{
struct CellIdFeaturePairForTest
{
  CellIdFeaturePairForTest(uint64_t cell, uint32_t feature) : m_Cell(cell), m_Feature(feature) {}
  uint64_t GetCell() const { return m_Cell; }
  uint32_t GetFeature() const { return m_Feature; }
  uint64_t m_Cell;
  uint32_t m_Feature;
};
}

UNIT_TEST(IntervalIndex_LevelCount)
{
  TEST_EQUAL(IntervalIndexBuilder(10, 1, 3).GetLevelCount(), 1, ());
  TEST_EQUAL(IntervalIndexBuilder(11, 1, 3).GetLevelCount(), 1, ());
  TEST_EQUAL(IntervalIndexBuilder(12, 1, 3).GetLevelCount(), 2, ());
  TEST_EQUAL(IntervalIndexBuilder(19, 2, 3).GetLevelCount(), 1, ());
  TEST_EQUAL(IntervalIndexBuilder(19, 1, 3).GetLevelCount(), 4, ());
  TEST_EQUAL(IntervalIndexBuilder(20, 1, 3).GetLevelCount(), 4, ());
}

UNIT_TEST(IntervalIndex_SerializedNodeBitmap)
{
  uint32_t const offset = 350; // == 0x15E
  uint32_t childSizes[8] = { 0, 0, 0, 10, 0, 0, 1000, 0 };
  char const expSerial [] =
      "\xBD\x05"  // (350 << 1) + 1 == 701 == 0x2BD - offset encoded as varuint.
      "\x48"      // (1 << 3) | (1 << 6) == 72 == 0x48 - bitmap.
      "\x0A"      // 10 - childSizes[3] encoded as varuint.
      "\xE8\x07"  // 1000 = 0x3E8 - childSizes[6] encoded as varuint.
      "";
  vector<uint8_t> serializedNode;
  MemWriter<vector<uint8_t> > writer(serializedNode);
  IntervalIndexBuilder(11, 1, 3).WriteNode(writer, offset, childSizes);
  TEST_EQUAL(serializedNode, vector<uint8_t>(expSerial, expSerial + ARRAY_SIZE(expSerial) - 1), ());
}

UNIT_TEST(IntervalIndex_SerializedNodeList)
{
  uint32_t const offset = 350; // == 0x15E
  uint32_t childSizes[16] = { 0, 0, 0, 0, 0, 0, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  char const expSerial [] =
      "\xBC\x05"         // (350 << 1) + 0 == 700 == 0x2BC - offset encoded as varuint.
      "\x06" "\xE8\x07"  // 6, 1000
      "";
  vector<uint8_t> serializedNode;
  MemWriter<vector<uint8_t> > writer(serializedNode);
  IntervalIndexBuilder(11, 1, 4).WriteNode(writer, offset, childSizes);
  TEST_EQUAL(serializedNode, vector<uint8_t>(expSerial, expSerial + ARRAY_SIZE(expSerial) - 1), ());
}

UNIT_TEST(IntervalIndex_SerializedLeaves)
{
  vector<CellIdFeaturePairForTest> data;
  data.push_back(CellIdFeaturePairForTest(0x1537U, 0));
  data.push_back(CellIdFeaturePairForTest(0x1538U, 1));
  data.push_back(CellIdFeaturePairForTest(0x1637U, 2));
  vector<uint8_t> serialLeaves;
  MemWriter<vector<uint8_t> > writer(serialLeaves);
  vector<uint32_t> sizes;
  IntervalIndexBuilder(16, 1, 4).BuildLeaves(writer, data.begin(), data.end(), sizes);
  char const expSerial [] = "\x37\x00" "\x38\x02" "\x37\x04"; // 0x1537 0x1538 0x1637
  uint32_t const expSizes [] = { 4, 2 };
  TEST_EQUAL(serialLeaves, vector<uint8_t>(expSerial, expSerial + ARRAY_SIZE(expSerial) - 1), ());
  TEST_EQUAL(sizes, vector<uint32_t>(expSizes, expSizes + ARRAY_SIZE(expSizes)), ());
}

UNIT_TEST(IntervalIndex_SerializedNodes)
{
  vector<CellIdFeaturePairForTest> data;
  data.push_back(CellIdFeaturePairForTest(0x1537U, 0));
  data.push_back(CellIdFeaturePairForTest(0x1538U, 1));
  data.push_back(CellIdFeaturePairForTest(0x1637U, 2));
  uint32_t const leavesSizes [] = { 4, 2 };
  vector<uint8_t> serialNodes;
  MemWriter<vector<uint8_t> > writer(serialNodes);
  vector<uint32_t> sizes;
  IntervalIndexBuilder(16, 1, 4).BuildLevel(writer, data.begin(), data.end(), 1,
                                            leavesSizes, leavesSizes + ARRAY_SIZE(leavesSizes),
                                            sizes);
  char const expSerial [] = "\x01\x60\x00\x04\x02";
  uint32_t const expSizes [] = { ARRAY_SIZE(expSerial) - 1 };
  TEST_EQUAL(serialNodes, vector<uint8_t>(expSerial, expSerial + ARRAY_SIZE(expSerial) - 1), ());
  TEST_EQUAL(sizes, vector<uint32_t>(expSizes, expSizes + ARRAY_SIZE(expSizes)), ());
}

UNIT_TEST(IntervalIndex_Serialized)
{
  vector<CellIdFeaturePairForTest> data;
  data.push_back(CellIdFeaturePairForTest(0x1537U, 0));
  data.push_back(CellIdFeaturePairForTest(0x1538U, 1));
  data.push_back(CellIdFeaturePairForTest(0x1637U, 2));
  vector<uint8_t> serialIndex;
  MemWriter<vector<uint8_t> > writer(serialIndex);
  IntervalIndexBuilder(16, 1, 4).BuildIndex(writer, data.begin(), data.end());

  char const expSerial [] =
      "\x01\x02\x04\x01"               // Header
      "\x14\x00\x00\x00"               // Leaves level offset
      "\x1A\x00\x00\x00"               // Level 1 offset
      "\x1F\x00\x00\x00"               // Root level offset
      "\x22\x00\x00\x00"               // Root level offset
      "\x37\x00" "\x38\x02" "\x37\x04" // 0x1537 0x1538 0x1637
      "\x01\x60\x00\x04\x02"           // 0x15, 0x16 node
      "\x00\x01\x05"                   // Root
      "";

  TEST_EQUAL(serialIndex, vector<uint8_t>(expSerial, expSerial + ARRAY_SIZE(expSerial) - 1), ());

  MemReader reader(&serialIndex[0], serialIndex.size());
  IntervalIndex<MemReader> index(reader);
  uint32_t expected [] = {0, 1, 2};
  vector<uint32_t> values;
  TEST_EQUAL(index.KeyEnd(), 0x10000, ());
  index.ForEach(MakeBackInsertFunctor(values), 0, 0x10000);
  TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
}

UNIT_TEST(IntervalIndex_Simple)
{
  vector<CellIdFeaturePairForTest> data;
  data.push_back(CellIdFeaturePairForTest(0xA0B1C2D100ULL, 0));
  data.push_back(CellIdFeaturePairForTest(0xA0B1C2D200ULL, 1));
  data.push_back(CellIdFeaturePairForTest(0xA0B2C2D100ULL, 2));
  vector<char> serialIndex;
  MemWriter<vector<char> > writer(serialIndex);
  BuildIntervalIndex(data.begin(), data.end(), writer, 40);
  MemReader reader(&serialIndex[0], serialIndex.size());
  IntervalIndex<MemReader> index(reader);
  TEST_EQUAL(index.KeyEnd(), 0x10000000000ULL, ());
  {
    uint32_t expected [] = {0, 1, 2};
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0ULL, index.KeyEnd());
    TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
  }
  {
    uint32_t expected [] = {0, 1};
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0xA0B1C2D100ULL, 0xA0B1C2D201ULL);
    TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
  }
  {
    uint32_t expected [] = {0, 1};
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0x0ULL, 0xA0B1C30000ULL);
    TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
  }
  {
    uint32_t expected [] = {0};
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0xA0B1C2D100ULL, 0xA0B1C2D101ULL);
    TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
  }
  {
    uint32_t expected [] = {0};
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0xA0B1C2D100ULL, 0xA0B1C2D200ULL);
    TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
  }
  {
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0xA0B1C2D100ULL, 0xA0B1C2D100ULL);
    TEST_EQUAL(values, vector<uint32_t>(), ());
  }
  {
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0xA0B1000000ULL, 0xA0B1B20000ULL);
    TEST_EQUAL(values, vector<uint32_t>(), ());
  }
}

UNIT_TEST(IntervalIndex_Empty)
{
  vector<CellIdFeaturePairForTest> data;
  vector<char> serialIndex;
  MemWriter<vector<char> > writer(serialIndex);
  BuildIntervalIndex(data.begin(), data.end(), writer, 40);
  MemReader reader(&serialIndex[0], serialIndex.size());
  IntervalIndex<MemReader> index(reader);
  {
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0ULL, 0xFFFFFFFFFFULL);
    TEST_EQUAL(values, vector<uint32_t>(), ());
  }
}

UNIT_TEST(IntervalIndex_Simple2)
{
  vector<CellIdFeaturePairForTest> data;
  data.push_back(CellIdFeaturePairForTest(0xA0B1C2D200ULL, 0));
  data.push_back(CellIdFeaturePairForTest(0xA0B1C2D200ULL, 1));
  data.push_back(CellIdFeaturePairForTest(0xA0B1C2D200ULL, 3));
  data.push_back(CellIdFeaturePairForTest(0xA0B2C2D200ULL, 2));
  vector<char> serialIndex;
  MemWriter<vector<char> > writer(serialIndex);
  BuildIntervalIndex(data.begin(), data.end(), writer, 40);
  MemReader reader(&serialIndex[0], serialIndex.size());
  IntervalIndex<MemReader> index(reader);
  {
    uint32_t expected [] = {0, 1, 2, 3};
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0, 0xFFFFFFFFFFULL);
    sort(values.begin(), values.end());
    TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
  }
}

UNIT_TEST(IntervalIndex_Simple3)
{
  vector<CellIdFeaturePairForTest> data;
  data.push_back(CellIdFeaturePairForTest(0x0100ULL, 0));
  data.push_back(CellIdFeaturePairForTest(0x0200ULL, 1));
  vector<char> serialIndex;
  MemWriter<vector<char> > writer(serialIndex);
  BuildIntervalIndex(data.begin(), data.end(), writer, 40);
  MemReader reader(&serialIndex[0], serialIndex.size());
  IntervalIndex<MemReader> index(reader);
  {
    uint32_t expected [] = {0, 1};
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0, 0xFFFFULL);
    sort(values.begin(), values.end());
    TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
  }
}

UNIT_TEST(IntervalIndex_Simple4)
{
  vector<CellIdFeaturePairForTest> data;
  data.push_back(CellIdFeaturePairForTest(0x01030400ULL, 0));
  data.push_back(CellIdFeaturePairForTest(0x02030400ULL, 1));
  vector<char> serialIndex;
  MemWriter<vector<char> > writer(serialIndex);
  BuildIntervalIndex(data.begin(), data.end(), writer, 40);
  MemReader reader(&serialIndex[0], serialIndex.size());
  IntervalIndex<MemReader> index(reader);
  {
    uint32_t expected [] = {0, 1};
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0, 0xFFFFFFFFULL);
    sort(values.begin(), values.end());
    TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
  }
}

UNIT_TEST(IntervalIndex_Simple5)
{
  vector<CellIdFeaturePairForTest> data;
  data.push_back(CellIdFeaturePairForTest(0xA0B1C2D200ULL, 0));
  data.push_back(CellIdFeaturePairForTest(0xA0B1C2D200ULL, 1));
  data.push_back(CellIdFeaturePairForTest(0xA0B1C2D200ULL, 3));
  data.push_back(CellIdFeaturePairForTest(0xA0B2C2D200ULL, 2));
  vector<char> serialIndex;
  MemWriter<vector<char> > writer(serialIndex);
  BuildIntervalIndex(data.begin(), data.end(), writer, 40);
  MemReader reader(&serialIndex[0], serialIndex.size());
  IntervalIndex<MemReader> index(reader);
  {
    uint32_t expected [] = {0, 1, 2, 3};
    vector<uint32_t> values;
    index.ForEach(MakeBackInsertFunctor(values), 0, 0xFFFFFFFFFFULL);
    sort(values.begin(), values.end());
    TEST_EQUAL(values, vector<uint32_t>(expected, expected + ARRAY_SIZE(expected)), ());
  }
}


text:
'use strict';

const events = require('./events.json');

module.exports = payload => {

	let eventNotificationType = payload['Notification Type (Raw)'];
	if (Buffer.isBuffer(eventNotificationType) && eventNotificationType.length) { eventNotificationType = eventNotificationType[0].toString(); }

	let eventCode = payload['Event (Raw)'];
	if (Buffer.isBuffer(eventCode) && eventCode.length) { eventCode = eventCode[0].toString(); }

	if (events[eventNotificationType]
	 && events[eventNotificationType][eventCode]) {

	 	let name = null;
		if (events[eventNotificationType][eventCode].name) {
			name = events[eventNotificationType][eventCode].name;
		} else if (events[eventNotificationType][eventCode].push) {
			name = events[eventNotificationType][eventCode].push;
		} else if (events[eventNotificationType][eventCode].pull) {
			name = events[eventNotificationType][eventCode].pull;
		}

		payload['Event (Parsed 2)'] = name;
	}

	return payload;

};


text:
package org.cloudbyexample.dc.service.si.application;

import static org.cloudbyexample.dc.service.si.application.VelocityTemplateConstants.DOCKER_DB_POSTGRES_TEMPLATE;
import static org.cloudbyexample.dc.service.si.application.VelocityTemplateConstants.DOCKER_IMAGE_TEMPLATE;
import static org.cloudbyexample.dc.service.si.application.VelocityTemplateConstants.DOCKER_WEBAPP_DIR;
import static org.cloudbyexample.dc.service.si.application.VelocityTemplateConstants.DOCKER_WEBAPP_TEMPLATE;
import static org.cloudbyexample.dc.service.si.application.VelocityTemplateConstants.DOCKER_WEB_TEMPLATE;
import static org.cloudbyexample.dc.service.si.application.VelocityTemplateConstants.TEMPLATE_KEY;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.cloudbyexample.dc.schema.beans.application.Application;
import org.cloudbyexample.dc.schema.beans.application.DbTemplate;
import org.cloudbyexample.dc.schema.beans.application.File;
import org.cloudbyexample.dc.schema.beans.application.FileCopy;
import org.cloudbyexample.dc.schema.beans.application.ImageTemplate;
import org.cloudbyexample.dc.schema.beans.application.WebTemplate;
import org.cloudbyexample.dc.schema.beans.application.WebappTemplate;
import org.cloudbyexample.dc.schema.beans.docker.image.DockerImageDir;
import org.cloudbyexample.dc.schema.beans.docker.image.DockerImageRequest;
import org.cloudbyexample.dc.schema.beans.docker.image.ImageCommandType;
import org.cloudbyexample.dc.service.docker.DockerImageService;
import org.cloudbyexample.dc.service.si.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;

/**
 * Image template processor.
 *
 * @author David Winterfeldt
 */
public class ImageTemplateProcessor {

    final Logger logger = LoggerFactory.getLogger(getClass());

    private final DockerImageService service;
    private final Template template;

    @Autowired
    public ImageTemplateProcessor(DockerImageService service, Template template) {
        this.service = service;
        this.template = template;
    }

    public ImageTemplate process(ImageTemplate imageTemplate,
            @Header(ApplicationFlow.APPLICATION) Application application) {
        logger.info("Processing image template '{}'.  {}", imageTemplate.getName(), imageTemplate.getClass());

        DockerImageRequest request = null;

        if (imageTemplate instanceof DbTemplate) {
            DbTemplate dbTemplate = (DbTemplate) imageTemplate;

            Map<String, Object> vars = new HashMap<String, Object>();
            vars.put(TEMPLATE_KEY, imageTemplate);

            // FIXME: extract all velocity related processing behind interface
            String dockerfile = template.process(DOCKER_DB_POSTGRES_TEMPLATE, vars);

            logger.info("Dockerfile: \n{}", dockerfile);

            List<File> files = new ArrayList<>();

            // sql files
            for (FileCopy fileCopy : dbTemplate.getSqlFiles()) {
                files.add(new File().withUrl(fileCopy.getUrl()));
            }

            // files
            for (FileCopy fileCopy : imageTemplate.getFileCopys()) {
                files.add(new File().withUrl(fileCopy.getUrl()));
            }

            request = new DockerImageRequest()
                .withCommand(ImageCommandType.BUILD)
                .withRequest(new DockerImageDir()
                    .withUuid(imageTemplate.getUuid())
                    .withRepoTags(imageTemplate.getTag())
                    .withDockerfile(dockerfile)
                    .withFiles(files));
        } else if (imageTemplate instanceof WebappTemplate) {
            WebappTemplate webappTemplate = (WebappTemplate) imageTemplate;

            // add war file
            FileCopy war = webappTemplate.getWar();
            String context = StringUtils.split(war.getName(), ".")[0];

            imageTemplate.withFileCopys(
                    war.withDestination(DOCKER_WEBAPP_DIR + "/" + context));

            Map<String, Object> vars = new HashMap<String, Object>();
            vars.put(TEMPLATE_KEY, imageTemplate);

            // FIXME: extract all velocity related processing behind interface
            String dockerfile = template.process(DOCKER_WEBAPP_TEMPLATE, vars);

            logger.info("Dockerfile: \n{}", dockerfile);

            List<File> files = new ArrayList<>();

            for (FileCopy fileCopy : imageTemplate.getFileCopys()) {
                files.add(new File().withUrl(fileCopy.getUrl()));
            }

            request = new DockerImageRequest()
                .withCommand(ImageCommandType.BUILD)
                .withRequest(new DockerImageDir()
                    .withUuid(imageTemplate.getUuid())
                    .withRepoTags(imageTemplate.getTag())
                    .withDockerfile(dockerfile)
                    .withFiles(files));
        } else if (imageTemplate instanceof WebTemplate) {
            Map<String, Object> vars = new HashMap<String, Object>();
            vars.put(TEMPLATE_KEY, imageTemplate);

            // FIXME: extract all velocity related processing behind interface
            String dockerfile = template.process(DOCKER_WEB_TEMPLATE, vars);

            logger.info("Dockerfile: \n{}", dockerfile);

            List<File> files = new ArrayList<>();
            for (FileCopy fileCopy : imageTemplate.getFileCopys()) {
                files.add(new File().withUrl(fileCopy.getUrl()));
            }

            request = new DockerImageRequest()
                .withCommand(ImageCommandType.BUILD)
                .withRequest(new DockerImageDir()
                    .withUuid(imageTemplate.getUuid())
                    .withRepoTags(imageTemplate.getTag())
                    .withDockerfile(dockerfile)
                    .withFiles(files));
        } else {
            if (!imageTemplate.getFileCopys().isEmpty()) {
                Map<String, Object> vars = new HashMap<String, Object>();
                vars.put(TEMPLATE_KEY, imageTemplate);

                // FIXME: extract all velocity related processing behind interface
                String dockerfile = template.process(DOCKER_IMAGE_TEMPLATE, vars);

                logger.info("Dockerfile: \n{}", dockerfile);

                List<File> files = new ArrayList<>();
                for (FileCopy fileCopy : imageTemplate.getFileCopys()) {
                    files.add(new File().withUrl(fileCopy.getUrl()));
                }

                request = new DockerImageRequest()
                    .withCommand(ImageCommandType.BUILD)
                    .withRequest(new DockerImageDir()
                        .withUuid(imageTemplate.getUuid())
                        .withRepoTags(imageTemplate.getTag())
                        .withDockerfile(dockerfile)
                        .withFiles(files));
            }
        }

        // image template that represents an image doesn't need any processing
        if (request != null) {
            service.build(request);

            logger.info("Called build for image with tag '{}'.", imageTemplate.getTag());
        }

        return imageTemplate;
    }

}


text:
namespace Apollo {

class Texture2D : public Texture {
public:
    using Texture::Texture;
    ~Texture2D();

    void active();
    void bind();
    void unbind();
    void activeBind();

    static Texture2D *Create(const TextureParameter &parameter);
};
}  // namespace Apollo

#endif  // APOLLO_TEXTURE2D_H_


text:
# The MIT License (MIT)
# Copyright (c) 2018 Massachusetts Institute of Technology
#
# Author: Guillaume Rongier
# This software has been created in projects supported by the US National
# Science Foundation and NASA (PI: Pankratius)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

# 3rd party imports
import numpy as np
from xml.dom import minidom
from six.moves.urllib.request import urlopen
from osgeo import gdal

# Standard library imports
from collections import OrderedDict
import sys
import re

def query_yes_no(question, default = "yes"):
    '''
    Ask a yes/no question via raw_input() and return the answer
    Written by Trent Mick under the MIT license, see:
    https://code.activestate.com/recipes/577058-query-yesno/

    @param question: A string that is presented to the user
    @param default: The presumed answer if the user just hits <Enter>.
                    It must be "yes" (the default), "no" or None (meaning
                    an answer is required of the user)

    @return The "answer", i.e., either "yes" or "no"
    '''

    valid = {"yes":"yes",   "y":"yes",  "ye":"yes",
             "no":"no",     "n":"no"}
    if default == None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while 1:
        sys.stdout.write(question + prompt)
        choice = input().lower()
        if default is not None and choice == '':
            return default
        elif choice in valid.keys():
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "\
                             "(or 'y' or 'n').\n")

def get_query_url(target, mission, instrument, product_type,
                  western_lon, eastern_lon, min_lat, max_lat,
                  min_ob_time, max_ob_time, product_id,
                  query_type, output, results,
                  number_product_limit, result_offset_number):
    '''
    Build the query URL using ODE REST interface
    Adapted from the Orbital Data Explorer (ODE) REST Interface Manual

    @param target: Aimed planetary body, i.e., Mars, Mercury, Moon, Phobos, or Venus
    @param mission: Aimed mission, e.g., MGS or MRO
    @param instrument: Aimed instrument from the mission, e.g., HIRISE or CRISM
    @param product_type: Type of product to look for, e.g., DTM or RDRV11
    @param western_lon: Western longitude to look for the data, from 0 to 360
    @param eastern_lon: Eastern longitude to look for the data, from 0 to 360
    @param min_lat: Minimal latitude to look for the data, from -90 to 90
    @param max_lat: Maximal latitude to look for the data, from -90 to 90
    @param min_ob_time: Minimal observation time in (even partial) UTC format, e.g., '2017-03-01'
    @param max_ob_time: Maximal observation time in (even partial) UTC format, e.g., '2017-03-01'
    @param product_id: PDS Product Id to look for, with wildcards (*) allowed
    @param query_type: File type to look for, i.e., Product, Browse, Derived, or Referenced
    @param output: Return format for product queries or error messages, i.e, XML or JSON
    @param results: Type of files to look for, i.e., c: count of products; o: ODE Product ID;
                    p: PDS product identifies; m: product metadata; f: product files; b: browse image;
                    t: thumbnail image; l: complete PDS label; x: single product footprint
    @param number_product_limit: Maximal number of products to return (100 at most)
    @param result_offset_number: Offset the return products, to go beyond the limit of 100 returned products

    @return Query URL
    '''

    ODE_REST_base_url = "http://oderest.rsl.wustl.edu/live2/?"

    target = 'target=' + target
    mission = '&ihid=' + mission
    instrument = '&iid=' + instrument
    product_type = '&pt=' + product_type
    if western_lon is not None:
        western_lon = '&westernlon=' + str(western_lon)
    else:
        western_lon = ''
    if eastern_lon is not None:
        eastern_lon = '&easternlon=' + str(eastern_lon)
    else:
        eastern_lon = ''
    if min_lat is not None:
        min_lat = '&minlat=' + str(min_lat)
    else:
        min_lat = ''
    if max_lat is not None:
        max_lat = '&maxlat=' + str(max_lat)
    else:
        max_lat = ''
    if min_ob_time != '':
        min_ob_time = '&mincreationtime=' + min_ob_time
    if max_ob_time != '':
        max_ob_time = '&maxcreationtime=' + max_ob_time
    if product_id != '':
        product_id = '&productid=' + product_id

    if query_type != '':
        query_type = '&query=' + query_type
    if results != '':
        results = '&results=' + results
    if output != '':
        output = '&output=' + output
    if number_product_limit != '':
        number_product_limit = '&limit=' + str(number_product_limit)
    if result_offset_number != '':
        result_offset_number = '&offset=' + str(result_offset_number)

    # Concatenate the REST request
    return ODE_REST_base_url + target + mission + instrument + product_type \
           + western_lon + eastern_lon + min_lat + max_lat + min_ob_time \
           + max_ob_time + query_type + results + output + number_product_limit \
           + result_offset_number + product_id

def get_files_urls(query_url, file_name = '*', print_info = False):
    '''
    Retrieve the files' URLs based on a query from ODE REST interface
    Adapted from the Orbital Data Explorer (ODE) REST Interface Manual

    @param query_url: URL resulting from the query of ODE
    @param file_name: File name to look for, with wildcards (*) allowed
    @param print_info: Print the files that will be downloaded

    @return List of URLs
    '''

    url = urlopen(query_url)
    query_results = url.read()
    xml_results = minidom.parseString(query_results)
    url.close()

    error = xml_results.getElementsByTagName('Error')
    if len(error) > 0:
        print('\nError:', error[0].firstChild.data)
        return None

    limit_file_types = 'Product'
    file_name = file_name.replace('*', '.')

    products = xml_results.getElementsByTagName('Product')
    file_urls = OrderedDict()
    for product in products:
        product_files = product.getElementsByTagName('Product_file')
        product_id = product.getElementsByTagName('pdsid')[0]
        if print_info == True:
            print('\nProduct ID:', product_id.firstChild.data)
        for product_file in product_files:
            file_type = product_file.getElementsByTagName('Type')[0]
            file_url = product_file.getElementsByTagName('URL')[0]
            file_description = product_file.getElementsByTagName('Description')[0]
            local_filename = file_url.firstChild.data.split('/')[-1]
            local_file_extension = local_filename.split('.')[-1]
            if re.search(file_name, local_filename) is not None:
                # Restriction on the file type to download
                if len(limit_file_types) > 0:
                    # If match, get the URL
                    if file_type.firstChild.data == limit_file_types:
                        file_urls[file_url.firstChild.data] = (product_id.firstChild.data,
                                                               file_description.firstChild.data)
                        if print_info == True:
                            print('File name:', file_url.firstChild.data.split('/')[-1])
                            print('Description:', file_description.firstChild.data)
                # No restriction on the file type to download
                else:
                    file_urls[file_url.firstChild.data] = (product_id.firstChild.data,
                                                           file_description.firstChild.data)
                    if print_info == True:
                        print('File name:', file_url.firstChild.data.split('/')[-1])
                        print('Description:', file_description.firstChild.data)

    return file_urls

def query_files_urls(target, mission, instrument, product_type,
                     western_lon, eastern_lon, min_lat, max_lat,
                     min_ob_time, max_ob_time, product_id, file_name,
                     number_product_limit, result_offset_number):
    '''
    Retrieve the URL locations based on a query using ODE REST interface

    @param target: Aimed planetary body, i.e., Mars, Mercury, Moon, Phobos, or Venus
    @param mission: Aimed mission, e.g., MGS or MRO
    @param instrument: Aimed instrument from the mission, e.g., HIRISE or CRISM
    @param product_type: Type of product to look for, e.g., DTM or RDRV11
    @param western_lon: Western longitude to look for the data, from 0 to 360
    @param eastern_lon: Eastern longitude to look for the data, from 0 to 360
    @param min_lat: Minimal latitude to look for the data, from -90 to 90
    @param max_lat: Maximal latitude to look for the data, from -90 to 90
    @param min_ob_time: Minimal observation time in (even partial) UTC format, e.g., '2017-03-01'
    @param max_ob_time: Maximal observation time in (even partial) UTC format, e.g., '2017-03-01'
    @param product_id: PDS Product Id to look for, with wildcards (*) allowed
    @param file_name: File name to look for, with wildcards (*) allowed
    @param number_product_limit: Maximal number of products to return (100 at most)
    @param result_offset_number: Offset the return products, to go beyond the limit of 100 returned products

    @return List of URL locations
    '''

    # Returns a list of products with selected product metadata that meet the query parameters
    query_type = 'product'
    # Controls the return format for product queries or error messages
    output = 'XML'
    # For each product found return the product files and IDS
    results = 'fp'

    query_url = get_query_url(target, mission, instrument, product_type,
                              western_lon, eastern_lon, min_lat, max_lat,
                              min_ob_time, max_ob_time, product_id,
                              query_type, output, results,
                              number_product_limit, result_offset_number)

    print('Query URL:', query_url)
    print('\nFiles that will be downloaded (if not previously downloaded):')
    file_urls = get_files_urls(query_url, file_name, print_info = True)
    if file_urls is None:
        return OrderedDict()
    elif len(file_urls) > 0:
        should_continue = query_yes_no('\nDo you want to proceed?')
        if should_continue == "no":
            return OrderedDict()
    else:
        print('\nNo file found')

    return file_urls

def correct_CRISM_label(label_file_location):
    '''
    Correct CRISM label file and allow GDAL to read it properly.
    Necessary for Targeted Reduced Data Record (TRDR) data
    Adapted from https://github.com/jlaura/crism/blob/master/csas.py

    @param label_file_location: Local address of the current label

    @return Local address of the new label
    '''

    new_label_file_location = label_file_location
    if '_fixed' not in new_label_file_location:
        new_label_file_location = '.'.join(label_file_location.split('.')[:-1]) \
                                  + '_fixed.' + label_file_location.split('.')[-1]
    new_label_file = open(new_label_file_location, 'w')

    for line in open(label_file_location, 'r'):
        if "OBJECT          = FILE" in line:
            line = "/* OBJECT = FILE */\n"
        if "LINES" in line:
            lines = int(line.split("=")[1])
        if "LINE_SAMPLES" in line:
            samples = int(line.split("=")[1])
        new_label_file.write(line)

    new_label_file.close()

    return new_label_file_location

def correct_file_name_case_in_label(label_file_location, other_file_locations):
    '''
    Correct a label file if the case of the related data file(s) is incorrect
    and GDAL cannot read it properly

    @param label_file_location: Local address of the current label
    @param other_file_locations: Other files that were downloaded with the label file

    @return Local address of the new label
    '''

    label_file_name = '_'.join('.'.join(label_file_location.split('/')[-1].split('.')[:-1]).split('_')[:-1])
    insensitive_lalels = []
    for file_location in other_file_locations:
        file_name = '.'.join(file_location.split('/')[-1].split('.')[:-1])
        if (file_location != label_file_location
            and file_name == label_file_name):
                insensitive_lalel = re.compile(re.escape(file_location.split('/')[-1]),
                                               re.IGNORECASE)
                insensitive_lalels.append((insensitive_lalel,
                                           file_location.split('/')[-1]))

    with open(label_file_location, 'r') as file:
        label_file = file.read()

    for insensitive_lalel, sensitive_lalel in insensitive_lalels:
        label_file = insensitive_lalel.sub(sensitive_lalel, label_file)

    new_label_file_location = label_file_location
    if '_fixed' not in new_label_file_location:
        new_label_file_location = '.'.join(label_file_location.split('.')[:-1]) \
                                  + '_fixed.' + label_file_location.split('.')[-1]
    with open(new_label_file_location, 'w') as file:
        file.write(label_file)

    return new_label_file_location

def correct_label_file(label_file_location, other_file_locations = []):
    '''
    Correct a label file if GDAL cannot open the corresponding data file

    @param label_file_location: Local address of the current label
    @param other_file_locations: Other files that were downloaded with the label file

    @return Local address of the new label
    '''

    # Correction not limited to CRISM data, in case other data had similar issues
    new_label_file_location = correct_CRISM_label(label_file_location)
    return correct_file_name_case_in_label(new_label_file_location,
                                           other_file_locations)

def get_raster_array(gdal_raster, remove_ndv = True):
    '''
    Get a NumPy array from a raster opened with GDAL

    @param gdal_raster: A raster opened with GDAL
    @param remove_ndv: Replace the no-data value as mentionned in the label by np.nan

    @return The array
    '''
    assert gdal_raster is not None, 'No raster available'

    number_of_bands = gdal_raster.RasterCount
    raster_array = gdal_raster.ReadAsArray().astype(np.float)
    for i_band in range(number_of_bands):
        raster_band = gdal_raster.GetRasterBand(i_band + 1)
        no_data_value = raster_band.GetNoDataValue()
        if no_data_value is not None and remove_ndv == True:
            if number_of_bands > 1:
                raster_array[i_band, :, :][raster_array[i_band, :, :] == no_data_value] = np.nan
            else:
                raster_array[raster_array == no_data_value] = np.nan
        scale = raster_band.GetScale()
        if scale is None:
            scale = 1.
        offset = raster_band.GetOffset()
        if offset is None:
            offset = 0.
        if number_of_bands > 1:
            raster_array[i_band, :, :] = raster_array[i_band, :, :]*scale + offset
        else:
            raster_array = raster_array*scale + offset

    return raster_array

def get_raster_extent(gdal_raster):
    '''
    Get the extent of a raster opened with GDAL

    @param gdal_raster: A raster opened with GDAL

    @return The raster extent
    '''
    assert gdal_raster is not None, 'No raster available'

    raster_x_size = gdal_raster.RasterXSize
    raster_y_size = gdal_raster.RasterYSize
    geotransform = gdal_raster.GetGeoTransform()
    xmin = geotransform[0]
    ymax = geotransform[3]
    xmax = xmin + geotransform[1]*raster_x_size
    ymin = ymax + geotransform[5]*raster_y_size

    return (xmin, xmax, ymin, ymax)


text:
namespace ark {
namespace plugin {
namespace dear_imgui {

WidgetWithVisibility::WidgetWithVisibility(sp<Widget> delegate, sp<Boolean> visible)
    : Delegate(std::move(delegate)), _visible(std::move(visible))
{
}

void WidgetWithVisibility::render()
{
    if(_visible->val())
        _delegate->render();
}

}
}
}


text:
'use strict';
const decamelize = require('decamelize');

const USER_AGENT = (
'Android-Finsky/6.8.44.F-all%20%5B0%5D%203087104 ' +
  '(api=3,versionCode=80684400,sdk=23,device=bullhead,' +
  'hardware=bullhead,product=bullhead,platformVersionRelease=6.0.1,' +
  'model=Nexus%205X,buildId=MHC19Q,isWideScreen=0)'
);

const DOWNLOAD_MANAGER_USER_AGENT = (
'AndroidDownloadManager/6.0.1 (Linux; U; Android 6.0.1; Nexus 5X Build/MHC19Q)'
);

const defaults = {
  username: process.env.GOOGLE_LOGIN,
  password: process.env.GOOGLE_PASSWORD,
  androidId: process.env.ANDROID_ID,
  authToken: undefined,
  countryCode: 'us',
  language: 'en_US',
  useCache: false,
  debug: process.env.DEBUG,
  apiUserAgent: USER_AGENT,
  downloadUserAgent: DOWNLOAD_MANAGER_USER_AGENT,
  sdkVersion: 23
}

const alias = Object.keys(defaults).reduce((a, k) => {
  a[decamelize(k, '-')] = k;
  return a;
}, {})

module.exports = require('rc')(
  'gpcli',
  defaults,
  require('minimist')(process.argv, {
    alias: alias
  })
);

if (!module.parent) {
  console.log(module.exports);
}


text:
package org.apache.jackrabbit.oak.plugins.document.impl;

import org.apache.jackrabbit.oak.plugins.document.DocumentMK;

/**
 * A class that can perform simple operations.
 */
public class SimpleNodeScenario {

    private final DocumentMK mk;

    public SimpleNodeScenario(DocumentMK mk) {
        this.mk = mk;
    }

    public String create() throws Exception {
        return mk.commit("/",
                "+\"a\" : { \"int\" : 1 , \"b\" : { \"string\" : \"foo\" } , \"c\" : { \"bool\" : true } }",
                null,
                "Simple node scenario with nodes /, /a, /a/b, /a/c");
    }

    public String addChildrenToA(int count) throws Exception {
        String revisionId = null;
        for (int i = 1; i <= count; i++) {
            revisionId = mk.commit("/a", "+\"child" + i + "\" : {}", null, "Add child" + i);
        }
        return revisionId;
    }

    public String deleteA() throws Exception {
        return mk.commit("/", "-\"a\"", null, "Commit with deleted /a");
    }

    public String deleteB() throws Exception {
        return mk.commit("/a", "-\"b\"", null, "Commit with deleted /a/b");
    }

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Bot. 28:268. 1890

#### Original name
null

### Remarks
null


text:
<?php
$this->makeDetailBreadcrumbs('Error Report');
?>

Error Report

<?php $this->widget('zii.widgets.grid.CGridView', array(
		'dataProvider'=>$dataProvider,
		'columns'=>array(
			array(
				'name' => 'messageText',
				'value' => '$data["messageText"] == "" ? "<no error>" : $data["messageText"]'
			),
			'count',
		),
)); ?>


text:
package de.vsis.evka01.shared.materials;

public class RbData {

	private int _temp;
	private int _battery;

	/**
	 * first temp, then battery charge level
	 * @param temp
	 * @param battery
	 */
	public RbData(int temp, int battery){
		_temp = temp;
		_battery = battery;
	}

	public int getBattery(){
		return _battery;
	}

	public int getTemp(){
		return _temp;
	}
}


text:
#include <stdio.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_log.h"

#include "driver/touch_pad.h"
#include "soc/rtc_periph.h"
#include "soc/sens_periph.h"

static const char *TAG = "Touch pad";

#define TOUCH_THRESH_NO_USE   (0)
#define TOUCH_THRESH_PERCENT  (80)
#define TOUCHPAD_FILTER_TOUCH_PERIOD (10)

static bool s_pad_activated[TOUCH_PAD_MAX];
static uint32_t s_pad_init_val[TOUCH_PAD_MAX];

/*
  Read values sensed at all available touch pads.
  Use 2 / 3 of read value as the threshold
  to trigger interrupt when the pad is touched.
  Note: this routine demonstrates a simple way
  to configure activation threshold for the touch pads.
  Do not touch any pads when this routine
  is running (on application start).
 */
static void tp_example_set_thresholds(void)
{
    uint16_t touch_value;
    for (int i = 0; i < TOUCH_PAD_MAX; i++) {
        //read filtered value
        touch_pad_read_filtered(i, &touch_value);
        s_pad_init_val[i] = touch_value;
        ESP_LOGI(TAG, "test init: touch pad [%d] val is %d", i, touch_value);
        //set interrupt threshold.
        ESP_ERROR_CHECK(touch_pad_set_thresh(i, touch_value * 2 / 3));

    }
}

/*
  Check if any of touch pads has been activated
  by reading a table updated by rtc_intr()
  If so, then print it out on a serial monitor.
  Clear related entry in the table afterwards

  In interrupt mode, the table is updated in touch ISR.

  In filter mode, we will compare the current filtered value with the initial one.
  If the current filtered value is less than 80% of the initial value, we can
  regard it as a 'touched' event.
  When calling touch_pad_init, a timer will be started to run the filter.
  This mode is designed for the situation that the pad is covered
  by a 2-or-3-mm-thick medium, usually glass or plastic.
  The difference caused by a 'touch' action could be very small, but we can still use
  filter mode to detect a 'touch' event.
 */
static void tp_example_read_task(void *pvParameter)
{
    static int show_message;
    int change_mode = 0;
    int filter_mode = 0;
    while (1) {
        if (filter_mode == 0) {
            //interrupt mode, enable touch interrupt
            touch_pad_intr_enable();
            for (int i = 0; i < TOUCH_PAD_MAX; i++) {
                if (s_pad_activated[i] == true) {
                    ESP_LOGI(TAG, "T%d activated!", i);
                    // Wait a while for the pad being released
                    vTaskDelay(200 / portTICK_PERIOD_MS);
                    // Clear information on pad activation
                    s_pad_activated[i] = false;
                    // Reset the counter triggering a message
                    // that application is running
                    show_message = 1;
                }
            }
        } else {
            //filter mode, disable touch interrupt
            touch_pad_intr_disable();
            touch_pad_clear_status();
            for (int i = 0; i < TOUCH_PAD_MAX; i++) {
                uint16_t value = 0;
                touch_pad_read_filtered(i, &value);
                if (value < s_pad_init_val[i] * TOUCH_THRESH_PERCENT / 100) {
                    ESP_LOGI(TAG, "T%d activated!", i);
                    ESP_LOGI(TAG, "value: %"PRIu16"; init val: %"PRIu32, value, s_pad_init_val[i]);
                    vTaskDelay(200 / portTICK_PERIOD_MS);
                    // Reset the counter to stop changing mode.
                    change_mode = 1;
                    show_message = 1;
                }
            }
        }

        vTaskDelay(10 / portTICK_PERIOD_MS);

        // If no pad is touched, every couple of seconds, show a message
        // that application is running
        if (show_message++ % 500 == 0) {
            ESP_LOGI(TAG, "Waiting for any pad being touched...");
        }
        // Change mode if no pad is touched for a long time.
        // We can compare the two different mode.
        if (change_mode++ % 2000 == 0) {
            filter_mode = !filter_mode;
            ESP_LOGW(TAG, "Change mode...%s", filter_mode == 0 ? "interrupt mode" : "filter mode");
        }
    }
}

/*
  Handle an interrupt triggered when a pad is touched.
  Recognize what pad has been touched and save it in a table.
 */
static void tp_example_rtc_intr(void *arg)
{
    uint32_t pad_intr = touch_pad_get_status();
    //clear interrupt
    touch_pad_clear_status();
    for (int i = 0; i < TOUCH_PAD_MAX; i++) {
        if ((pad_intr >> i) & 0x01) {
            s_pad_activated[i] = true;
        }
    }
}

/*
 * Before reading touch pad, we need to initialize the RTC IO.
 */
static void tp_example_touch_pad_init(void)
{
    for (int i = 0; i < TOUCH_PAD_MAX; i++) {
        //init RTC IO and mode for touch pad.
        touch_pad_config(i, TOUCH_THRESH_NO_USE);
    }
}

void app_main(void)
{
    // Initialize touch pad peripheral, it will start a timer to run a filter
    ESP_LOGI(TAG, "Initializing touch pad");
    ESP_ERROR_CHECK(touch_pad_init());
    // If use interrupt trigger mode, should set touch sensor FSM mode at 'TOUCH_FSM_MODE_TIMER'.
    touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER);
    // Set reference voltage for charging/discharging
    // For most usage scenarios, we recommend using the following combination:
    // the high reference valtage will be 2.7V - 1V = 1.7V, The low reference voltage will be 0.5V.
    touch_pad_set_voltage(TOUCH_HVOLT_2V7, TOUCH_LVOLT_0V5, TOUCH_HVOLT_ATTEN_1V);
    // Init touch pad IO
    tp_example_touch_pad_init();
    // Initialize and start a software filter to detect slight change of capacitance.
    touch_pad_filter_start(TOUCHPAD_FILTER_TOUCH_PERIOD);
    // Set thresh hold
    tp_example_set_thresholds();
    // Register touch interrupt ISR
    touch_pad_isr_register(tp_example_rtc_intr, NULL);
    // Start a task to show what pads have been touched
    xTaskCreate(&tp_example_read_task, "touch_pad_read_task", 4096, NULL, 5, NULL);
}


text:
// flowlint ambiguous-object-type:error

'use strict';
import type {Direction, OperationDescriptor, Variables} from 'relay-runtime';
import type {Disposable} from 'relay-runtime/util/RelayRuntimeTypes';

const useBlockingPaginationFragmentOriginal = require('../useBlockingPaginationFragment');
const invariant = require('invariant');
const React = require('react');
const ReactRelayContext = require('react-relay/ReactRelayContext');
const TestRenderer = require('react-test-renderer');
const {
  ConnectionHandler,
  FRAGMENT_OWNER_KEY,
  FRAGMENTS_KEY,
  ID_KEY,
  createOperationDescriptor,
  getRequest,
  graphql,
} = require('relay-runtime');
const {createMockEnvironment} = require('relay-test-utils');
const Scheduler = require('scheduler');

const {useEffect, useTransition, useMemo, useState} = React;

describe('useBlockingPaginationFragment with useTransition', () => {
  if (typeof useTransition !== 'function') {
    it('empty test to prevent Jest from failing', () => {
      // This suite is only useful with experimental React build
    });
  } else {
    let environment;
    let initialUser;
    let gqlQuery;
    let gqlQueryWithoutID;
    let gqlPaginationQuery;
    let gqlFragment;
    let query;
    let queryWithoutID;
    let paginationQuery;
    let variables;
    let variablesWithoutID;
    let setOwner;
    let renderFragment;
    let loadNext;
    let refetch;
    let forceUpdate;
    let release;
    let Renderer;

    class ErrorBoundary extends React.Component<any, any> {
      state = {error: null};
      componentDidCatch(error) {
        this.setState({error});
      }
      render() {
        const {children, fallback} = this.props;
        const {error} = this.state;
        if (error) {
          return React.createElement(fallback, {error});
        }
        return children;
      }
    }

    function useBlockingPaginationFragmentWithSuspenseTransition(
      fragmentNode,
      fragmentRef,
    ) {
      const [isPendingNext, startTransition] = useTransition();
      // $FlowFixMe[incompatible-call]
      const {data, ...result} = useBlockingPaginationFragmentOriginal(
        fragmentNode,
        // $FlowFixMe[prop-missing]
        // $FlowFixMe[incompatible-call]
        fragmentRef,
      );
      loadNext = (...args) => {
        let disposable: Disposable | {|dispose: () => void|} = {
          dispose: () => {},
        };
        startTransition(() => {
          disposable = result.loadNext(...args);
        });
        return disposable;
      };
      refetch = result.refetch;
      // $FlowFixMe[prop-missing]
      result.isPendingNext = isPendingNext;

      useEffect(() => {
        Scheduler.unstable_yieldValue({data, ...result});
      });

      return {data, ...result};
    }

    function assertYieldsWereCleared() {
      const actualYields = Scheduler.unstable_clearYields();
      if (actualYields.length !== 0) {
        throw new Error(
          'Log of yielded values is not empty. ' +
            'Call expect(Scheduler).toHaveYielded(...) first.',
        );
      }
    }

    function assertYield(expected, actual) {
      expect(actual.data).toEqual(expected.data);
      expect(actual.isPendingNext).toEqual(expected.isPendingNext);
      expect(actual.hasNext).toEqual(expected.hasNext);
      expect(actual.hasPrevious).toEqual(expected.hasPrevious);
    }

    function expectFragmentResults(
      expectedYields: $ReadOnlyArray<{|
        data: $FlowFixMe,
        isPendingNext: boolean,
        hasNext: boolean,
        hasPrevious: boolean,
      |}>,
    ) {
      assertYieldsWereCleared();
      Scheduler.unstable_flushNumberOfYields(expectedYields.length);
      const actualYields = Scheduler.unstable_clearYields();
      expect(actualYields.length).toEqual(expectedYields.length);
      expectedYields.forEach((expected, idx) =>
        assertYield(expected, actualYields[idx]),
      );
    }

    function expectRequestIsInFlight(expected) {
      // $FlowFixMe[method-unbinding] added when improving typing for this parameters
      expect(environment.execute).toBeCalledTimes(expected.requestCount);
      expect(
        environment.mock.isLoading(
          gqlPaginationQuery,
          expected.paginationVariables,
          {force: true},
        ),
      ).toEqual(expected.inFlight);
    }

    function expectFragmentIsPendingOnPagination(
      renderer,
      direction: Direction,
      expected: {|
        data: mixed,
        hasNext: boolean,
        hasPrevious: boolean,
        paginationVariables: Variables,
      |},
    ) {
      // Assert fragment sets isPending to true
      expectFragmentResults([
        {
          data: expected.data,
          isPendingNext: direction === 'forward',
          hasNext: expected.hasNext,
          hasPrevious: expected.hasPrevious,
        },
      ]);

      // Assert refetch query was fetched
      expectRequestIsInFlight({...expected, inFlight: true, requestCount: 1});
    }

    function createFragmentRef(id, owner) {
      return {
        [ID_KEY]: id,
        [FRAGMENTS_KEY]: {
          useBlockingPaginationFragmentWithSuspenseTransitionTestNestedUserFragment:
            {},
        },
        [FRAGMENT_OWNER_KEY]: owner.request,
        __isWithinUnmatchedTypeRefinement: false,
      };
    }

    beforeEach(() => {
      // Set up mocks
      jest.resetModules();
      jest.mock('warning');
      jest.mock('scheduler', () => {
        return jest.requireActual('scheduler/unstable_mock');
      });

      // Supress `act` warnings since we are intentionally not
      // using it for most tests here. `act` currently always
      // flushes Suspense fallbacks, and that's not what we want
      // when asserting pending/suspended states,
      const originalLogError = console.error.bind(console);
      jest.spyOn(console, 'error').mockImplementation((message, ...args) => {
        if (typeof message === 'string' && message.includes('act(...)')) {
          return;
        }
        originalLogError(message, ...args);
      });

      // Set up environment and base data
      environment = createMockEnvironment({
        handlerProvider: () => ConnectionHandler,
      });
      release = jest.fn();
      // $FlowFixMe[method-unbinding] added when improving typing for this parameters
      environment.retain.mockImplementation((...args) => {
        return {
          dispose: release,
        };
      });
      graphql`
        fragment useBlockingPaginationFragmentWithSuspenseTransitionTestNestedUserFragment on User {
          username
        }
      `;

      gqlFragment = graphql`
        fragment useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragment on User
        @refetchable(
          queryName: "useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragmentPaginationQuery"
        )
        @argumentDefinitions(
          isViewerFriendLocal: {type: "Boolean", defaultValue: false}
          orderby: {type: "[String]"}
        ) {
          id
          name
          friends(
            after: $after
            first: $first
            before: $before
            last: $last
            orderby: $orderby
            isViewerFriend: $isViewerFriendLocal
          ) @connection(key: "UserFragment_friends") {
            edges {
              node {
                id
                name
                ...useBlockingPaginationFragmentWithSuspenseTransitionTestNestedUserFragment
              }
            }
          }
        }
      `;

      gqlQuery = graphql`
        query useBlockingPaginationFragmentWithSuspenseTransitionTestUserQuery(
          $id: ID!
          $after: ID
          $first: Int
          $before: ID
          $last: Int
          $orderby: [String]
          $isViewerFriend: Boolean
        ) {
          node(id: $id) {
            actor {
              ...useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragment
                @arguments(
                  isViewerFriendLocal: $isViewerFriend
                  orderby: $orderby
                )
            }
          }
        }
      `;

      gqlQueryWithoutID = graphql`
        query useBlockingPaginationFragmentWithSuspenseTransitionTestUserQueryWithoutIDQuery(
          $after: ID
          $first: Int
          $before: ID
          $last: Int
          $orderby: [String]
          $isViewerFriend: Boolean
        ) {
          viewer {
            actor {
              ...useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragment
                @arguments(
                  isViewerFriendLocal: $isViewerFriend
                  orderby: $orderby
                )
            }
          }
        }
      `;

      variablesWithoutID = {
        after: null,
        first: 1,
        before: null,
        last: null,
        isViewerFriend: false,
        orderby: ['name'],
      };
      variables = {
        ...variablesWithoutID,
        id: '<feedbackid>',
      };
      gqlPaginationQuery = require('./__generated__/useBlockingPaginationFragmentWithSuspenseTransitionTestUserFragmentPaginationQuery.graphql');

      query = createOperationDescriptor(gqlQuery, variables);
      queryWithoutID = createOperationDescriptor(
        gqlQueryWithoutID,
        variablesWithoutID,
      );
      paginationQuery = createOperationDescriptor(
        gqlPaginationQuery,
        variables,
      );
      environment.commitPayload(query, {
        node: {
          __typename: 'Feedback',
          id: '<feedbackid>',
          actor: {
            __typename: 'User',
            id: '1',
            name: 'Alice',
            friends: {
              edges: [
                {
                  cursor: 'cursor:1',
                  node: {
                    __typename: 'User',
                    id: 'node:1',
                    name: 'name:node:1',
                    username: 'username:node:1',
                  },
                },
              ],
              pageInfo: {
                endCursor: 'cursor:1',
                hasNextPage: true,
                hasPreviousPage: false,
                startCursor: 'cursor:1',
              },
            },
          },
        },
      });
      environment.commitPayload(queryWithoutID, {
        viewer: {
          actor: {
            __typename: 'User',
            id: '1',
            name: 'Alice',
            friends: {
              edges: [
                {
                  cursor: 'cursor:1',
                  node: {
                    __typename: 'User',
                    id: 'node:1',
                    name: 'name:node:1',
                    username: 'username:node:1',
                  },
                },
              ],
              pageInfo: {
                endCursor: 'cursor:1',
                hasNextPage: true,
                hasPreviousPage: false,
                startCursor: 'cursor:1',
              },
            },
          },
        },
      });

      // Set up renderers
      Renderer = props => null;

      const Container = (props: {
        userRef?: {...},
        owner: $FlowFixMe,
        fragment: $FlowFixMe,
        ...
      }) => {
        // We need a render a component to run a Hook
        const [owner, _setOwner] = useState(props.owner);
        const [, setCount] = useState(0);
        const fragment = props.fragment ?? gqlFragment;
        const artificialUserRef = useMemo(() => {
          const snapshot = environment.lookup(owner.fragment);
          return (snapshot.data: $FlowFixMe)?.node?.actor;
        }, [owner]);
        const userRef = props.hasOwnProperty('userRef')
          ? props.userRef
          : artificialUserRef;

        setOwner = _setOwner;
        forceUpdate = setCount;

        const {data: userData} =
          useBlockingPaginationFragmentWithSuspenseTransition(
            fragment,
            userRef,
          );
        return <Renderer user={userData} />;
      };

      const ContextProvider = ({children}) => {
        // TODO(T39494051) - We set empty variables in relay context to make
        // Flow happy, but useBlockingPaginationFragment does not use them, instead it uses
        // the variables from the fragment owner.
        const relayContext = useMemo(() => ({environment}), []);

        return (
          <ReactRelayContext.Provider value={relayContext}>
            {children}
          </ReactRelayContext.Provider>
        );
      };

      const Fallback = () => {
        useEffect(() => {
          Scheduler.unstable_yieldValue('Fallback');
        });

        return 'Fallback';
      };

      renderFragment = (args?: {
        isConcurrent?: boolean,
        owner?: $FlowFixMe,
        userRef?: $FlowFixMe,
        fragment?: $FlowFixMe,
        ...
      }): $FlowFixMe => {
        const {isConcurrent = true, ...props} = args ?? {};
        return TestRenderer.create(
          <ErrorBoundary fallback={({error}) => `Error: ${error.message}`}>
            <React.Suspense fallback={<Fallback />}>
              <ContextProvider>
                <Container owner={query} {...props} />
              </ContextProvider>
            </React.Suspense>
          </ErrorBoundary>,
          // $FlowFixMe[prop-missing] - error revealed when flow-typing ReactTestRenderer
          {unstable_isConcurrent: isConcurrent},
        );
      };

      initialUser = {
        id: '1',
        name: 'Alice',
        friends: {
          edges: [
            {
              cursor: 'cursor:1',
              node: {
                __typename: 'User',
                id: 'node:1',
                name: 'name:node:1',
                ...createFragmentRef('node:1', query),
              },
            },
          ],
          pageInfo: {
            endCursor: 'cursor:1',
            hasNextPage: true,
            hasPreviousPage: false,
            startCursor: 'cursor:1',
          },
        },
      };
    });

    afterEach(() => {
      environment.mockClear();
      jest.dontMock('scheduler');
    });

    describe('loadNext', () => {
      const direction = 'forward';

      // Sanity check test, should already be tested in useBlockingPagination test
      it('loads and renders next items in connection', () => {
        const callback = jest.fn();
        const renderer = renderFragment();
        expectFragmentResults([
          {
            data: initialUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);

        loadNext(1, {onComplete: callback});

        const paginationVariables = {
          id: '1',
          after: 'cursor:1',
          first: 1,
          before: null,
          last: null,
          isViewerFriendLocal: false,
          orderby: ['name'],
        };
        expectFragmentIsPendingOnPagination(renderer, direction, {
          data: initialUser,
          hasNext: true,
          hasPrevious: false,
          paginationVariables,
        });
        expect(callback).toBeCalledTimes(0);
        expect(renderer.toJSON()).toEqual(null);

        environment.mock.resolve(gqlPaginationQuery, {
          data: {
            node: {
              __typename: 'User',
              id: '1',
              name: 'Alice',
              friends: {
                edges: [
                  {
                    cursor: 'cursor:2',
                    node: {
                      __typename: 'User',
                      id: 'node:2',
                      name: 'name:node:2',
                      username: 'username:node:2',
                    },
                  },
                ],
                pageInfo: {
                  startCursor: 'cursor:2',
                  endCursor: 'cursor:2',
                  hasNextPage: true,
                  hasPreviousPage: true,
                },
              },
            },
          },
        });

        const expectedUser = {
          ...initialUser,
          friends: {
            ...initialUser.friends,
            edges: [
              {
                cursor: 'cursor:1',
                node: {
                  __typename: 'User',
                  id: 'node:1',
                  name: 'name:node:1',
                  ...createFragmentRef('node:1', query),
                },
              },
              {
                cursor: 'cursor:2',
                node: {
                  __typename: 'User',
                  id: 'node:2',
                  name: 'name:node:2',
                  ...createFragmentRef('node:2', query),
                },
              },
            ],
            pageInfo: {
              endCursor: 'cursor:2',
              hasNextPage: true,
              hasPreviousPage: false,
              startCursor: 'cursor:1',
            },
          },
        };
        expectFragmentResults([
          {
            data: expectedUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);
        expect(callback).toBeCalledTimes(1);
      });

      it('renders pending flag correctly if pagination update is interrupted before it commits (unsuspends)', () => {
        const callback = jest.fn();
        const renderer = renderFragment();
        expectFragmentResults([
          {
            data: initialUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);

        loadNext(1, {onComplete: callback});

        const paginationVariables = {
          id: '1',
          after: 'cursor:1',
          first: 1,
          before: null,
          last: null,
          isViewerFriendLocal: false,
          orderby: ['name'],
        };
        expectFragmentIsPendingOnPagination(renderer, direction, {
          data: initialUser,
          hasNext: true,
          hasPrevious: false,
          paginationVariables,
        });
        expect(callback).toBeCalledTimes(0);
        expect(renderer.toJSON()).toEqual(null);

        // Schedule a high-pri update while the component is
        // suspended on pagination
        Scheduler.unstable_runWithPriority(
          Scheduler.unstable_UserBlockingPriority,
          () => {
            forceUpdate(prev => prev + 1);
          },
        );

        // Assert high-pri update is rendered when initial update
        // that suspended hasn't committed
        // Assert that the avoided Suspense fallback isn't rendered
        expect(renderer.toJSON()).toEqual(null);
        expectFragmentResults([
          {
            data: initialUser,
            // Assert that isPending flag is still true
            isPendingNext: true,
            hasNext: true,
            hasPrevious: false,
          },
        ]);

        // Assert list is updated after pagination request completes
        environment.mock.resolve(gqlPaginationQuery, {
          data: {
            node: {
              __typename: 'User',
              id: '1',
              name: 'Alice',
              friends: {
                edges: [
                  {
                    cursor: 'cursor:2',
                    node: {
                      __typename: 'User',
                      id: 'node:2',
                      name: 'name:node:2',
                      username: 'username:node:2',
                    },
                  },
                ],
                pageInfo: {
                  startCursor: 'cursor:2',
                  endCursor: 'cursor:2',
                  hasNextPage: true,
                  hasPreviousPage: true,
                },
              },
            },
          },
        });

        const expectedUser = {
          ...initialUser,
          friends: {
            ...initialUser.friends,
            edges: [
              {
                cursor: 'cursor:1',
                node: {
                  __typename: 'User',
                  id: 'node:1',
                  name: 'name:node:1',
                  ...createFragmentRef('node:1', query),
                },
              },
              {
                cursor: 'cursor:2',
                node: {
                  __typename: 'User',
                  id: 'node:2',
                  name: 'name:node:2',
                  ...createFragmentRef('node:2', query),
                },
              },
            ],
            pageInfo: {
              endCursor: 'cursor:2',
              hasNextPage: true,
              hasPreviousPage: false,
              startCursor: 'cursor:1',
            },
          },
        };

        expectFragmentResults([
          {
            data: expectedUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);
        expect(callback).toBeCalledTimes(1);
      });

      it('loads more correctly when original variables do not include an id', () => {
        const callback = jest.fn();
        const viewer = environment.lookup(queryWithoutID.fragment).data?.viewer;
        const userRef =
          typeof viewer === 'object' && viewer != null ? viewer?.actor : null;
        invariant(userRef != null, 'Expected to have cached test data');

        let expectedUser = {
          ...initialUser,
          friends: {
            ...initialUser.friends,
            edges: [
              {
                cursor: 'cursor:1',
                node: {
                  __typename: 'User',
                  id: 'node:1',
                  name: 'name:node:1',
                  ...createFragmentRef('node:1', queryWithoutID),
                },
              },
            ],
          },
        };

        const renderer = renderFragment({owner: queryWithoutID, userRef});
        expectFragmentResults([
          {
            data: expectedUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);

        loadNext(1, {onComplete: callback});

        const paginationVariables = {
          id: '1',
          after: 'cursor:1',
          first: 1,
          before: null,
          last: null,
          isViewerFriendLocal: false,
          orderby: ['name'],
        };
        expectFragmentIsPendingOnPagination(renderer, direction, {
          data: expectedUser,
          hasNext: true,
          hasPrevious: false,
          paginationVariables,
        });
        expect(callback).toBeCalledTimes(0);
        expect(renderer.toJSON()).toEqual(null);

        environment.mock.resolve(gqlPaginationQuery, {
          data: {
            node: {
              __typename: 'User',
              id: '1',
              name: 'Alice',
              friends: {
                edges: [
                  {
                    cursor: 'cursor:2',
                    node: {
                      __typename: 'User',
                      id: 'node:2',
                      name: 'name:node:2',
                      username: 'username:node:2',
                    },
                  },
                ],
                pageInfo: {
                  startCursor: 'cursor:2',
                  endCursor: 'cursor:2',
                  hasNextPage: true,
                  hasPreviousPage: true,
                },
              },
            },
          },
        });

        expectedUser = {
          ...initialUser,
          friends: {
            ...initialUser.friends,
            edges: [
              {
                cursor: 'cursor:1',
                node: {
                  __typename: 'User',
                  id: 'node:1',
                  name: 'name:node:1',
                  ...createFragmentRef('node:1', queryWithoutID),
                },
              },
              {
                cursor: 'cursor:2',
                node: {
                  __typename: 'User',
                  id: 'node:2',
                  name: 'name:node:2',
                  ...createFragmentRef('node:2', queryWithoutID),
                },
              },
            ],
            pageInfo: {
              endCursor: 'cursor:2',
              hasNextPage: true,
              hasPreviousPage: false,
              startCursor: 'cursor:1',
            },
          },
        };
        expectFragmentResults([
          {
            data: expectedUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);
        expect(callback).toBeCalledTimes(1);
      });

      it('calls callback with error when error occurs during fetch', () => {
        const callback = jest.fn();
        const renderer = renderFragment();
        expectFragmentResults([
          {
            data: initialUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);

        loadNext(1, {onComplete: callback});

        const paginationVariables = {
          id: '1',
          after: 'cursor:1',
          first: 1,
          before: null,
          last: null,
          isViewerFriendLocal: false,
          orderby: ['name'],
        };
        expectFragmentIsPendingOnPagination(renderer, direction, {
          data: initialUser,
          hasNext: true,
          hasPrevious: false,
          paginationVariables,
        });
        expect(callback).toBeCalledTimes(0);
        expect(renderer.toJSON()).toEqual(null);

        const error = new Error('Oops');
        environment.mock.reject(gqlPaginationQuery, error);

        // We pass the error in the callback, but do not throw during render
        // since we want to continue rendering the existing items in the
        // connection
        expect(callback).toBeCalledTimes(1);
        expect(callback).toBeCalledWith(error);
      });

      it('preserves pagination request if re-rendered with same fragment ref', () => {
        const callback = jest.fn();
        const renderer = renderFragment();
        expectFragmentResults([
          {
            data: initialUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);

        loadNext(1, {onComplete: callback});

        const paginationVariables = {
          id: '1',
          after: 'cursor:1',
          first: 1,
          before: null,
          last: null,
          isViewerFriendLocal: false,
          orderby: ['name'],
        };
        expectFragmentIsPendingOnPagination(renderer, direction, {
          data: initialUser,
          hasNext: true,
          hasPrevious: false,
          paginationVariables,
        });
        expect(callback).toBeCalledTimes(0);
        expect(renderer.toJSON()).toEqual(null);

        setOwner({...query});

        // Assert that request is still in flight after re-rendering
        // with new fragment ref that points to the same data.
        expectRequestIsInFlight({
          inFlight: true,
          requestCount: 1,
          gqlPaginationQuery,
          paginationVariables,
        });
        expect(callback).toBeCalledTimes(0);

        environment.mock.resolve(gqlPaginationQuery, {
          data: {
            node: {
              __typename: 'User',
              id: '1',
              name: 'Alice',
              friends: {
                edges: [
                  {
                    cursor: 'cursor:2',
                    node: {
                      __typename: 'User',
                      id: 'node:2',
                      name: 'name:node:2',
                      username: 'username:node:2',
                    },
                  },
                ],
                pageInfo: {
                  startCursor: 'cursor:2',
                  endCursor: 'cursor:2',
                  hasNextPage: true,
                  hasPreviousPage: true,
                },
              },
            },
          },
        });

        const expectedUser = {
          ...initialUser,
          friends: {
            ...initialUser.friends,
            edges: [
              {
                cursor: 'cursor:1',
                node: {
                  __typename: 'User',
                  id: 'node:1',
                  name: 'name:node:1',
                  ...createFragmentRef('node:1', query),
                },
              },
              {
                cursor: 'cursor:2',
                node: {
                  __typename: 'User',
                  id: 'node:2',
                  name: 'name:node:2',
                  ...createFragmentRef('node:2', query),
                },
              },
            ],
            pageInfo: {
              endCursor: 'cursor:2',
              hasNextPage: true,
              hasPreviousPage: false,
              startCursor: 'cursor:1',
            },
          },
        };
        expectFragmentResults([
          {
            data: expectedUser,
            isPendingNext: true,
            hasNext: true,
            hasPrevious: false,
          },
          {
            data: expectedUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);
        expect(callback).toBeCalledTimes(1);
      });
    });

    describe('refetch', () => {
      // The bulk of refetch behavior is covered in useRefetchableFragmentNode-test,
      // so this suite covers the pagination-related test cases.
      function expectRefetchRequestIsInFlight(expected) {
        // $FlowFixMe[method-unbinding] added when improving typing for this parameters
        expect(environment.executeWithSource).toBeCalledTimes(
          expected.requestCount,
        );
        expect(
          environment.mock.isLoading(
            expected.gqlRefetchQuery ?? gqlPaginationQuery,
            expected.refetchVariables,
            {force: true},
          ),
        ).toEqual(expected.inFlight);
      }

      function expectFragmentSuspendedOnRefetch(
        renderer,
        expected: {|
          data: mixed,
          hasNext: boolean,
          hasPrevious: boolean,
          refetchVariables: Variables,
          refetchQuery?: OperationDescriptor,
          gqlRefetchQuery?: $FlowFixMe,
        |},
        flushFallback: boolean = true,
      ) {
        assertYieldsWereCleared();

        TestRenderer.act(() => {
          // Wrap in act to ensure passive effects are run
          jest.runAllImmediates();
        });

        Scheduler.unstable_flushNumberOfYields(1);
        const actualYields = Scheduler.unstable_clearYields();

        if (flushFallback) {
          // Flushing fallbacks by running a timer could cause other side-effects
          // such as releasing retained queries. Until React has a better way to flush
          // fallbacks, we can't test fallbacks and other timeout based effects at the same time.
          jest.runOnlyPendingTimers(); // Tigger fallbacks.

          // Assert component suspendeds
          expect(actualYields.length).toEqual(1);
          expect(actualYields[0]).toEqual('Fallback');
          expect(renderer.toJSON()).toEqual('Fallback');
        }

        // Assert refetch query was fetched
        expectRefetchRequestIsInFlight({
          ...expected,
          inFlight: true,
          requestCount: 1,
        });

        // Assert query is retained by loadQuery
        // and tentatively retained while component is suspended
        // $FlowFixMe[method-unbinding] added when improving typing for this parameters
        expect(environment.retain).toBeCalledTimes(2);
        // $FlowFixMe[method-unbinding] added when improving typing for this parameters
        expect(environment.retain.mock.calls[0][0]).toEqual(
          expected.refetchQuery,
        );
      }

      it('loads more items correctly after refetching', () => {
        const renderer = renderFragment();
        expectFragmentResults([
          {
            data: initialUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);

        refetch({isViewerFriendLocal: true, orderby: ['lastname']});

        // Assert that fragment is refetching with the right variables and
        // suspends upon refetch
        const refetchVariables = {
          after: null,
          first: 1,
          before: null,
          last: null,
          id: '1',
          isViewerFriendLocal: true,
          orderby: ['lastname'],
        };
        paginationQuery = createOperationDescriptor(
          gqlPaginationQuery,
          refetchVariables,
          {force: true},
        );
        expectFragmentSuspendedOnRefetch(
          renderer,
          {
            data: initialUser,
            hasNext: true,
            hasPrevious: false,
            refetchVariables,
            refetchQuery: paginationQuery,
          },
          false,
        );

        // Mock network response
        environment.mock.resolve(gqlPaginationQuery, {
          data: {
            node: {
              __typename: 'User',
              id: '1',
              name: 'Alice',
              friends: {
                edges: [
                  {
                    cursor: 'cursor:100',
                    node: {
                      __typename: 'User',
                      id: 'node:100',
                      name: 'name:node:100',
                      username: 'username:node:100',
                    },
                  },
                ],
                pageInfo: {
                  endCursor: 'cursor:100',
                  hasNextPage: true,
                  hasPreviousPage: false,
                  startCursor: 'cursor:100',
                },
              },
            },
          },
        });

        // Assert fragment is rendered with new data
        const expectedUser = {
          id: '1',
          name: 'Alice',
          friends: {
            edges: [
              {
                cursor: 'cursor:100',
                node: {
                  __typename: 'User',
                  id: 'node:100',
                  name: 'name:node:100',
                  ...createFragmentRef('node:100', paginationQuery),
                },
              },
            ],
            pageInfo: {
              endCursor: 'cursor:100',
              hasNextPage: true,
              hasPreviousPage: false,
              startCursor: 'cursor:100',
            },
          },
        };

        jest.runAllImmediates();
        expectFragmentResults([
          {
            data: expectedUser,
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);

        // Assert refetch query was retained by loadQuery and component
        expect(release).not.toBeCalled();
        // $FlowFixMe[method-unbinding] added when improving typing for this parameters
        expect(environment.retain).toBeCalledTimes(2);
        // $FlowFixMe[method-unbinding] added when improving typing for this parameters
        expect(environment.retain.mock.calls[0][0]).toEqual(paginationQuery);

        // Paginate after refetching
        // $FlowFixMe[method-unbinding] added when improving typing for this parameters
        environment.execute.mockClear();
        loadNext(1);

        const paginationVariables = {
          id: '1',
          after: 'cursor:100',
          first: 1,
          before: null,
          last: null,
          isViewerFriendLocal: true,
          orderby: ['lastname'],
        };
        expectFragmentIsPendingOnPagination(renderer, 'forward', {
          data: expectedUser,
          hasNext: true,
          hasPrevious: false,
          paginationVariables,
        });

        environment.mock.resolve(gqlPaginationQuery, {
          data: {
            node: {
              __typename: 'User',
              id: '1',
              name: 'Alice',
              friends: {
                edges: [
                  {
                    cursor: 'cursor:200',
                    node: {
                      __typename: 'User',
                      id: 'node:200',
                      name: 'name:node:200',
                      username: 'username:node:200',
                    },
                  },
                ],
                pageInfo: {
                  startCursor: 'cursor:200',
                  endCursor: 'cursor:200',
                  hasNextPage: true,
                  hasPreviousPage: true,
                },
              },
            },
          },
        });

        const paginatedUser = {
          ...expectedUser,
          friends: {
            ...expectedUser.friends,
            edges: [
              {
                cursor: 'cursor:100',
                node: {
                  __typename: 'User',
                  id: 'node:100',
                  name: 'name:node:100',
                  ...createFragmentRef('node:100', paginationQuery),
                },
              },
              {
                cursor: 'cursor:200',
                node: {
                  __typename: 'User',
                  id: 'node:200',
                  name: 'name:node:200',
                  ...createFragmentRef('node:200', paginationQuery),
                },
              },
            ],
            pageInfo: {
              endCursor: 'cursor:200',
              hasNextPage: true,
              hasPreviousPage: false,
              startCursor: 'cursor:100',
            },
          },
        };
        expectFragmentResults([
          {
            data: paginatedUser,
            // Assert pending flag is set back to false
            isPendingNext: false,
            hasNext: true,
            hasPrevious: false,
          },
        ]);
      });
    });
  }
});